repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
bulletcms/bullet-sabot
src/middleware/index.js
132
import {Authenticator} from './authentication'; import {CacheControl} from './cacheControl'; export {Authenticator, CacheControl};
mpl-2.0
csegames/Camelot-Unchained
game/camelotunchained/hud/src/index.tsx
2913
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import 'font-awesome/css/font-awesome.css'; import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import 'ol/ol.css'; import './third-party/animate.css'; import './third-party/toastr.min.css'; import './index.css'; import './services/types'; // TODO: AUDIT IF WE NEED THESE import 'core-js/es6/map'; import 'core-js/es6/weak-map'; import 'core-js/es6/set'; // --------------------- import '@csegames/library/lib/_baseGame'; import '@csegames/library/lib/camelotunchained'; import { regMap } from '@csegames/library/lib/_baseGame/engineEvents'; import { CoherentEventHandle } from '@csegames/library/lib/_baseGame/coherent'; import initialize from './services/initialization'; import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Provider } from 'react-redux'; import { ErrorBoundary } from 'cseshared/components/ErrorBoundary'; import { HUDView } from 'hud/index'; import { store } from './services/session/reducer'; import './services/session/UIContext'; import { GlobalProviders } from './components/context'; if (process.env.CUUI_HUD_ENABLE_WHY_DID_YOU_UPDATE) { // tslint:disable const { whyDidYouUpdate } = require('why-did-you-update'); whyDidYouUpdate(React); // tslint:enable } // Catch any events that come through before the readyCheck is finished and fire them once we're ready and mounted. let engineEventQueue = {}; let eventQueueHandles: { [eventName: string]: CoherentEventHandle } = {}; Object.keys(regMap).forEach((eventName) => { const handle = engine.on(eventName, (...args) => { if (engineEventQueue[eventName]) { engineEventQueue[eventName].push(args); } else { engineEventQueue[eventName] = [args]; } }); eventQueueHandles[eventName] = handle; }); function fireEventQueue() { setTimeout(() => { Object.keys(engineEventQueue).forEach((eventQueued) => { engineEventQueue[eventQueued].forEach((args: any[]) => { engine.trigger(eventQueued, ...args); }); }); Object.keys(eventQueueHandles).forEach((eventName) => { eventQueueHandles[eventName].clear(); }); engineEventQueue = null; eventQueueHandles = null; }, 500); } function readyCheck() { if ((!camelotunchained.game.selfPlayerState.characterID || camelotunchained.game.selfPlayerState.characterID === 'unknown') && game.isClientAttached) { setTimeout(readyCheck, 20); return; } initialize(); ReactDom.render( <Provider store={store}> <ErrorBoundary outputErrorToConsole> <GlobalProviders> <HUDView /> </GlobalProviders> </ErrorBoundary> </Provider>, document.getElementById('hud'), fireEventQueue); } readyCheck();
mpl-2.0
danieldc/hooky
models/account.go
2811
package models import ( "math/rand" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // Account is an account to access the service. type Account struct { // ID is the ID of the Account. ID bson.ObjectId `bson:"_id"` // Name is display name for the Account. Name *string `bson:"name,omitempty"` // Key is the secret key to authenticate the Account ID. Key string `bson:"key"` // Deleted Deleted bool `bson:"deleted"` } // NewAccount creates a new Account. func (b *Base) NewAccount(name *string) (account *Account, err error) { account = &Account{ ID: bson.NewObjectId(), Name: name, Key: randKey(32), } err = b.db.C("accounts").Insert(account) return } // UpdateAccount updates an Account. func (b *Base) UpdateAccount(accountID bson.ObjectId, name *string) (account *Account, err error) { if name == nil { return b.GetAccount(accountID) } change := mgo.Change{ Update: bson.M{ "$set": bson.M{ "name": name, }, }, ReturnNew: true, } query := bson.M{ "_id": accountID, } account = &Account{} _, err = b.db.C("accounts").Find(query).Apply(change, account) return } // GetAccount returns an Account given its ID. func (b *Base) GetAccount(accountID bson.ObjectId) (account *Account, err error) { query := bson.M{ "_id": accountID, "deleted": false, } account = &Account{} err = b.db.C("accounts").Find(query).One(account) if err == mgo.ErrNotFound { err = nil account = nil } return } // DeleteAccount deletes an Account given its ID. func (b *Base) DeleteAccount(account bson.ObjectId) (err error) { update := bson.M{ "$set": bson.M{ "deleted": true, }, } err = b.db.C("accounts").UpdateId(account, update) if err == nil { query := bson.M{ "account": account, } if _, err = b.db.C("applications").UpdateAll(query, update); err == nil { if _, err = b.db.C("queues").UpdateAll(query, update); err == nil { if _, err = b.db.C("tasks").UpdateAll(query, update); err == nil { _, err = b.db.C("attempts").UpdateAll(query, update) } } } } return } // GetAccounts returns a list of Accounts. func (b *Base) GetAccounts(lp ListParams, lr *ListResult) (err error) { query := bson.M{ "deleted": false, } return b.getItems("accounts", query, lp, lr) } //AuthenticateAccount authenticates an Account. func (b *Base) AuthenticateAccount(account bson.ObjectId, key string) (bool, error) { query := bson.M{ "_id": account, "key": key, "deleted": false, } n, err := b.db.C("accounts").Find(query).Count() if err != nil { return false, err } return n == 1, nil } var chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") func randKey(n int) string { b := make([]rune, n) for i := range b { b[i] = chars[rand.Intn(len(chars))] } return string(b) }
mpl-2.0
seedstack/samples
full-apps/ddd/src/main/java/org/seedstack/samples/ddd/domain/model/cargo/Leg.java
1770
/* * Copyright © 2013-2018, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.samples.ddd.domain.model.cargo; import java.util.Date; import dev.morphia.annotations.Embedded; import org.apache.commons.lang3.Validate; import org.seedstack.business.domain.BaseValueObject; import org.seedstack.samples.ddd.domain.model.location.UnLocode; import org.seedstack.samples.ddd.domain.model.voyage.VoyageNumber; /** * An itinerary consists of one or more legs. */ @Embedded public class Leg extends BaseValueObject { private VoyageNumber voyage; private UnLocode loadLocation; private UnLocode unloadLocation; private Date loadTime; private Date unloadTime; private Leg() { // required by persistence } public Leg(VoyageNumber voyage, UnLocode loadLocation, UnLocode unloadLocation, Date loadTime, Date unloadTime) { Validate.noNullElements(new Object[]{voyage, loadLocation, unloadLocation, loadTime, unloadTime}); this.voyage = voyage; this.loadLocation = loadLocation; this.unloadLocation = unloadLocation; this.loadTime = loadTime; this.unloadTime = unloadTime; } public VoyageNumber voyage() { return voyage; } public UnLocode loadLocation() { return loadLocation; } public UnLocode unloadLocation() { return unloadLocation; } public Date loadTime() { return new Date(loadTime.getTime()); } public Date unloadTime() { return new Date(unloadTime.getTime()); } }
mpl-2.0
dominikstanojevic/InteraktivniVHDL
src/main/java/hr/fer/zemris/java/vhdl/models/mappers/PositionalMap.java
559
package hr.fer.zemris.java.vhdl.models.mappers; import java.util.List; import java.util.Objects; /** * Created by Dominik on 22.8.2016.. */ public class PositionalMap extends EntityMap { private List<Mappable> signals; public PositionalMap(String label, String entity, List<Mappable> signals) { super(label, entity); Objects.requireNonNull(signals, "List of mapped signals cannot be null."); this.signals = signals; } public List<Mappable> getSignals() { return signals; } @Override public int mapSize() { return signals.size(); } }
mpl-2.0
oracle/terraform-provider-baremetal
oci/blockchain_blockchain_platforms_data_source.go
3702
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. // Licensed under the Mozilla Public License v2.0 package oci import ( "context" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" oci_blockchain "github.com/oracle/oci-go-sdk/v46/blockchain" ) func init() { RegisterDatasource("oci_blockchain_blockchain_platforms", BlockchainBlockchainPlatformsDataSource()) } func BlockchainBlockchainPlatformsDataSource() *schema.Resource { return &schema.Resource{ Read: readBlockchainBlockchainPlatforms, Schema: map[string]*schema.Schema{ "filter": dataSourceFiltersSchema(), "compartment_id": { Type: schema.TypeString, Required: true, }, "display_name": { Type: schema.TypeString, Optional: true, }, "state": { Type: schema.TypeString, Optional: true, }, "blockchain_platform_collection": { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "items": { Type: schema.TypeList, Computed: true, Elem: GetDataSourceItemSchema(BlockchainBlockchainPlatformResource()), }, }, }, }, }, } } func readBlockchainBlockchainPlatforms(d *schema.ResourceData, m interface{}) error { sync := &BlockchainBlockchainPlatformsDataSourceCrud{} sync.D = d sync.Client = m.(*OracleClients).blockchainPlatformClient() return ReadResource(sync) } type BlockchainBlockchainPlatformsDataSourceCrud struct { D *schema.ResourceData Client *oci_blockchain.BlockchainPlatformClient Res *oci_blockchain.ListBlockchainPlatformsResponse } func (s *BlockchainBlockchainPlatformsDataSourceCrud) VoidState() { s.D.SetId("") } func (s *BlockchainBlockchainPlatformsDataSourceCrud) Get() error { request := oci_blockchain.ListBlockchainPlatformsRequest{} if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok { tmp := compartmentId.(string) request.CompartmentId = &tmp } if displayName, ok := s.D.GetOkExists("display_name"); ok { tmp := displayName.(string) request.DisplayName = &tmp } if state, ok := s.D.GetOkExists("state"); ok { request.LifecycleState = oci_blockchain.BlockchainPlatformLifecycleStateEnum(state.(string)) } request.RequestMetadata.RetryPolicy = getRetryPolicy(false, "blockchain") response, err := s.Client.ListBlockchainPlatforms(context.Background(), request) if err != nil { return err } s.Res = &response request.Page = s.Res.OpcNextPage for request.Page != nil { listResponse, err := s.Client.ListBlockchainPlatforms(context.Background(), request) if err != nil { return err } s.Res.Items = append(s.Res.Items, listResponse.Items...) request.Page = listResponse.OpcNextPage } return nil } func (s *BlockchainBlockchainPlatformsDataSourceCrud) SetData() error { if s.Res == nil { return nil } s.D.SetId(GenerateDataSourceHashID("BlockchainBlockchainPlatformsDataSource-", BlockchainBlockchainPlatformsDataSource(), s.D)) resources := []map[string]interface{}{} blockchainPlatform := map[string]interface{}{} items := []interface{}{} for _, item := range s.Res.Items { items = append(items, BlockchainPlatformSummaryToMap(item)) } blockchainPlatform["items"] = items if f, fOk := s.D.GetOkExists("filter"); fOk { items = ApplyFiltersInCollection(f.(*schema.Set), items, BlockchainBlockchainPlatformsDataSource().Schema["blockchain_platform_collection"].Elem.(*schema.Resource).Schema) blockchainPlatform["items"] = items } resources = append(resources, blockchainPlatform) if err := s.D.Set("blockchain_platform_collection", resources); err != nil { return err } return nil }
mpl-2.0
code4romania/anabi-gestiune-api
Anabi.Integration.Tests/Assets/GetAssetAddressTests.cs
3098
using Anabi.Common.ViewModels; using Anabi.Integration.Tests.Helpers; using Newtonsoft.Json; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; namespace Anabi.Integration.Tests.Assets { public class GetAssetAddressTests : ApiTests { public AddMinimalAssetHelper _minimalAssetHelper { get; } public AddAddressToAssetHelper _addAddressToAssetHelper { get; } public GetAssetAddressTests(AnabiApplicationFactory<Startup> factory) : base(factory) { Context = new AnabiDbContextBuilder() .CreateInMemorySqliteDbContext() .WithCounties() .WithStages() .WithAssetCategories() .Build(); Client = factory.CreateClient(); _minimalAssetHelper = new AddMinimalAssetHelper(Context, Client); _addAddressToAssetHelper = new AddAddressToAssetHelper(Context, Client); } [Fact] public async Task GetAssetAddress_ReturnsViewModel() { var assetId = await AddMinimalAsset(); var addressModel = await AddAddressToAsset(assetId); var response = await Client.GetAsync($"api/assets/{assetId}/address"); var data = await response.Content.ReadAsStringAsync(); var viewModel = JsonConvert.DeserializeObject<AddressViewModel>(data); Assert.Equal(addressModel.CountyId, viewModel.CountyId); Assert.Equal(addressModel.City, viewModel.City); Assert.Equal(addressModel.Street, viewModel.Street); } [Fact] public async Task GetAssetAddress_ReturnsEmptyViewModel() { var assetId = await AddMinimalAsset(); var response = await Client.GetAsync($"api/assets/{assetId}/address"); response.EnsureSuccessStatusCode(); var data = await response.Content.ReadAsStringAsync(); var viewModel = JsonConvert.DeserializeObject<AddressViewModel>(data); Assert.NotNull(viewModel); } [Theory] [InlineData(0)] [InlineData(int.MinValue)] public async Task GetAssetAddress_AssetIdZero_ValidationFail_BadRequest(int assetId) { var response = await Client.GetAsync($"api/assets/{assetId}/address"); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task GetAssetAddress_AssetIdNotExists_ValidationFail_BadRequest() { await AddMinimalAsset(); var id = Context.Assets.Max(a => a.Id) + 1; var response = await Client.GetAsync($"api/assets/{id}/address"); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } private Task<int> AddMinimalAsset() { return _minimalAssetHelper.AddMinimalAsset(); } private Task<AddressViewModel> AddAddressToAsset(int assetId) { return _addAddressToAssetHelper.AddAddressToAsset(assetId); } } }
mpl-2.0
joyent/smartos-image-tests
spec/apache/services_spec.rb
201
require 'spec_helper' describe service('apache') do it { should be_enabled } it { should be_running } end describe service('php-fpm') do it { should be_enabled } it { should be_running } end
mpl-2.0
susaing/doc.servo.org
url/percent_encoding/encode_sets/sidebar-items.js
144
initSidebarItems({"static":[["DEFAULT",""],["FORM_URLENCODED",""],["PASSWORD",""],["QUERY",""],["SIMPLE",""],["USERINFO",""],["USERNAME",""]]});
mpl-2.0
cliqz-oss/jsengine
jsengine-android/jsengine/src/main/java/com/cliqz/jsengine/v8/V8Engine.java
6805
package com.cliqz.jsengine.v8; import android.util.Log; import com.eclipsesource.v8.V8; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Contain for V8 Javascript runtime. * <p> * Manages interaction and threading */ public class V8Engine implements JSEngine { private static final String TAG = V8Engine.class.getSimpleName(); private V8 v8; private final BlockingQueue<FutureTask<?>> queries = new LinkedBlockingQueue<>(); private final Thread v8Thread; private final List<Query> shutdownHooks = new LinkedList<>(); private boolean shutdown = false; boolean suppressShutdownCrash = true; final ExecutorService workerService; public V8Engine() { v8Thread = new Thread(new Runnable() { @Override public void run() { v8 = V8.createV8Runtime(); // Executor loop: take and process queries offered to the queue while (!shutdown || !queries.isEmpty()) { try { FutureTask<?> task = queries.take(); task.run(); } catch (InterruptedException e) { Log.e(TAG, "Task timeout", e); } } try { v8.release(); } catch(IllegalStateException e) { // caused by memory leak on shutdown if (!suppressShutdownCrash) { throw e; } } } }); v8Thread.start(); workerService = Executors.newFixedThreadPool(1); } public boolean isOnV8Thread() { return Thread.currentThread().equals(this.v8Thread); } public void shutdown() { shutdown(false); } public void shutdown(boolean strict) { // for a strict shutdown we crash if memory was leaked suppressShutdownCrash = !strict; // release JS engine resources and shutdown executor thread. Log.w(TAG, "V8 shutdown"); for(Query q : shutdownHooks) { try { queryEngine(q); } catch (InterruptedException | ExecutionException | TimeoutException e) { Log.e(TAG, "Exception in shutdown hook", e); } } shutdownHooks.clear(); shutdown = true; workerService.shutdown(); try { workerService.awaitTermination(10000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { if (!suppressShutdownCrash) { throw new RuntimeException(e); } else { Log.e(TAG, "Could not shutdown worker", e); } } try { // submit a task to force-wake v8 thread. asyncQuery(new Query<Object>() { public Object query(V8 runtime) { return null; } }); v8Thread.join(); } catch (Exception e) { } } public void registerShutdownHook(Query onShutdown) { shutdownHooks.add(onShutdown); } /** * Asynchronous task to be run on the javascript engine. * * @param <V> Return type of the query */ public interface Query<V> { /** * Query the javascript engine and return a result value * * @param runtime * @return */ V query(V8 runtime); } public <V> V queryEngine(final Query<V> q) throws InterruptedException, ExecutionException, TimeoutException { return queryEngine(q, 0); } public <V> V queryEngine(final Query<V> q, final int msTimeout) throws InterruptedException, ExecutionException, TimeoutException { return queryEngine(q, msTimeout, false); } /** * Send a Query to the javascript engine. * <p/> * May be called from any thread. The task is safely submitted to the v8 thread, which processes * the query in turn, at which point this function will return the result. * * @param q A Query containing calls to be run on the v8 thread, and a possible return value * @param msTimeout an integer timeout in MS for this query. If there is no result within this time at TimeoutException is thrown. If the timeout is 0, the query will never timeout * @param <V> The return type of the query * @return The value returned from the query * @throws InterruptedException * @throws ExecutionException * @throws TimeoutException if the query blocks for more than msTimeout ms. */ public <V> V queryEngine(final Query<V> q, final int msTimeout, final boolean async) throws InterruptedException, ExecutionException, TimeoutException { FutureTask<V> future = new FutureTask<V>(new Callable<V>() { @Override public V call() throws Exception { return q.query(v8); } }); queries.add(future); if (async) { return null; } if (msTimeout > 0) { try { return future.get(msTimeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { future.cancel(true); throw e; } } else { return future.get(); } } /** * Submit a Query to the javscript engine without blocking. * * @param q A Query containing calls to be run on the v8 thread * @throws InterruptedException * @throws ExecutionException */ public void asyncQuery(final Query<?> q) throws InterruptedException, ExecutionException { try { queryEngine(q, 0, true); } catch (TimeoutException e) { // this shouldn't be possible } } public void executeScript(final String javascript) throws ExecutionException { try { asyncQuery(new Query<Object>() { @Override public Object query(V8 runtime) { runtime.executeVoidScript(javascript); return null; } }); } catch (InterruptedException e) { Log.e(TAG, "Error executing Javascript", e); } } public ExecutorService getWorker() { return workerService; } }
mpl-2.0
Nutomic/ensichat
integration/src/main/scala/com.nutomic.ensichat.integration/LocalNode.scala
2720
package com.nutomic.ensichat.integration import java.io.File import java.util.concurrent.LinkedBlockingQueue import com.nutomic.ensichat.core.interfaces.{CallbackInterface, SettingsInterface} import com.nutomic.ensichat.core.messages.Message import com.nutomic.ensichat.core.util.{Crypto, Database} import com.nutomic.ensichat.core.ConnectionHandler import com.nutomic.ensichat.integration.LocalNode._ import scala.concurrent.Await import scala.concurrent.duration.Duration import scalax.file.Path object LocalNode { private final val StartingPort = 21000 object EventType extends Enumeration { type EventType = Value val MessageReceived, ConnectionsChanged, ContactsUpdated = Value } class FifoStream[A]() { private val queue = new LinkedBlockingQueue[Option[A]]() def toStream: Stream[A] = queue.take match { case Some(a) => Stream.cons(a, toStream) case None => Stream.empty } def close() = queue add None def enqueue(a: A) = queue.put(Option(a)) } } /** * Runs an ensichat node on localhost. * * Received messages can be accessed through [[eventQueue]]. * * @param index Number of this node. The server port is opened on port [[StartingPort]] + index. * @param configFolder Folder where keys and configuration should be stored. */ class LocalNode(val index: Int, configFolder: File) extends CallbackInterface { private val databaseFile = new File(configFolder, "database") private val keyFolder = new File(configFolder, "keys") private val settings = new SettingsInterface { private var values = Map[String, Any]() override def get[T](key: String, default: T): T = values.get(key).map(_.asInstanceOf[T]).getOrElse(default) override def put[T](key: String, value: T): Unit = values += (key -> value.asInstanceOf[Any]) } val crypto = new Crypto(settings, keyFolder) val database = new Database(databaseFile, settings, this) val connectionHandler = new ConnectionHandler(settings, database, this, crypto, port) val eventQueue = new FifoStream[(EventType.EventType, Option[Message])]() configFolder.mkdirs() keyFolder.mkdirs() settings.put(SettingsInterface.KeyAddresses, "") Await.result(connectionHandler.start(), Duration.Inf) def port = StartingPort + index def stop(): Unit = { connectionHandler.stop() Path(configFolder).deleteRecursively() } def onMessageReceived(msg: Message): Unit = { eventQueue.enqueue((EventType.MessageReceived, Option(msg))) } def onConnectionsChanged(): Unit = eventQueue.enqueue((EventType.ConnectionsChanged, None)) def onContactsUpdated(): Unit = eventQueue.enqueue((EventType.ContactsUpdated, None)) }
mpl-2.0
MitocGroup/deep-framework
src/deep-event/lib/Driver/AbstractDriver.js
1087
/** * Created by AlexanderC on 2/22/17. */ 'use strict'; export class AbstractDriver { /** * @param {*} context */ constructor(context) { this._context = context; } /** * @returns {*} */ get context() { return this._context; } /** * @param {String} name * @param {*} data * @param {*} context * * @returns {Promise|*} */ log(name, data, context = {}) { return this._log( name, data, this.context.enrichEventContext(context) ); } /** * @param {String} name * @param {*} data * @param {*} context * * @returns {Promise|*} * * @private */ _printEvent(name, data, context) { console.log('[EVENT]', name, '{DATA->', data , '}', '{CONTEXT->', context, '}'); return Promise.resolve(); } /** * @param {String} name * @param {*} data * @param {Object} context * * @returns {Promise|*} * * @private */ _log(name, data, context) { return Promise.reject(new Error(`Driver._log() not implemented!`)); } }
mpl-2.0
openMF/self-service-app
app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.java
6952
package org.mifos.mobile.ui.fragments; /* * Created by saksham on 23/July/2018 */ import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; import org.mifos.mobile.R; import org.mifos.mobile.models.guarantor.GuarantorPayload; import org.mifos.mobile.presenters.GuarantorListPresenter; import org.mifos.mobile.ui.activities.base.BaseActivity; import org.mifos.mobile.ui.adapters.GuarantorListAdapter; import org.mifos.mobile.ui.enums.GuarantorState; import org.mifos.mobile.ui.fragments.base.BaseFragment; import org.mifos.mobile.ui.views.GuarantorListView; import org.mifos.mobile.utils.Constants; import org.mifos.mobile.utils.DateHelper; import org.mifos.mobile.utils.RxBus; import org.mifos.mobile.utils.RxEvent; import java.util.List; import javax.inject.Inject; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; public class GuarantorListFragment extends BaseFragment implements GuarantorListView { @BindView(R.id.layout_error) View layoutError; @BindView(R.id.ll_container) LinearLayout llContainer; @BindView(R.id.rv_guarantors) RecyclerView rvGuarantors; @Inject GuarantorListPresenter presenter; GuarantorListAdapter adapter; View rootView; long loanId; SweetUIErrorHandler sweetUIErrorHandler; List<GuarantorPayload> list; Disposable disposableAddGuarantor, disposableDeleteGuarantor; public static GuarantorListFragment newInstance(long loanId) { GuarantorListFragment fragment = new GuarantorListFragment(); Bundle args = new Bundle(); args.putLong(Constants.LOAN_ID, loanId); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { loanId = getArguments().getLong(Constants.LOAN_ID); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_guarantor_list, container, false); ButterKnife.bind(this, rootView); setToolbarTitle(getString(R.string.view_guarantor)); ((BaseActivity) getActivity()).getActivityComponent().inject(this); presenter.attachView(this); if (list == null) { presenter.getGuarantorList(loanId); adapter = new GuarantorListAdapter(getContext(), new GuarantorListAdapter.OnClickListener() { @Override public void setOnClickListener(int position) { ((BaseActivity) getActivity()).replaceFragment(GuarantorDetailFragment .newInstance(position, loanId, list.get(position)), true, R.id.container); } }); setUpRxBus(); } sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (list != null && list.size() == 0) { sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.no_guarantors), getString(R.string.tap_to_add_guarantor), R.drawable.ic_person_black_24dp, llContainer, layoutError); } rvGuarantors.setAdapter(adapter); rvGuarantors.setLayoutManager(new LinearLayoutManager(getContext())); } private void setUpRxBus() { disposableAddGuarantor = RxBus.listen(RxEvent.AddGuarantorEvent.class) .subscribe(new Consumer<RxEvent.AddGuarantorEvent>() { @Override public void accept(RxEvent.AddGuarantorEvent event) throws Exception { //TODO wrong guarantor id is assigned, although it wont affect the working list.add(event.getIndex(), new GuarantorPayload(list.size(), event.getPayload().getOfficeName(), event.getPayload().getLastName(), event.getPayload().getGuarantorType(), event.getPayload().getFirstName(), DateHelper.getCurrentDate("yyyy-MM-dd", "-"), loanId)); adapter.setGuarantorList(list); } }); disposableDeleteGuarantor = RxBus.listen(RxEvent.DeleteGuarantorEvent.class) .subscribe(new Consumer<RxEvent.DeleteGuarantorEvent>() { @Override public void accept(RxEvent.DeleteGuarantorEvent deleteGuarantorEvent) throws Exception { int index = deleteGuarantorEvent.getIndex(); list.remove(index); adapter.setGuarantorList(list); } }); } @OnClick(R.id.fab_add_loan_guarantor) void addGuarantor() { ((BaseActivity) getActivity()).replaceFragment(AddGuarantorFragment .newInstance(0, GuarantorState.CREATE, null, loanId), true, R.id.container); } @Override public void showProgress() { showProgressBar(); } @Override public void hideProgress() { hideProgressBar(); } @Override public void showGuarantorListSuccessfully(final List<GuarantorPayload> list) { this.list = list; if (list.size() == 0) { sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.no_guarantors), getString(R.string.tap_to_add_guarantor), R.drawable.ic_person_black_24dp, llContainer, layoutError); } else { adapter.setGuarantorList(list); } } @Override public void showError(String message) { } @Override public void onDestroy() { super.onDestroy(); presenter.detachView(); if (!disposableAddGuarantor.isDisposed()) { disposableAddGuarantor.dispose(); } if (!disposableDeleteGuarantor.isDisposed()) { disposableDeleteGuarantor.dispose(); } hideProgress(); } }
mpl-2.0
yonadev/yona-app-android
app/src/test/java/nu/yona/app/ui/signup/StepOneTest.java
3004
/* * Copyright (c) 2016 Stichting Yona Foundation * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * */ package nu.yona.app.ui.signup; import android.content.Intent; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import nu.yona.app.R; import nu.yona.app.YonaApplication; import nu.yona.app.YonaTestCase; import nu.yona.app.api.db.DatabaseHelper; import nu.yona.app.api.manager.APIManager; import nu.yona.app.api.manager.AuthenticateManager; import nu.yona.app.customview.YonaFontEditTextView; import nu.yona.app.utils.AppConstant; /** * Created by kinnarvasa on 31/03/16. */ public class StepOneTest extends YonaTestCase { private StepOne stepOneFragment; private String name; private SignupActivity activity; private YonaFontEditTextView firstName, lastName; private View view; private AuthenticateManager authenticateManager; DatabaseHelper dbhelper = DatabaseHelper.getInstance(RuntimeEnvironment.application); @Before public void setup() { if(activity == null){ String uri = YonaApplication.getAppContext().getString(R.string.server_url); Intent intent = new Intent(Intent.ACTION_VIEW).putExtra(AppConstant.DEEP_LINK, uri); activity = Robolectric.buildActivity(SignupActivity.class, intent) .create() .start() .resume() .get(); } if(view == null){ StepOne stepOne = new StepOne(); FragmentManager fragmentManager = activity.getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(stepOne, null); fragmentTransaction.commit(); view = stepOne.getView(); firstName = (YonaFontEditTextView) view.findViewById(R.id.first_name); } if(authenticateManager == null){ authenticateManager = APIManager.getInstance().getAuthenticateManager(); } } @Test public void validateFirstName(){ firstName.setText("Kinnar"); assertTrue(authenticateManager.validateText(firstName.getText().toString())); } @Test public void validateEmptyFirstName() { firstName.setText(""); assertFalse(authenticateManager.validateText(firstName.getText().toString())); } @Test public void validateNullFirstName() { firstName.setText(""); assertNotNull(authenticateManager.validateText(null)); } @After public void tearDown() { dbhelper.close(); } }
mpl-2.0
gozer/voice-web
web/src/components/pages/home/stats.tsx
9544
const spline = require('@yr/monotone-cubic-spline'); import { LocalizationProps, Localized, withLocalization, } from 'fluent-react/compat'; import * as React from 'react'; import { useState } from 'react'; import { connect } from 'react-redux'; import API from '../../../services/api'; import { trackHome } from '../../../services/tracker'; import StateTree from '../../../stores/tree'; import LanguageSelect, { ALL_LOCALES, } from '../../language-select/language-select'; import Plot, { BarPlot, LINE_OFFSET, PLOT_PADDING, TOTAL_LINE_MARGIN, Y_OFFSET, } from '../../plot/plot'; import './stats.css'; const { Tooltip } = require('react-tippy'); const PLOT_STROKE_WIDTH = 2; type Attribute = 'total' | 'valid'; interface State { locale: string; } function StatsCard({ children, onLocaleChange, header, }: { children?: React.ReactNode; header: React.ReactNode; onLocaleChange: (locale: string) => any; }) { const [locale, setLocale] = useState(ALL_LOCALES); return ( <div className="home-card"> <div className="head"> {header} <LanguageSelect value={locale} onChange={locale => { trackHome('metric-locale-change', locale); setLocale(locale); onLocaleChange(locale == ALL_LOCALES ? null : locale); }} /> </div> {children} </div> ); } interface PropsFromState { api: API; } const mapStateToProps = ({ api }: StateTree) => ({ api, }); export namespace ClipsStats { const DATA_LENGTH = 5; const TICK_COUNT = 7; const CIRCLE_RADIUS = 8; function formatSeconds(totalSeconds: number, precise: boolean = false) { const seconds = totalSeconds % 60; const minutes = Math.floor(totalSeconds / 60) % 60; const hours = Math.floor(totalSeconds / 3600); if (precise) return `${hours.toLocaleString()}h`; if (hours >= 1000) { return (hours / 1000).toPrecision(2) + 'k'; } const timeParts = []; if (hours > 0) { timeParts.push(hours + 'h'); } if (hours < 10 && minutes > 0) { timeParts.push(minutes + 'm'); } if (hours == 0 && minutes < 10 && seconds > 0) { timeParts.push(seconds + 's'); } return timeParts.join(' ') || '0'; } const MetricValue = ({ attribute, title, children }: any) => ( <div className={'metric-value ' + attribute} title={title}> <div className="point">●</div> {children} </div> ); const Metric = ({ data, labelId, attribute, }: { data: any[]; labelId: string; attribute: Attribute; }) => ( <div className="metric"> <Localized id={labelId}> <div className="label" /> </Localized> <MetricValue attribute={attribute} title={ data.length > 0 ? formatSeconds(data[data.length - 1][attribute], true) : '' }> {data.length > 0 ? formatSeconds(data[data.length - 1][attribute]) : '?'} </MetricValue> </div> ); const Path = React.forwardRef( ( { attribute, data, max, width, }: { attribute: Attribute; data: any[]; max: number; width: number; }, ref: any ) => { if (data.length === 0) return null; const pointFromDatum = (x: number, y: number): [number, number] => [ LINE_OFFSET + PLOT_PADDING + (x * (width - LINE_OFFSET - 2 * PLOT_PADDING - CIRCLE_RADIUS)) / (data.length - 1), Y_OFFSET - PLOT_STROKE_WIDTH / 2 + ((1 - y / max) * (data.length + 1) * TOTAL_LINE_MARGIN) / TICK_COUNT, ]; const lastIndex = data.length - 1; const [x, y] = pointFromDatum(lastIndex, data[lastIndex][attribute]); return ( <React.Fragment> <path d={spline.svgPath( spline.points( data.map((datum: any, i: number) => pointFromDatum(i, datum[attribute]) ) ) )} className={attribute} fill="none" ref={ref} strokeWidth={PLOT_STROKE_WIDTH} /> <circle cx={x} cy={y} r={CIRCLE_RADIUS} fill="white" className={'outer ' + attribute} /> <circle cx={x} cy={y} r={CIRCLE_RADIUS - 2} className={'inner ' + attribute} /> </React.Fragment> ); } ); class BareRoot extends React.Component<LocalizationProps & PropsFromState> { state: { data: any[]; hoveredIndex: number } = { data: [], hoveredIndex: null, }; pathRef: any = React.createRef(); async componentDidMount() { await this.updateData(); } updateData = async (locale?: string) => { this.setState({ data: await this.props.api.fetchClipsStats(locale) }); }; handleMouseMove = (event: any) => { const path = this.pathRef.current; if (!path) { this.setState({ hoveredIndex: null }); } const { left, width } = path.getBoundingClientRect(); const hoveredIndex = Math.round((DATA_LENGTH * (event.clientX - left)) / width) - 1; this.setState({ hoveredIndex: hoveredIndex >= 0 && hoveredIndex < DATA_LENGTH ? hoveredIndex : null, }); }; handleMouseOut = () => this.setState({ hoveredIndex: null }); render() { const { getString } = this.props; const { data, hoveredIndex } = this.state; const datum = data[hoveredIndex]; const { date, total, valid } = datum || ({} as any); const tooltipContents = datum ? ( <React.Fragment> <b> {new Date(date).toLocaleDateString([], { day: 'numeric', month: 'long', year: 'numeric', })} </b> <div className="metrics"> <MetricValue attribute="total">{formatSeconds(total)}</MetricValue> <MetricValue attribute="valid">{formatSeconds(valid)}</MetricValue> </div> </React.Fragment> ) : null; return ( <StatsCard header={ <div className="metrics"> <Metric data={data} labelId="hours-recorded" attribute="total" /> <Metric data={data} labelId="hours-validated" attribute="valid" /> </div> } onLocaleChange={this.updateData}> <Tooltip arrow={true} duration={0} html={tooltipContents} open={Boolean(tooltipContents)} theme="white" followCursor> <Plot data={data} formatNumber={formatSeconds} max={data.reduce( (max: number, d: any) => Math.max(max, d.total, d.valid), 0 )} onMouseMove={this.handleMouseMove} onMouseOut={this.handleMouseOut} renderXTickLabel={({ date }: any) => { const dateObj = new Date(date); const dayDiff = Math.ceil( Math.abs(dateObj.getTime() - new Date().getTime()) / (1000 * 3600 * 24) ); if (dayDiff <= 1) return getString('today'); if (dayDiff < 30) { return getString('x-weeks-short', { count: Math.floor(dayDiff / 7), }); } if (dayDiff < 365) { return getString('x-months-short', { count: Math.floor(dayDiff / 30), }); } return getString('x-years-short', { count: Math.floor(dayDiff / 365), }); }} tickCount={TICK_COUNT} tickMultipliers={[10, 60, 600, 3600, 36000, 360000]}> {state => ( <React.Fragment> <Path attribute="valid" data={data} {...state} /> <Path attribute="total" data={data} {...state} ref={this.pathRef} /> </React.Fragment> )} </Plot> </Tooltip> </StatsCard> ); } } export const Root = connect<PropsFromState>(mapStateToProps)( withLocalization(BareRoot) ); } export const VoiceStats = connect<PropsFromState>(mapStateToProps)( class BareRoot extends React.Component<PropsFromState> { state: { data: any[] } = { data: [] }; async componentDidMount() { await this.updateData(); } updateData = async (locale?: string) => { this.setState({ data: await this.props.api.fetchClipVoices(locale) }); }; render() { const { data } = this.state; return ( <StatsCard header={ <div> <Localized id="voices-online"> <h3 /> </Localized> <div className="online-voices"> {data.length > 0 ? data[data.length - 1].value.toLocaleString() : '?'} </div> </div> } onLocaleChange={this.updateData}> <BarPlot data={data} /> </StatsCard> ); } } );
mpl-2.0
ThesisPlanet/EducationPlatform
src/public/js/libs/dojox/atom/widget/nls/zh/PeopleEditor.js
94
({ add: "添加", addAuthor: "添加作者", addContributor: "添加内容添加者" })
mpl-2.0
sirthias/swave
core/src/main/scala/swave/core/io/ByteArrayBytes.scala
6576
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package swave.core.io import java.io.OutputStream import java.nio.charset.{CharacterCodingException, Charset} import java.nio.{ByteBuffer, CharBuffer} import java.util import scala.annotation.tailrec import scala.collection.GenTraversableOnce import swave.core.macros._ class ByteArrayBytes extends Bytes[Array[Byte]] { ///////////////// CONSTRUCTION /////////////////// def empty = ByteArrayBytes.Empty def fill[A: Integral](size: Long)(byte: A) = { requireArg(0 <= size && size <= Int.MaxValue, "`size` must be >= 0 and <= Int.MaxValue") val b = implicitly[Integral[A]].toInt(byte).toByte val array = new Array[Byte](size.toInt) util.Arrays.fill(array, b) array } def apply(array: Array[Byte]) = array def apply(bytes: Array[Byte], offset: Int, length: Int) = util.Arrays.copyOfRange(bytes, offset, offset + length) def apply[A: Integral](bytes: A*) = { val integral = implicitly[Integral[A]] val buf = new Array[Byte](bytes.size) @tailrec def rec(ix: Int): Array[Byte] = if (ix < buf.length) { buf(ix) = integral.toInt(bytes(ix)).toByte rec(ix + 1) } else buf rec(0) } def apply(bytes: Vector[Byte]) = bytes.toArray def apply(buffer: ByteBuffer) = { val array = new Array[Byte](buffer.remaining) buffer.get(array) array } def apply(bs: GenTraversableOnce[Byte]) = bs.toArray def view(bytes: Array[Byte]) = apply(bytes) // no view-like constructor available for byte arrays def view(bytes: ByteBuffer) = apply(bytes) // no view-like constructor available for byte arrays def encodeString(str: String, charset: Charset) = str getBytes charset def encodeStringStrict(str: String, charset: Charset) = try Right(apply(charset.newEncoder.encode(CharBuffer.wrap(str)))) catch { case e: CharacterCodingException ⇒ Left(e) } ///////////////// QUERY /////////////////// def size(value: Array[Byte]): Long = value.length.toLong def byteAt(value: Array[Byte], ix: Long): Byte = { requireArg(0 <= ix && ix <= Int.MaxValue, "`ix` must be >= 0 and <= Int.MaxValue") value(ix.toInt) } def indexOfSlice(value: Array[Byte], slice: Array[Byte], startIx: Long): Long = { requireArg(0 <= startIx && startIx <= Int.MaxValue, "`startIx` must be >= 0 and <= Int.MaxValue") value.indexOfSlice(slice, startIx.toInt).toLong } ///////////////// TRANSFORMATION TO Array[Byte] /////////////////// def update(value: Array[Byte], ix: Long, byte: Byte) = { requireArg(0 <= ix && ix <= Int.MaxValue, "`ix` must be >= 0 and <= Int.MaxValue") val array = util.Arrays.copyOf(value, value.length) array(ix.toInt) = byte array } def concat(value: Array[Byte], other: Array[Byte]) = if (value.length > 0) { if (other.length > 0) { val len = value.length.toLong + other.length requireArg(0 <= len && len <= Int.MaxValue, "concatenated length must be >= 0 and <= Int.MaxValue") val array = util.Arrays.copyOf(value, len.toInt) System.arraycopy(other, 0, array, value.length, other.length) array } else value } else other def concat(value: Array[Byte], byte: Byte) = { val len = value.length if (value.length > 0) { requireArg(0 <= len && len <= Int.MaxValue - 1, "concatenated length must be >= 0 and <= Int.MaxValue - 1") val array = new Array[Byte](len + 1) System.arraycopy(value, 0, array, 0, len) array(len) = byte array } else singleByteArray(byte) } def concat(byte: Byte, value: Array[Byte]) = { val len = value.length if (value.length > 0) { requireArg(0 <= len && len <= Int.MaxValue - 1, "concatenated length must be >= 0 and <= Int.MaxValue - 1") val array = new Array[Byte](len + 1) System.arraycopy(value, 0, array, 1, len) array(0) = byte array } else singleByteArray(byte) } private def singleByteArray(byte: Byte) = { val array = new Array[Byte](1) array(0) = byte array } def drop(value: Array[Byte], n: Long) = { requireArg(0 <= n && n <= Int.MaxValue, "`n` must be >= 0 and <= Int.MaxValue") if (n > 0) if (n < value.length) util.Arrays.copyOfRange(value, n.toInt, value.length) else empty else value } def take(value: Array[Byte], n: Long) = { requireArg(0 <= n && n <= Int.MaxValue, "`n` must be >= 0 and <= Int.MaxValue") if (n > 0) if (n < value.length) util.Arrays.copyOfRange(value, 0, n.toInt) else value else empty } def map(value: Array[Byte], f: Byte ⇒ Byte) = value.map(f) def reverse(value: Array[Byte]) = value.reverse def compact(value: Array[Byte]) = value ///////////////// TRANSFORMATION TO OTHER TYPES /////////////////// def toArray(value: Array[Byte]) = value def copyToArray(value: Array[Byte], xs: Array[Byte], offset: Int) = System.arraycopy(value, 0, xs, offset, math.max(0, math.min(value.length, xs.length - offset))) def copyToArray(value: Array[Byte], sourceOffset: Long, xs: Array[Byte], destOffset: Int, len: Int) = { requireArg(0 <= sourceOffset && sourceOffset <= Int.MaxValue, "`sourceOffset` must be >= 0 and <= Int.MaxValue") System.arraycopy(value, sourceOffset.toInt, xs, destOffset, len) } def copyToBuffer(value: Array[Byte], buffer: ByteBuffer): Int = { val len = math.min(value.length, buffer.remaining) buffer.put(value) len } def copyToOutputStream(value: Array[Byte], s: OutputStream) = s.write(value) def toByteBuffer(value: Array[Byte]) = ByteBuffer.wrap(value) def toIndexedSeq(value: Array[Byte]): IndexedSeq[Byte] = value def toSeq(value: Array[Byte]): Seq[Byte] = value def decodeString(value: Array[Byte], charset: Charset): Either[CharacterCodingException, String] = try Right(charset.newDecoder.decode(toByteBuffer(value)).toString) catch { case e: CharacterCodingException ⇒ Left(e) } ///////////////// ITERATION /////////////////// def foldLeft[A](value: Array[Byte], z: A, f: (A, Byte) ⇒ A) = value.foldLeft(z)(f) def foldRight[A](value: Array[Byte], z: A, f: (Byte, A) ⇒ A) = value.foldRight(z)(f) def foreach(value: Array[Byte], f: Byte ⇒ Unit) = value.foreach(f) } object ByteArrayBytes { val Empty = new Array[Byte](0) }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
js/src/jit/mips32/Simulator-mips32.cpp
118513
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ // Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "jit/mips32/Simulator-mips32.h" #include "mozilla/Casting.h" #include "mozilla/FloatingPoint.h" #include "mozilla/Likely.h" #include "mozilla/MathAlgorithms.h" #include <float.h> #include "jit/mips32/Assembler-mips32.h" #include "vm/Runtime.h" namespace js { namespace jit { static const Instr kCallRedirInstr = op_special | MAX_BREAK_CODE << FunctionBits | ff_break; // Utils functions. static bool HaveSameSign(int32_t a, int32_t b) { return ((a ^ b) >= 0); } static uint32_t GetFCSRConditionBit(uint32_t cc) { if (cc == 0) { return 23; } else { return 24 + cc; } } static const int32_t kRegisterskMaxValue = 0x7fffffff; static const int32_t kRegisterskMinValue = 0x80000000; // ----------------------------------------------------------------------------- // MIPS assembly various constants. class SimInstruction { public: enum { kInstrSize = 4, // On MIPS PC cannot actually be directly accessed. We behave as if PC was // always the value of the current instruction being executed. kPCReadOffset = 0 }; // Get the raw instruction bits. inline Instr instructionBits() const { return *reinterpret_cast<const Instr*>(this); } // Set the raw instruction bits to value. inline void setInstructionBits(Instr value) { *reinterpret_cast<Instr*>(this) = value; } // Read one particular bit out of the instruction bits. inline int bit(int nr) const { return (instructionBits() >> nr) & 1; } // Read a bit field out of the instruction bits. inline int bits(int hi, int lo) const { return (instructionBits() >> lo) & ((2 << (hi - lo)) - 1); } // Instruction type. enum Type { kRegisterType, kImmediateType, kJumpType, kUnsupported = -1 }; // Get the encoding type of the instruction. Type instructionType() const; // Accessors for the different named fields used in the MIPS encoding. inline Opcode opcodeValue() const { return static_cast<Opcode>(bits(OpcodeShift + OpcodeBits - 1, OpcodeShift)); } inline int rsValue() const { MOZ_ASSERT(instructionType() == kRegisterType || instructionType() == kImmediateType); return bits(RSShift + RSBits - 1, RSShift); } inline int rtValue() const { MOZ_ASSERT(instructionType() == kRegisterType || instructionType() == kImmediateType); return bits(RTShift + RTBits - 1, RTShift); } inline int rdValue() const { MOZ_ASSERT(instructionType() == kRegisterType); return bits(RDShift + RDBits - 1, RDShift); } inline int saValue() const { MOZ_ASSERT(instructionType() == kRegisterType); return bits(SAShift + SABits - 1, SAShift); } inline int functionValue() const { MOZ_ASSERT(instructionType() == kRegisterType || instructionType() == kImmediateType); return bits(FunctionShift + FunctionBits - 1, FunctionShift); } inline int fdValue() const { return bits(FDShift + FDBits - 1, FDShift); } inline int fsValue() const { return bits(FSShift + FSBits - 1, FSShift); } inline int ftValue() const { return bits(FTShift + FTBits - 1, FTShift); } inline int frValue() const { return bits(FRShift + FRBits - 1, FRShift); } // Float Compare condition code instruction bits. inline int fcccValue() const { return bits(FCccShift + FCccBits - 1, FCccShift); } // Float Branch condition code instruction bits. inline int fbccValue() const { return bits(FBccShift + FBccBits - 1, FBccShift); } // Float Branch true/false instruction bit. inline int fbtrueValue() const { return bits(FBtrueShift + FBtrueBits - 1, FBtrueShift); } // Return the fields at their original place in the instruction encoding. inline Opcode opcodeFieldRaw() const { return static_cast<Opcode>(instructionBits() & OpcodeMask); } inline int rsFieldRaw() const { MOZ_ASSERT(instructionType() == kRegisterType || instructionType() == kImmediateType); return instructionBits() & RSMask; } // Same as above function, but safe to call within instructionType(). inline int rsFieldRawNoAssert() const { return instructionBits() & RSMask; } inline int rtFieldRaw() const { MOZ_ASSERT(instructionType() == kRegisterType || instructionType() == kImmediateType); return instructionBits() & RTMask; } inline int rdFieldRaw() const { MOZ_ASSERT(instructionType() == kRegisterType); return instructionBits() & RDMask; } inline int saFieldRaw() const { MOZ_ASSERT(instructionType() == kRegisterType); return instructionBits() & SAMask; } inline int functionFieldRaw() const { return instructionBits() & FunctionMask; } // Get the secondary field according to the opcode. inline int secondaryValue() const { Opcode op = opcodeFieldRaw(); switch (op) { case op_special: case op_special2: return functionValue(); case op_cop1: return rsValue(); case op_regimm: return rtValue(); default: return ff_null; } } inline int32_t imm16Value() const { MOZ_ASSERT(instructionType() == kImmediateType); return bits(Imm16Shift + Imm16Bits - 1, Imm16Shift); } inline int32_t imm26Value() const { MOZ_ASSERT(instructionType() == kJumpType); return bits(Imm26Shift + Imm26Bits - 1, Imm26Shift); } // Say if the instruction should not be used in a branch delay slot. bool isForbiddenInBranchDelay() const; // Say if the instruction 'links'. e.g. jal, bal. bool isLinkingInstruction() const; // Say if the instruction is a break or a trap. bool isTrap() const; private: SimInstruction() = delete; SimInstruction(const SimInstruction& other) = delete; void operator=(const SimInstruction& other) = delete; }; bool SimInstruction::isForbiddenInBranchDelay() const { const int op = opcodeFieldRaw(); switch (op) { case op_j: case op_jal: case op_beq: case op_bne: case op_blez: case op_bgtz: case op_beql: case op_bnel: case op_blezl: case op_bgtzl: return true; case op_regimm: switch (rtFieldRaw()) { case rt_bltz: case rt_bgez: case rt_bltzal: case rt_bgezal: return true; default: return false; }; break; case op_special: switch (functionFieldRaw()) { case ff_jr: case ff_jalr: return true; default: return false; }; break; default: return false; } } bool SimInstruction::isLinkingInstruction() const { const int op = opcodeFieldRaw(); switch (op) { case op_jal: return true; case op_regimm: switch (rtFieldRaw()) { case rt_bgezal: case rt_bltzal: return true; default: return false; }; case op_special: switch (functionFieldRaw()) { case ff_jalr: return true; default: return false; }; default: return false; }; } bool SimInstruction::isTrap() const { if (opcodeFieldRaw() != op_special) { return false; } else { switch (functionFieldRaw()) { case ff_break: case ff_tge: case ff_tgeu: case ff_tlt: case ff_tltu: case ff_teq: case ff_tne: return true; default: return false; }; } } SimInstruction::Type SimInstruction::instructionType() const { switch (opcodeFieldRaw()) { case op_special: switch (functionFieldRaw()) { case ff_jr: case ff_jalr: case ff_break: case ff_sll: case ff_srl: case ff_sra: case ff_sllv: case ff_srlv: case ff_srav: case ff_mfhi: case ff_mflo: case ff_mult: case ff_multu: case ff_div: case ff_divu: case ff_add: case ff_addu: case ff_sub: case ff_subu: case ff_and: case ff_or: case ff_xor: case ff_nor: case ff_slt: case ff_sltu: case ff_tge: case ff_tgeu: case ff_tlt: case ff_tltu: case ff_teq: case ff_tne: case ff_movz: case ff_movn: case ff_movci: return kRegisterType; default: return kUnsupported; }; break; case op_special2: switch (functionFieldRaw()) { case ff_mul: case ff_clz: return kRegisterType; default: return kUnsupported; }; break; case op_special3: switch (functionFieldRaw()) { case ff_ins: case ff_ext: return kRegisterType; default: return kUnsupported; }; break; case op_cop1: // Coprocessor instructions. switch (rsFieldRawNoAssert()) { case rs_bc1: // Branch on coprocessor condition. return kImmediateType; default: return kRegisterType; }; break; case op_cop1x: return kRegisterType; // 16 bits Immediate type instructions. e.g.: addi dest, src, imm16. case op_regimm: case op_beq: case op_bne: case op_blez: case op_bgtz: case op_addi: case op_addiu: case op_slti: case op_sltiu: case op_andi: case op_ori: case op_xori: case op_lui: case op_beql: case op_bnel: case op_blezl: case op_bgtzl: case op_lb: case op_lh: case op_lwl: case op_lw: case op_lbu: case op_lhu: case op_lwr: case op_sb: case op_sh: case op_swl: case op_sw: case op_swr: case op_lwc1: case op_ldc1: case op_swc1: case op_sdc1: return kImmediateType; // 26 bits immediate type instructions. e.g.: j imm26. case op_j: case op_jal: return kJumpType; default: return kUnsupported; } return kUnsupported; } // C/C++ argument slots size. const int kCArgSlotCount = 4; const int kCArgsSlotsSize = kCArgSlotCount * SimInstruction::kInstrSize; const int kBranchReturnOffset = 2 * SimInstruction::kInstrSize; class CachePage { public: static const int LINE_VALID = 0; static const int LINE_INVALID = 1; static const int kPageShift = 12; static const int kPageSize = 1 << kPageShift; static const int kPageMask = kPageSize - 1; static const int kLineShift = 2; // The cache line is only 4 bytes right now. static const int kLineLength = 1 << kLineShift; static const int kLineMask = kLineLength - 1; CachePage() { memset(&validity_map_, LINE_INVALID, sizeof(validity_map_)); } char* validityByte(int offset) { return &validity_map_[offset >> kLineShift]; } char* cachedData(int offset) { return &data_[offset]; } private: char data_[kPageSize]; // The cached data. static const int kValidityMapSize = kPageSize >> kLineShift; char validity_map_[kValidityMapSize]; // One byte per line. }; // Protects the icache() and redirection() properties of the // Simulator. class AutoLockSimulatorCache : public LockGuard<Mutex> { using Base = LockGuard<Mutex>; public: explicit AutoLockSimulatorCache(Simulator* sim) : Base(sim->cacheLock_) , sim_(sim) { MOZ_ASSERT(sim_->cacheLockHolder_.isNothing()); #ifdef DEBUG sim_->cacheLockHolder_ = mozilla::Some(ThisThread::GetId()); #endif } ~AutoLockSimulatorCache() { MOZ_ASSERT(sim_->cacheLockHolder_.isSome()); #ifdef DEBUG sim_->cacheLockHolder_.reset(); #endif } private: Simulator* const sim_; }; bool Simulator::ICacheCheckingEnabled = false; int Simulator::StopSimAt = -1; Simulator* Simulator::Create(JSContext* cx) { Simulator* sim = js_new<Simulator>(); if (!sim) return nullptr; if (!sim->init()) { js_delete(sim); return nullptr; } if (getenv("MIPS_SIM_ICACHE_CHECKS")) Simulator::ICacheCheckingEnabled = true; char* stopAtStr = getenv("MIPS_SIM_STOP_AT"); int64_t stopAt; if (stopAtStr && sscanf(stopAtStr, "%lld", &stopAt) == 1) { fprintf(stderr, "\nStopping simulation at icount %lld\n", stopAt); Simulator::StopSimAt = stopAt; } return sim; } void Simulator::Destroy(Simulator* sim) { js_delete(sim); } // The MipsDebugger class is used by the simulator while debugging simulated // code. class MipsDebugger { public: explicit MipsDebugger(Simulator* sim) : sim_(sim) { } void stop(SimInstruction* instr); void debug(); // Print all registers with a nice formatting. void printAllRegs(); void printAllRegsIncludingFPU(); private: // We set the breakpoint code to 0xfffff to easily recognize it. static const Instr kBreakpointInstr = op_special | ff_break | 0xfffff << 6; static const Instr kNopInstr = op_special | ff_sll; Simulator* sim_; int32_t getRegisterValue(int regnum); int32_t getFPURegisterValueInt(int regnum); int64_t getFPURegisterValueLong(int regnum); float getFPURegisterValueFloat(int regnum); double getFPURegisterValueDouble(int regnum); bool getValue(const char* desc, int32_t* value); // Set or delete a breakpoint. Returns true if successful. bool setBreakpoint(SimInstruction* breakpc); bool deleteBreakpoint(SimInstruction* breakpc); // Undo and redo all breakpoints. This is needed to bracket disassembly and // execution to skip past breakpoints when run from the debugger. void undoBreakpoints(); void redoBreakpoints(); }; static void UNSUPPORTED() { printf("Unsupported instruction.\n"); MOZ_CRASH(); } void MipsDebugger::stop(SimInstruction* instr) { // Get the stop code. uint32_t code = instr->bits(25, 6); // Retrieve the encoded address, which comes just after this stop. char* msg = *reinterpret_cast<char**>(sim_->get_pc() + SimInstruction::kInstrSize); // Update this stop description. if (!sim_->watchedStops_[code].desc_) { sim_->watchedStops_[code].desc_ = msg; } // Print the stop message and code if it is not the default code. if (code != kMaxStopCode) { printf("Simulator hit stop %u: %s\n", code, msg); } else { printf("Simulator hit %s\n", msg); } sim_->set_pc(sim_->get_pc() + 2 * SimInstruction::kInstrSize); debug(); } int32_t MipsDebugger::getRegisterValue(int regnum) { if (regnum == kPCRegister) return sim_->get_pc(); return sim_->getRegister(regnum); } int32_t MipsDebugger::getFPURegisterValueInt(int regnum) { return sim_->getFpuRegister(regnum); } int64_t MipsDebugger::getFPURegisterValueLong(int regnum) { return sim_->getFpuRegisterLong(regnum); } float MipsDebugger::getFPURegisterValueFloat(int regnum) { return sim_->getFpuRegisterFloat(regnum); } double MipsDebugger::getFPURegisterValueDouble(int regnum) { return sim_->getFpuRegisterDouble(regnum); } bool MipsDebugger::getValue(const char* desc, int32_t* value) { Register reg = Register::FromName(desc); if (reg != InvalidReg) { *value = getRegisterValue(reg.code()); return true; } if (strncmp(desc, "0x", 2) == 0) { return sscanf(desc, "%x", reinterpret_cast<uint32_t*>(value)) == 1; } return sscanf(desc, "%i", value) == 1; } bool MipsDebugger::setBreakpoint(SimInstruction* breakpc) { // Check if a breakpoint can be set. If not return without any side-effects. if (sim_->break_pc_ != nullptr) return false; // Set the breakpoint. sim_->break_pc_ = breakpc; sim_->break_instr_ = breakpc->instructionBits(); // Not setting the breakpoint instruction in the code itself. It will be set // when the debugger shell continues. return true; } bool MipsDebugger::deleteBreakpoint(SimInstruction* breakpc) { if (sim_->break_pc_ != nullptr) sim_->break_pc_->setInstructionBits(sim_->break_instr_); sim_->break_pc_ = nullptr; sim_->break_instr_ = 0; return true; } void MipsDebugger::undoBreakpoints() { if (sim_->break_pc_) sim_->break_pc_->setInstructionBits(sim_->break_instr_); } void MipsDebugger::redoBreakpoints() { if (sim_->break_pc_) sim_->break_pc_->setInstructionBits(kBreakpointInstr); } void MipsDebugger::printAllRegs() { int32_t value; for (uint32_t i = 0; i < Registers::Total; i++) { value = getRegisterValue(i); printf("%3s: 0x%08x %10d ", Registers::GetName(i), value, value); if (i % 2) printf("\n"); } printf("\n"); value = getRegisterValue(Simulator::LO); printf(" LO: 0x%08x %10d ", value, value); value = getRegisterValue(Simulator::HI); printf(" HI: 0x%08x %10d\n", value, value); value = getRegisterValue(Simulator::pc); printf(" pc: 0x%08x\n", value); } void MipsDebugger::printAllRegsIncludingFPU() { printAllRegs(); printf("\n\n"); // f0, f1, f2, ... f31. for (uint32_t i = 0; i < FloatRegisters::RegisterIdLimit; i++) { if (i & 0x1) { printf("%3s: 0x%08x\tflt: %-8.4g\n", FloatRegisters::GetName(i), getFPURegisterValueInt(i), getFPURegisterValueFloat(i)); } else { printf("%3s: 0x%08x\tflt: %-8.4g\tdbl: %-16.4g\n", FloatRegisters::GetName(i), getFPURegisterValueInt(i), getFPURegisterValueFloat(i), getFPURegisterValueDouble(i)); } } } static char* ReadLine(const char* prompt) { char* result = nullptr; char lineBuf[256]; int offset = 0; bool keepGoing = true; fprintf(stdout, "%s", prompt); fflush(stdout); while (keepGoing) { if (fgets(lineBuf, sizeof(lineBuf), stdin) == nullptr) { // fgets got an error. Just give up. if (result) js_delete(result); return nullptr; } int len = strlen(lineBuf); if (len > 0 && lineBuf[len - 1] == '\n') { // Since we read a new line we are done reading the line. This // will exit the loop after copying this buffer into the result. keepGoing = false; } if (!result) { // Allocate the initial result and make room for the terminating '\0' result = (char*)js_malloc(len + 1); if (!result) return nullptr; } else { // Allocate a new result with enough room for the new addition. int new_len = offset + len + 1; char* new_result = (char*)js_malloc(new_len); if (!new_result) return nullptr; // Copy the existing input into the new array and set the new // array as the result. memcpy(new_result, result, offset * sizeof(char)); js_free(result); result = new_result; } // Copy the newly read line into the result. memcpy(result + offset, lineBuf, len * sizeof(char)); offset += len; } MOZ_ASSERT(result); result[offset] = '\0'; return result; } static void DisassembleInstruction(uint32_t pc) { uint8_t* bytes = reinterpret_cast<uint8_t*>(pc); char hexbytes[256]; sprintf(hexbytes, "0x%x 0x%x 0x%x 0x%x", bytes[0], bytes[1], bytes[2], bytes[3]); char llvmcmd[1024]; sprintf(llvmcmd, "bash -c \"echo -n '%p'; echo '%s' | " "llvm-mc -disassemble -arch=mipsel -mcpu=mips32r2 | " "grep -v pure_instructions | grep -v .text\"", static_cast<void*>(bytes), hexbytes); if (system(llvmcmd)) printf("Cannot disassemble instruction.\n"); } void MipsDebugger::debug() { intptr_t lastPC = -1; bool done = false; #define COMMAND_SIZE 63 #define ARG_SIZE 255 #define STR(a) #a #define XSTR(a) STR(a) char cmd[COMMAND_SIZE + 1]; char arg1[ARG_SIZE + 1]; char arg2[ARG_SIZE + 1]; char* argv[3] = { cmd, arg1, arg2 }; // Make sure to have a proper terminating character if reaching the limit. cmd[COMMAND_SIZE] = 0; arg1[ARG_SIZE] = 0; arg2[ARG_SIZE] = 0; // Undo all set breakpoints while running in the debugger shell. This will // make them invisible to all commands. undoBreakpoints(); while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) { if (lastPC != sim_->get_pc()) { DisassembleInstruction(sim_->get_pc()); lastPC = sim_->get_pc(); } char* line = ReadLine("sim> "); if (line == nullptr) { break; } else { char* last_input = sim_->lastDebuggerInput(); if (strcmp(line, "\n") == 0 && last_input != nullptr) { line = last_input; } else { // Ownership is transferred to sim_; sim_->setLastDebuggerInput(line); } // Use sscanf to parse the individual parts of the command line. At the // moment no command expects more than two parameters. int argc = sscanf(line, "%" XSTR(COMMAND_SIZE) "s " "%" XSTR(ARG_SIZE) "s " "%" XSTR(ARG_SIZE) "s", cmd, arg1, arg2); if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) { SimInstruction* instr = reinterpret_cast<SimInstruction*>(sim_->get_pc()); if (!(instr->isTrap()) || instr->instructionBits() == kCallRedirInstr) { sim_->instructionDecode( reinterpret_cast<SimInstruction*>(sim_->get_pc())); } else { // Allow si to jump over generated breakpoints. printf("/!\\ Jumping over generated breakpoint.\n"); sim_->set_pc(sim_->get_pc() + SimInstruction::kInstrSize); } } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) { // Execute the one instruction we broke at with breakpoints disabled. sim_->instructionDecode(reinterpret_cast<SimInstruction*>(sim_->get_pc())); // Leave the debugger shell. done = true; } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) { if (argc == 2) { int32_t value; if (strcmp(arg1, "all") == 0) { printAllRegs(); } else if (strcmp(arg1, "allf") == 0) { printAllRegsIncludingFPU(); } else { Register reg = Register::FromName(arg1); FloatRegisters::Code fCode = FloatRegister::FromName(arg1); if (reg != InvalidReg) { value = getRegisterValue(reg.code()); printf("%s: 0x%08x %d \n", arg1, value, value); } else if (fCode != FloatRegisters::Invalid) { if (fCode & 0x1) { printf("%3s: 0x%08x\tflt: %-8.4g\n", FloatRegisters::GetName(fCode), getFPURegisterValueInt(fCode), getFPURegisterValueFloat(fCode)); } else { printf("%3s: 0x%08x\tflt: %-8.4g\tdbl: %-16.4g\n", FloatRegisters::GetName(fCode), getFPURegisterValueInt(fCode), getFPURegisterValueFloat(fCode), getFPURegisterValueDouble(fCode)); } } else { printf("%s unrecognized\n", arg1); } } } else { printf("print <register> or print <fpu register> single\n"); } } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) { int32_t* cur = nullptr; int32_t* end = nullptr; int next_arg = 1; if (strcmp(cmd, "stack") == 0) { cur = reinterpret_cast<int32_t*>(sim_->getRegister(Simulator::sp)); } else { // Command "mem". int32_t value; if (!getValue(arg1, &value)) { printf("%s unrecognized\n", arg1); continue; } cur = reinterpret_cast<int32_t*>(value); next_arg++; } int32_t words; if (argc == next_arg) { words = 10; } else { if (!getValue(argv[next_arg], &words)) { words = 10; } } end = cur + words; while (cur < end) { printf(" %p: 0x%08x %10d", cur, *cur, *cur); printf("\n"); cur++; } } else if ((strcmp(cmd, "disasm") == 0) || (strcmp(cmd, "dpc") == 0) || (strcmp(cmd, "di") == 0)) { uint8_t* cur = nullptr; uint8_t* end = nullptr; if (argc == 1) { cur = reinterpret_cast<uint8_t*>(sim_->get_pc()); end = cur + (10 * SimInstruction::kInstrSize); } else if (argc == 2) { Register reg = Register::FromName(arg1); if (reg != InvalidReg || strncmp(arg1, "0x", 2) == 0) { // The argument is an address or a register name. int32_t value; if (getValue(arg1, &value)) { cur = reinterpret_cast<uint8_t*>(value); // Disassemble 10 instructions at <arg1>. end = cur + (10 * SimInstruction::kInstrSize); } } else { // The argument is the number of instructions. int32_t value; if (getValue(arg1, &value)) { cur = reinterpret_cast<uint8_t*>(sim_->get_pc()); // Disassemble <arg1> instructions. end = cur + (value * SimInstruction::kInstrSize); } } } else { int32_t value1; int32_t value2; if (getValue(arg1, &value1) && getValue(arg2, &value2)) { cur = reinterpret_cast<uint8_t*>(value1); end = cur + (value2 * SimInstruction::kInstrSize); } } while (cur < end) { DisassembleInstruction(uint32_t(cur)); cur += SimInstruction::kInstrSize; } } else if (strcmp(cmd, "gdb") == 0) { printf("relinquishing control to gdb\n"); asm("int $3"); printf("regaining control from gdb\n"); } else if (strcmp(cmd, "break") == 0) { if (argc == 2) { int32_t value; if (getValue(arg1, &value)) { if (!setBreakpoint(reinterpret_cast<SimInstruction*>(value))) printf("setting breakpoint failed\n"); } else { printf("%s unrecognized\n", arg1); } } else { printf("break <address>\n"); } } else if (strcmp(cmd, "del") == 0) { if (!deleteBreakpoint(nullptr)) { printf("deleting breakpoint failed\n"); } } else if (strcmp(cmd, "flags") == 0) { printf("No flags on MIPS !\n"); } else if (strcmp(cmd, "stop") == 0) { int32_t value; intptr_t stop_pc = sim_->get_pc() - 2 * SimInstruction::kInstrSize; SimInstruction* stop_instr = reinterpret_cast<SimInstruction*>(stop_pc); SimInstruction* msg_address = reinterpret_cast<SimInstruction*>(stop_pc + SimInstruction::kInstrSize); if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) { // Remove the current stop. if (sim_->isStopInstruction(stop_instr)) { stop_instr->setInstructionBits(kNopInstr); msg_address->setInstructionBits(kNopInstr); } else { printf("Not at debugger stop.\n"); } } else if (argc == 3) { // Print information about all/the specified breakpoint(s). if (strcmp(arg1, "info") == 0) { if (strcmp(arg2, "all") == 0) { printf("Stop information:\n"); for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->printStopInfo(i); } } else if (getValue(arg2, &value)) { sim_->printStopInfo(value); } else { printf("Unrecognized argument.\n"); } } else if (strcmp(arg1, "enable") == 0) { // Enable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->enableStop(i); } } else if (getValue(arg2, &value)) { sim_->enableStop(value); } else { printf("Unrecognized argument.\n"); } } else if (strcmp(arg1, "disable") == 0) { // Disable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->disableStop(i); } } else if (getValue(arg2, &value)) { sim_->disableStop(value); } else { printf("Unrecognized argument.\n"); } } } else { printf("Wrong usage. Use help command for more information.\n"); } } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) { printf("cont\n"); printf(" continue execution (alias 'c')\n"); printf("stepi\n"); printf(" step one instruction (alias 'si')\n"); printf("print <register>\n"); printf(" print register content (alias 'p')\n"); printf(" use register name 'all' to print all registers\n"); printf("printobject <register>\n"); printf(" print an object from a register (alias 'po')\n"); printf("stack [<words>]\n"); printf(" dump stack content, default dump 10 words)\n"); printf("mem <address> [<words>]\n"); printf(" dump memory content, default dump 10 words)\n"); printf("flags\n"); printf(" print flags\n"); printf("disasm [<instructions>]\n"); printf("disasm [<address/register>]\n"); printf("disasm [[<address/register>] <instructions>]\n"); printf(" disassemble code, default is 10 instructions\n"); printf(" from pc (alias 'di')\n"); printf("gdb\n"); printf(" enter gdb\n"); printf("break <address>\n"); printf(" set a break point on the address\n"); printf("del\n"); printf(" delete the breakpoint\n"); printf("stop feature:\n"); printf(" Description:\n"); printf(" Stops are debug instructions inserted by\n"); printf(" the Assembler::stop() function.\n"); printf(" When hitting a stop, the Simulator will\n"); printf(" stop and and give control to the Debugger.\n"); printf(" All stop codes are watched:\n"); printf(" - They can be enabled / disabled: the Simulator\n"); printf(" will / won't stop when hitting them.\n"); printf(" - The Simulator keeps track of how many times they \n"); printf(" are met. (See the info command.) Going over a\n"); printf(" disabled stop still increases its counter. \n"); printf(" Commands:\n"); printf(" stop info all/<code> : print infos about number <code>\n"); printf(" or all stop(s).\n"); printf(" stop enable/disable all/<code> : enables / disables\n"); printf(" all or number <code> stop(s)\n"); printf(" stop unstop\n"); printf(" ignore the stop instruction at the current location\n"); printf(" from now on\n"); } else { printf("Unknown command: %s\n", cmd); } } } // Add all the breakpoints back to stop execution and enter the debugger // shell when hit. redoBreakpoints(); #undef COMMAND_SIZE #undef ARG_SIZE #undef STR #undef XSTR } static bool AllOnOnePage(uintptr_t start, int size) { intptr_t start_page = (start & ~CachePage::kPageMask); intptr_t end_page = ((start + size) & ~CachePage::kPageMask); return start_page == end_page; } void Simulator::setLastDebuggerInput(char* input) { js_free(lastDebuggerInput_); lastDebuggerInput_ = input; } static CachePage* GetCachePageLocked(Simulator::ICacheMap& i_cache, void* page) { Simulator::ICacheMap::AddPtr p = i_cache.lookupForAdd(page); if (p) return p->value(); CachePage* new_page = js_new<CachePage>(); if (!i_cache.add(p, page, new_page)) return nullptr; return new_page; } // Flush from start up to and not including start + size. static void FlushOnePageLocked(Simulator::ICacheMap& i_cache, intptr_t start, int size) { MOZ_ASSERT(size <= CachePage::kPageSize); MOZ_ASSERT(AllOnOnePage(start, size - 1)); MOZ_ASSERT((start & CachePage::kLineMask) == 0); MOZ_ASSERT((size & CachePage::kLineMask) == 0); void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask)); int offset = (start & CachePage::kPageMask); CachePage* cache_page = GetCachePageLocked(i_cache, page); char* valid_bytemap = cache_page->validityByte(offset); memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift); } static void FlushICacheLocked(Simulator::ICacheMap& i_cache, void* start_addr, size_t size) { intptr_t start = reinterpret_cast<intptr_t>(start_addr); int intra_line = (start & CachePage::kLineMask); start -= intra_line; size += intra_line; size = ((size - 1) | CachePage::kLineMask) + 1; int offset = (start & CachePage::kPageMask); while (!AllOnOnePage(start, size - 1)) { int bytes_to_flush = CachePage::kPageSize - offset; FlushOnePageLocked(i_cache, start, bytes_to_flush); start += bytes_to_flush; size -= bytes_to_flush; MOZ_ASSERT((start & CachePage::kPageMask) == 0); offset = 0; } if (size != 0) { FlushOnePageLocked(i_cache, start, size); } } void Simulator::checkICacheLocked(Simulator::ICacheMap& i_cache, SimInstruction* instr) { intptr_t address = reinterpret_cast<intptr_t>(instr); void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask)); void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask)); int offset = (address & CachePage::kPageMask); CachePage* cache_page = GetCachePageLocked(i_cache, page); char* cache_valid_byte = cache_page->validityByte(offset); bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID); char* cached_line = cache_page->cachedData(offset & ~CachePage::kLineMask); // Read all state before considering signal handler effects. int cmpret = 0; if (cache_hit) { // Check that the data in memory matches the contents of the I-cache. cmpret = memcmp(reinterpret_cast<void*>(instr), cache_page->cachedData(offset), SimInstruction::kInstrSize); } // Check for signal handler interruption between reading state and asserting. // It is safe for the signal to arrive during the !cache_hit path, since it // will be cleared the next time this function is called. if (cacheInvalidatedBySignalHandler_) { i_cache.clear(); cacheInvalidatedBySignalHandler_ = false; return; } if (cache_hit) { MOZ_ASSERT(cmpret == 0); } else { // Cache miss. Load memory into the cache. memcpy(cached_line, line, CachePage::kLineLength); *cache_valid_byte = CachePage::LINE_VALID; } } HashNumber Simulator::ICacheHasher::hash(const Lookup& l) { return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(l)) >> 2; } bool Simulator::ICacheHasher::match(const Key& k, const Lookup& l) { MOZ_ASSERT((reinterpret_cast<intptr_t>(k) & CachePage::kPageMask) == 0); MOZ_ASSERT((reinterpret_cast<intptr_t>(l) & CachePage::kPageMask) == 0); return k == l; } void Simulator::FlushICache(void* start_addr, size_t size) { if (Simulator::ICacheCheckingEnabled) { Simulator* sim = Simulator::Current(); AutoLockSimulatorCache als(sim); js::jit::FlushICacheLocked(sim->icache(), start_addr, size); } } Simulator::Simulator() : cacheLock_(mutexid::SimulatorCacheLock), cacheInvalidatedBySignalHandler_(false) { // Set up simulator support first. Some of this information is needed to // setup the architecture state. // Note, allocation and anything that depends on allocated memory is // deferred until init(), in order to handle OOM properly. stack_ = nullptr; stackLimit_ = 0; pc_modified_ = false; icount_ = 0; break_count_ = 0; resume_pc_ = 0; break_pc_ = nullptr; break_instr_ = 0; // Set up architecture state. // All registers are initialized to zero to start with. for (int i = 0; i < Register::kNumSimuRegisters; i++) { registers_[i] = 0; } for (int i = 0; i < Simulator::FPURegister::kNumFPURegisters; i++) { FPUregisters_[i] = 0; } FCSR_ = 0; // The ra and pc are initialized to a known bad value that will cause an // access violation if the simulator ever tries to execute it. registers_[pc] = bad_ra; registers_[ra] = bad_ra; for (int i = 0; i < kNumExceptions; i++) exceptions[i] = 0; lastDebuggerInput_ = nullptr; redirection_ = nullptr; } bool Simulator::init() { if (!icache_.init()) return false; // Allocate 2MB for the stack. Note that we will only use 1MB, see below. static const size_t stackSize = 2 * 1024 * 1024; stack_ = static_cast<char*>(js_malloc(stackSize)); if (!stack_) return false; // Leave a safety margin of 1MB to prevent overrunning the stack when // pushing values (total stack size is 2MB). stackLimit_ = reinterpret_cast<uintptr_t>(stack_) + 1024 * 1024; // The sp is initialized to point to the bottom (high address) of the // allocated stack area. To be safe in potential stack underflows we leave // some buffer below. registers_[sp] = reinterpret_cast<int32_t>(stack_) + stackSize - 64; return true; } // When the generated code calls an external reference we need to catch that in // the simulator. The external reference will be a function compiled for the // host architecture. We need to call that function instead of trying to // execute it with the simulator. We do that by redirecting the external // reference to a swi (software-interrupt) instruction that is handled by // the simulator. We write the original destination of the jump just at a known // offset from the swi instruction so the simulator knows what to call. class Redirection { friend class Simulator; // sim's lock must already be held. Redirection(void* nativeFunction, ABIFunctionType type, Simulator* sim) : nativeFunction_(nativeFunction), swiInstruction_(kCallRedirInstr), type_(type), next_(nullptr) { next_ = sim->redirection(); if (Simulator::ICacheCheckingEnabled) FlushICacheLocked(sim->icache(), addressOfSwiInstruction(), SimInstruction::kInstrSize); sim->setRedirection(this); } public: void* addressOfSwiInstruction() { return &swiInstruction_; } void* nativeFunction() const { return nativeFunction_; } ABIFunctionType type() const { return type_; } static Redirection* Get(void* nativeFunction, ABIFunctionType type) { Simulator* sim = Simulator::Current(); AutoLockSimulatorCache als(sim); Redirection* current = sim->redirection(); for (; current != nullptr; current = current->next_) { if (current->nativeFunction_ == nativeFunction) { MOZ_ASSERT(current->type() == type); return current; } } Redirection* redir = (Redirection*)js_malloc(sizeof(Redirection)); if (!redir) { MOZ_ReportAssertionFailure("[unhandlable oom] Simulator redirection", __FILE__, __LINE__); MOZ_CRASH(); } new(redir) Redirection(nativeFunction, type, sim); return redir; } static Redirection* FromSwiInstruction(SimInstruction* swiInstruction) { uint8_t* addrOfSwi = reinterpret_cast<uint8_t*>(swiInstruction); uint8_t* addrOfRedirection = addrOfSwi - offsetof(Redirection, swiInstruction_); return reinterpret_cast<Redirection*>(addrOfRedirection); } private: void* nativeFunction_; uint32_t swiInstruction_; ABIFunctionType type_; Redirection* next_; }; Simulator::~Simulator() { js_free(stack_); Redirection* r = redirection_; while (r) { Redirection* next = r->next_; js_delete(r); r = next; } } /* static */ void* Simulator::RedirectNativeFunction(void* nativeFunction, ABIFunctionType type) { Redirection* redirection = Redirection::Get(nativeFunction, type); return redirection->addressOfSwiInstruction(); } // Get the active Simulator for the current thread. Simulator* Simulator::Current() { return TlsPerThreadData.get()->simulator(); } // Sets the register in the architecture state. It will also deal with updating // Simulator internal state for special registers such as PC. void Simulator::setRegister(int reg, int32_t value) { MOZ_ASSERT((reg >= 0) && (reg < Register::kNumSimuRegisters)); if (reg == pc) { pc_modified_ = true; } // Zero register always holds 0. registers_[reg] = (reg == 0) ? 0 : value; } void Simulator::setFpuRegister(int fpureg, int32_t value) { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters)); FPUregisters_[fpureg] = value; } void Simulator::setFpuRegisterFloat(int fpureg, float value) { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters)); *mozilla::BitwiseCast<float*>(&FPUregisters_[fpureg]) = value; } void Simulator::setFpuRegisterFloat(int fpureg, int64_t value) { setFpuRegister(fpureg, value & 0xffffffff); setFpuRegister(fpureg + 1, value >> 32); } void Simulator::setFpuRegisterDouble(int fpureg, double value) { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters) && ((fpureg % 2) == 0)); *mozilla::BitwiseCast<double*>(&FPUregisters_[fpureg]) = value; } void Simulator::setFpuRegisterDouble(int fpureg, int64_t value) { setFpuRegister(fpureg, value & 0xffffffff); setFpuRegister(fpureg + 1, value >> 32); } // Get the register from the architecture state. This function does handle // the special case of accessing the PC register. int32_t Simulator::getRegister(int reg) const { MOZ_ASSERT((reg >= 0) && (reg < Register::kNumSimuRegisters)); if (reg == 0) return 0; return registers_[reg] + ((reg == pc) ? SimInstruction::kPCReadOffset : 0); } double Simulator::getDoubleFromRegisterPair(int reg) { MOZ_ASSERT((reg >= 0) && (reg < Register::kNumSimuRegisters) && ((reg % 2) == 0)); double dm_val = 0.0; // Read the bits from the unsigned integer register_[] array // into the double precision floating point value and return it. memcpy(&dm_val, &registers_[reg], sizeof(dm_val)); return(dm_val); } int32_t Simulator::getFpuRegister(int fpureg) const { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters)); return FPUregisters_[fpureg]; } int64_t Simulator::getFpuRegisterLong(int fpureg) const { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters) && ((fpureg % 2) == 0)); return *mozilla::BitwiseCast<int64_t*>(const_cast<int32_t*>(&FPUregisters_[fpureg])); } float Simulator::getFpuRegisterFloat(int fpureg) const { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters)); return *mozilla::BitwiseCast<float*>(const_cast<int32_t*>(&FPUregisters_[fpureg])); } double Simulator::getFpuRegisterDouble(int fpureg) const { MOZ_ASSERT((fpureg >= 0) && (fpureg < Simulator::FPURegister::kNumFPURegisters) && ((fpureg % 2) == 0)); return *mozilla::BitwiseCast<double*>(const_cast<int32_t*>(&FPUregisters_[fpureg])); } // Runtime FP routines take up to two double arguments and zero // or one integer arguments. All are constructed here, // from a0-a3 or f12 and f14. void Simulator::getFpArgs(double* x, double* y, int32_t* z) { *x = getFpuRegisterDouble(12); *y = getFpuRegisterDouble(14); *z = getRegister(a2); } void Simulator::getFpFromStack(int32_t* stack, double* x) { MOZ_ASSERT(stack); MOZ_ASSERT(x); memcpy(x, stack, sizeof(double)); } void Simulator::setCallResultDouble(double result) { setFpuRegisterDouble(f0, result); } void Simulator::setCallResultFloat(float result) { setFpuRegisterFloat(f0, result); } void Simulator::setCallResult(int64_t res) { setRegister(v0, static_cast<int32_t>(res)); setRegister(v1, static_cast<int32_t>(res >> 32)); } // Helper functions for setting and testing the FCSR register's bits. void Simulator::setFCSRBit(uint32_t cc, bool value) { if (value) FCSR_ |= (1 << cc); else FCSR_ &= ~(1 << cc); } bool Simulator::testFCSRBit(uint32_t cc) { return FCSR_ & (1 << cc); } // Sets the rounding error codes in FCSR based on the result of the rounding. // Returns true if the operation was invalid. bool Simulator::setFCSRRoundError(double original, double rounded) { bool ret = false; if (!std::isfinite(original) || !std::isfinite(rounded)) { setFCSRBit(kFCSRInvalidOpFlagBit, true); ret = true; } if (original != rounded) { setFCSRBit(kFCSRInexactFlagBit, true); } if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) { setFCSRBit(kFCSRUnderflowFlagBit, true); ret = true; } if (rounded > INT_MAX || rounded < INT_MIN) { setFCSRBit(kFCSROverflowFlagBit, true); // The reference is not really clear but it seems this is required: setFCSRBit(kFCSRInvalidOpFlagBit, true); ret = true; } return ret; } // Raw access to the PC register. void Simulator::set_pc(int32_t value) { pc_modified_ = true; registers_[pc] = value; } bool Simulator::has_bad_pc() const { return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc)); } // Raw access to the PC register without the special adjustment when reading. int32_t Simulator::get_pc() const { return registers_[pc]; } // The MIPS cannot do unaligned reads and writes. On some MIPS platforms an // interrupt is caused. On others it does a funky rotation thing. For now we // simply disallow unaligned reads, but at some point we may want to move to // emulating the rotate behaviour. Note that simulator runs have the runtime // system running directly on the host system and only generated code is // executed in the simulator. Since the host is typically IA32 we will not // get the correct MIPS-like behaviour on unaligned accesses. int Simulator::readW(uint32_t addr, SimInstruction* instr) { if (addr < 0x400) { // This has to be a NULL-dereference, drop into debugger. printf("Memory read from bad address: 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } if ((addr & kPointerAlignmentMask) == 0) { intptr_t* ptr = reinterpret_cast<intptr_t*>(addr); return *ptr; } printf("Unaligned read at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); return 0; } void Simulator::writeW(uint32_t addr, int value, SimInstruction* instr) { if (addr < 0x400) { // This has to be a NULL-dereference, drop into debugger. printf("Memory write to bad address: 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } if ((addr & kPointerAlignmentMask) == 0) { intptr_t* ptr = reinterpret_cast<intptr_t*>(addr); *ptr = value; return; } printf("Unaligned write at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } double Simulator::readD(uint32_t addr, SimInstruction* instr) { if ((addr & kDoubleAlignmentMask) == 0) { double* ptr = reinterpret_cast<double*>(addr); return *ptr; } printf("Unaligned (double) read at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); return 0; } void Simulator::writeD(uint32_t addr, double value, SimInstruction* instr) { if ((addr & kDoubleAlignmentMask) == 0) { double* ptr = reinterpret_cast<double*>(addr); *ptr = value; return; } printf("Unaligned (double) write at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } uint16_t Simulator::readHU(uint32_t addr, SimInstruction* instr) { if ((addr & 1) == 0) { uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); return *ptr; } printf("Unaligned unsigned halfword read at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); return 0; } int16_t Simulator::readH(uint32_t addr, SimInstruction* instr) { if ((addr & 1) == 0) { int16_t* ptr = reinterpret_cast<int16_t*>(addr); return *ptr; } printf("Unaligned signed halfword read at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); return 0; } void Simulator::writeH(uint32_t addr, uint16_t value, SimInstruction* instr) { if ((addr & 1) == 0) { uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); *ptr = value; return; } printf("Unaligned unsigned halfword write at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } void Simulator::writeH(uint32_t addr, int16_t value, SimInstruction* instr) { if ((addr & 1) == 0) { int16_t* ptr = reinterpret_cast<int16_t*>(addr); *ptr = value; return; } printf("Unaligned halfword write at 0x%08x, pc=0x%08" PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MOZ_CRASH(); } uint32_t Simulator::readBU(uint32_t addr) { uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); return *ptr; } int32_t Simulator::readB(uint32_t addr) { int8_t* ptr = reinterpret_cast<int8_t*>(addr); return *ptr; } void Simulator::writeB(uint32_t addr, uint8_t value) { uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); *ptr = value; } void Simulator::writeB(uint32_t addr, int8_t value) { int8_t* ptr = reinterpret_cast<int8_t*>(addr); *ptr = value; } uintptr_t Simulator::stackLimit() const { return stackLimit_; } uintptr_t* Simulator::addressOfStackLimit() { return &stackLimit_; } bool Simulator::overRecursed(uintptr_t newsp) const { if (newsp == 0) newsp = getRegister(sp); return newsp <= stackLimit(); } bool Simulator::overRecursedWithExtra(uint32_t extra) const { uintptr_t newsp = getRegister(sp) - extra; return newsp <= stackLimit(); } // Unsupported instructions use format to print an error and stop execution. void Simulator::format(SimInstruction* instr, const char* format) { printf("Simulator found unsupported instruction:\n 0x%08" PRIxPTR ": %s\n", reinterpret_cast<intptr_t>(instr), format); MOZ_CRASH(); } // Note: With the code below we assume that all runtime calls return a 64 bits // result. If they don't, the v1 result register contains a bogus value, which // is fine because it is caller-saved. typedef int64_t (*Prototype_General0)(); typedef int64_t (*Prototype_General1)(int32_t arg0); typedef int64_t (*Prototype_General2)(int32_t arg0, int32_t arg1); typedef int64_t (*Prototype_General3)(int32_t arg0, int32_t arg1, int32_t arg2); typedef int64_t (*Prototype_General4)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3); typedef int64_t (*Prototype_General5)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4); typedef int64_t (*Prototype_General6)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5); typedef int64_t (*Prototype_General7)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5, int32_t arg6); typedef int64_t (*Prototype_General8)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5, int32_t arg6, int32_t arg7); typedef double (*Prototype_Double_None)(); typedef double (*Prototype_Double_Double)(double arg0); typedef double (*Prototype_Double_Int)(int32_t arg0); typedef int32_t (*Prototype_Int_Double)(double arg0); typedef int64_t (*Prototype_Int64_Double)(double arg0); typedef int32_t (*Prototype_Int_DoubleIntInt)(double arg0, int32_t arg1, int32_t arg2); typedef int32_t (*Prototype_Int_IntDoubleIntInt)(int32_t arg0, double arg1, int32_t arg2, int32_t arg3); typedef float (*Prototype_Float32_Float32)(float arg0); typedef double (*Prototype_DoubleInt)(double arg0, int32_t arg1); typedef double (*Prototype_Double_IntInt)(int32_t arg0, int32_t arg1); typedef double (*Prototype_Double_IntDouble)(int32_t arg0, double arg1); typedef double (*Prototype_Double_DoubleDouble)(double arg0, double arg1); typedef int32_t (*Prototype_Int_IntDouble)(int32_t arg0, double arg1); typedef double (*Prototype_Double_DoubleDoubleDouble)(double arg0, double arg1, double arg2); typedef double (*Prototype_Double_DoubleDoubleDoubleDouble)(double arg0, double arg1, double arg2, double arg3); // Software interrupt instructions are used by the simulator to call into C++. void Simulator::softwareInterrupt(SimInstruction* instr) { int32_t func = instr->functionFieldRaw(); uint32_t code = (func == ff_break) ? instr->bits(25, 6) : -1; // We first check if we met a call_rt_redirected. if (instr->instructionBits() == kCallRedirInstr) { #if !defined(USES_O32_ABI) MOZ_CRASH("Only O32 ABI supported."); #else Redirection* redirection = Redirection::FromSwiInstruction(instr); int32_t arg0 = getRegister(a0); int32_t arg1 = getRegister(a1); int32_t arg2 = getRegister(a2); int32_t arg3 = getRegister(a3); int32_t* stack_pointer = reinterpret_cast<int32_t*>(getRegister(sp)); // Args 4 and 5 are on the stack after the reserved space for args 0..3. int32_t arg4 = stack_pointer[4]; int32_t arg5 = stack_pointer[5]; // This is dodgy but it works because the C entry stubs are never moved. // See comment in codegen-arm.cc and bug 1242173. int32_t saved_ra = getRegister(ra); intptr_t external = reinterpret_cast<intptr_t>(redirection->nativeFunction()); bool stack_aligned = (getRegister(sp) & (ABIStackAlignment - 1)) == 0; if (!stack_aligned) { fprintf(stderr, "Runtime call with unaligned stack!\n"); MOZ_CRASH(); } switch (redirection->type()) { case Args_General0: { Prototype_General0 target = reinterpret_cast<Prototype_General0>(external); int64_t result = target(); setCallResult(result); break; } case Args_General1: { Prototype_General1 target = reinterpret_cast<Prototype_General1>(external); int64_t result = target(arg0); setCallResult(result); break; } case Args_General2: { Prototype_General2 target = reinterpret_cast<Prototype_General2>(external); int64_t result = target(arg0, arg1); setCallResult(result); break; } case Args_General3: { Prototype_General3 target = reinterpret_cast<Prototype_General3>(external); int64_t result = target(arg0, arg1, arg2); setCallResult(result); break; } case Args_General4: { Prototype_General4 target = reinterpret_cast<Prototype_General4>(external); int64_t result = target(arg0, arg1, arg2, arg3); setCallResult(result); break; } case Args_General5: { Prototype_General5 target = reinterpret_cast<Prototype_General5>(external); int64_t result = target(arg0, arg1, arg2, arg3, arg4); setCallResult(result); break; } case Args_General6: { Prototype_General6 target = reinterpret_cast<Prototype_General6>(external); int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5); setCallResult(result); break; } case Args_General7: { Prototype_General7 target = reinterpret_cast<Prototype_General7>(external); int32_t arg6 = stack_pointer[6]; int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5, arg6); setCallResult(result); break; } case Args_General8: { Prototype_General8 target = reinterpret_cast<Prototype_General8>(external); int32_t arg6 = stack_pointer[6]; int32_t arg7 = stack_pointer[7]; int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); setCallResult(result); break; } case Args_Double_None: { Prototype_Double_None target = reinterpret_cast<Prototype_Double_None>(external); double dresult = target(); setCallResultDouble(dresult); break; } case Args_Int_Double: { double dval0, dval1; int32_t ival; getFpArgs(&dval0, &dval1, &ival); Prototype_Int_Double target = reinterpret_cast<Prototype_Int_Double>(external); int32_t res = target(dval0); setRegister(v0, res); break; } case Args_Int64_Double: { double dval0, dval1; int32_t ival; getFpArgs(&dval0, &dval1, &ival); Prototype_Int64_Double target = reinterpret_cast<Prototype_Int64_Double>(external); int64_t result = target(dval0); setCallResult(result); break; } case Args_Int_DoubleIntInt: { double dval = getFpuRegisterDouble(12); Prototype_Int_DoubleIntInt target = reinterpret_cast<Prototype_Int_DoubleIntInt>(external); int32_t res = target(dval, arg2, arg3); setRegister(v0, res); break; } case Args_Int_IntDoubleIntInt: { double dval = getDoubleFromRegisterPair(a2); Prototype_Int_IntDoubleIntInt target = reinterpret_cast<Prototype_Int_IntDoubleIntInt>(external); int32_t res = target(arg0, dval, arg4, arg5); setRegister(v0, res); break; } case Args_Double_Double: { double dval0, dval1; int32_t ival; getFpArgs(&dval0, &dval1, &ival); Prototype_Double_Double target = reinterpret_cast<Prototype_Double_Double>(external); double dresult = target(dval0); setCallResultDouble(dresult); break; } case Args_Float32_Float32: { float fval0; fval0 = getFpuRegisterFloat(12); Prototype_Float32_Float32 target = reinterpret_cast<Prototype_Float32_Float32>(external); float fresult = target(fval0); setCallResultFloat(fresult); break; } case Args_Double_Int: { Prototype_Double_Int target = reinterpret_cast<Prototype_Double_Int>(external); double dresult = target(arg0); setCallResultDouble(dresult); break; } case Args_Double_IntInt: { Prototype_Double_IntInt target = reinterpret_cast<Prototype_Double_IntInt>(external); double dresult = target(arg0, arg1); setCallResultDouble(dresult); break; } case Args_Double_DoubleInt: { double dval0, dval1; int32_t ival; getFpArgs(&dval0, &dval1, &ival); Prototype_DoubleInt target = reinterpret_cast<Prototype_DoubleInt>(external); double dresult = target(dval0, ival); setCallResultDouble(dresult); break; } case Args_Double_DoubleDouble: { double dval0, dval1; int32_t ival; getFpArgs(&dval0, &dval1, &ival); Prototype_Double_DoubleDouble target = reinterpret_cast<Prototype_Double_DoubleDouble>(external); double dresult = target(dval0, dval1); setCallResultDouble(dresult); break; } case Args_Double_IntDouble: { int32_t ival = getRegister(a0); double dval0 = getDoubleFromRegisterPair(a2); Prototype_Double_IntDouble target = reinterpret_cast<Prototype_Double_IntDouble>(external); double dresult = target(ival, dval0); setCallResultDouble(dresult); break; } case Args_Int_IntDouble: { int32_t ival = getRegister(a0); double dval0 = getDoubleFromRegisterPair(a2); Prototype_Int_IntDouble target = reinterpret_cast<Prototype_Int_IntDouble>(external); int32_t result = target(ival, dval0); setRegister(v0, result); break; } case Args_Double_DoubleDoubleDouble: { double dval0, dval1, dval2; int32_t ival; getFpArgs(&dval0, &dval1, &ival); // the last argument is on stack getFpFromStack(stack_pointer + 4, &dval2); Prototype_Double_DoubleDoubleDouble target = reinterpret_cast<Prototype_Double_DoubleDoubleDouble>(external); double dresult = target(dval0, dval1, dval2); setCallResultDouble(dresult); break; } case Args_Double_DoubleDoubleDoubleDouble: { double dval0, dval1, dval2, dval3; int32_t ival; getFpArgs(&dval0, &dval1, &ival); // the two last arguments are on stack getFpFromStack(stack_pointer + 4, &dval2); getFpFromStack(stack_pointer + 6, &dval3); Prototype_Double_DoubleDoubleDoubleDouble target = reinterpret_cast<Prototype_Double_DoubleDoubleDoubleDouble>(external); double dresult = target(dval0, dval1, dval2, dval3); setCallResultDouble(dresult); break; } default: MOZ_CRASH("call"); } setRegister(ra, saved_ra); set_pc(getRegister(ra)); #endif } else if (func == ff_break && code <= kMaxStopCode) { if (isWatchpoint(code)) { printWatchpoint(code); } else { increaseStopCounter(code); handleStop(code, instr); } } else { // All remaining break_ codes, and all traps are handled here. MipsDebugger dbg(this); dbg.debug(); } } // Stop helper functions. bool Simulator::isWatchpoint(uint32_t code) { return (code <= kMaxWatchpointCode); } void Simulator::printWatchpoint(uint32_t code) { MipsDebugger dbg(this); ++break_count_; printf("\n---- break %d marker: %3d (instr count: %8d) ----------" "----------------------------------", code, break_count_, icount_); dbg.printAllRegs(); // Print registers and continue running. } void Simulator::handleStop(uint32_t code, SimInstruction* instr) { // Stop if it is enabled, otherwise go on jumping over the stop // and the message address. if (isEnabledStop(code)) { MipsDebugger dbg(this); dbg.stop(instr); } else { set_pc(get_pc() + 2 * SimInstruction::kInstrSize); } } bool Simulator::isStopInstruction(SimInstruction* instr) { int32_t func = instr->functionFieldRaw(); uint32_t code = static_cast<uint32_t>(instr->bits(25, 6)); return (func == ff_break) && code > kMaxWatchpointCode && code <= kMaxStopCode; } bool Simulator::isEnabledStop(uint32_t code) { MOZ_ASSERT(code <= kMaxStopCode); MOZ_ASSERT(code > kMaxWatchpointCode); return !(watchedStops_[code].count_ & kStopDisabledBit); } void Simulator::enableStop(uint32_t code) { if (!isEnabledStop(code)) watchedStops_[code].count_ &= ~kStopDisabledBit; } void Simulator::disableStop(uint32_t code) { if (isEnabledStop(code)) watchedStops_[code].count_ |= kStopDisabledBit; } void Simulator::increaseStopCounter(uint32_t code) { MOZ_ASSERT(code <= kMaxStopCode); if ((watchedStops_[code].count_ & ~(1 << 31)) == 0x7fffffff) { printf("Stop counter for code %i has overflowed.\n" "Enabling this code and reseting the counter to 0.\n", code); watchedStops_[code].count_ = 0; enableStop(code); } else { watchedStops_[code].count_++; } } // Print a stop status. void Simulator::printStopInfo(uint32_t code) { if (code <= kMaxWatchpointCode) { printf("That is a watchpoint, not a stop.\n"); return; } else if (code > kMaxStopCode) { printf("Code too large, only %u stops can be used\n", kMaxStopCode + 1); return; } const char* state = isEnabledStop(code) ? "Enabled" : "Disabled"; int32_t count = watchedStops_[code].count_ & ~kStopDisabledBit; // Don't print the state of unused breakpoints. if (count != 0) { if (watchedStops_[code].desc_) { printf("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code, state, count, watchedStops_[code].desc_); } else { printf("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state, count); } } } void Simulator::signalExceptions() { for (int i = 1; i < kNumExceptions; i++) { if (exceptions[i] != 0) MOZ_CRASH("Error: Exception raised."); } } // Handle execution based on instruction types. void Simulator::configureTypeRegister(SimInstruction* instr, int32_t& alu_out, int64_t& i64hilo, uint64_t& u64hilo, int32_t& next_pc, int32_t& return_addr_reg, bool& do_interrupt) { // Every local variable declared here needs to be const. // This is to make sure that changed values are sent back to // decodeTypeRegister correctly. // Instruction fields. const Opcode op = instr->opcodeFieldRaw(); const int32_t rs_reg = instr->rsValue(); const int32_t rs = getRegister(rs_reg); const uint32_t rs_u = static_cast<uint32_t>(rs); const int32_t rt_reg = instr->rtValue(); const int32_t rt = getRegister(rt_reg); const uint32_t rt_u = static_cast<uint32_t>(rt); const int32_t rd_reg = instr->rdValue(); const uint32_t sa = instr->saValue(); const int32_t fs_reg = instr->fsValue(); // ---------- Configuration. switch (op) { case op_cop1: // Coprocessor instructions. switch (instr->rsFieldRaw()) { case rs_bc1: // Handled in DecodeTypeImmed, should never come here. MOZ_CRASH(); break; case rs_cfc1: // At the moment only FCSR is supported. MOZ_ASSERT(fs_reg == kFCSRRegister); alu_out = FCSR_; break; case rs_mfc1: alu_out = getFpuRegister(fs_reg); break; case rs_mfhc1: MOZ_CRASH(); break; case rs_ctc1: case rs_mtc1: case rs_mthc1: // Do the store in the execution step. break; case rs_s: case rs_d: case rs_w: case rs_l: case rs_ps: // Do everything in the execution step. break; default: MOZ_CRASH(); } break; case op_cop1x: break; case op_special: switch (instr->functionFieldRaw()) { case ff_jr: case ff_jalr: next_pc = getRegister(instr->rsValue()); return_addr_reg = instr->rdValue(); break; case ff_sll: alu_out = rt << sa; break; case ff_srl: if (rs_reg == 0) { // Regular logical right shift of a word by a fixed number of // bits instruction. RS field is always equal to 0. alu_out = rt_u >> sa; } else { // Logical right-rotate of a word by a fixed number of bits. This // is special case of SRL instruction, added in MIPS32 Release 2. // RS field is equal to 00001. alu_out = (rt_u >> sa) | (rt_u << (32 - sa)); } break; case ff_sra: alu_out = rt >> sa; break; case ff_sllv: alu_out = rt << rs; break; case ff_srlv: if (sa == 0) { // Regular logical right-shift of a word by a variable number of // bits instruction. SA field is always equal to 0. alu_out = rt_u >> rs; } else { // Logical right-rotate of a word by a variable number of bits. // This is special case od SRLV instruction, added in MIPS32 // Release 2. SA field is equal to 00001. alu_out = (rt_u >> rs_u) | (rt_u << (32 - rs_u)); } break; case ff_srav: alu_out = rt >> rs; break; case ff_mfhi: alu_out = getRegister(HI); break; case ff_mflo: alu_out = getRegister(LO); break; case ff_mult: i64hilo = static_cast<int64_t>(rs) * static_cast<int64_t>(rt); break; case ff_multu: u64hilo = static_cast<uint64_t>(rs_u) * static_cast<uint64_t>(rt_u); break; case ff_add: if (HaveSameSign(rs, rt)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (kRegisterskMaxValue - rt); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (kRegisterskMinValue - rt); } } alu_out = rs + rt; break; case ff_addu: alu_out = rs + rt; break; case ff_sub: if (!HaveSameSign(rs, rt)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (kRegisterskMaxValue + rt); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (kRegisterskMinValue + rt); } } alu_out = rs - rt; break; case ff_subu: alu_out = rs - rt; break; case ff_and: alu_out = rs & rt; break; case ff_or: alu_out = rs | rt; break; case ff_xor: alu_out = rs ^ rt; break; case ff_nor: alu_out = ~(rs | rt); break; case ff_slt: alu_out = rs < rt ? 1 : 0; break; case ff_sltu: alu_out = rs_u < rt_u ? 1 : 0; break; // Break and trap instructions. case ff_break: do_interrupt = true; break; case ff_tge: do_interrupt = rs >= rt; break; case ff_tgeu: do_interrupt = rs_u >= rt_u; break; case ff_tlt: do_interrupt = rs < rt; break; case ff_tltu: do_interrupt = rs_u < rt_u; break; case ff_teq: do_interrupt = rs == rt; break; case ff_tne: do_interrupt = rs != rt; break; case ff_movn: case ff_movz: case ff_movci: // No action taken on decode. break; case ff_div: case ff_divu: // div and divu never raise exceptions. break; default: MOZ_CRASH(); } break; case op_special2: switch (instr->functionFieldRaw()) { case ff_mul: alu_out = rs_u * rt_u; // Only the lower 32 bits are kept. break; case ff_clz: alu_out = rs_u ? __builtin_clz(rs_u) : 32; break; default: MOZ_CRASH(); } break; case op_special3: switch (instr->functionFieldRaw()) { case ff_ins: { // Mips32r2 instruction. // Interpret rd field as 5-bit msb of insert. uint16_t msb = rd_reg; // Interpret sa field as 5-bit lsb of insert. uint16_t lsb = sa; uint16_t size = msb - lsb + 1; uint32_t mask = (1 << size) - 1; alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb); break; } case ff_ext: { // Mips32r2 instruction. // Interpret rd field as 5-bit msb of extract. uint16_t msb = rd_reg; // Interpret sa field as 5-bit lsb of extract. uint16_t lsb = sa; uint16_t size = msb + 1; uint32_t mask = (1 << size) - 1; alu_out = (rs_u & (mask << lsb)) >> lsb; break; } default: MOZ_CRASH(); } break; default: MOZ_CRASH(); } } void Simulator::decodeTypeRegister(SimInstruction* instr) { // Instruction fields. const Opcode op = instr->opcodeFieldRaw(); const int32_t rs_reg = instr->rsValue(); const int32_t rs = getRegister(rs_reg); const uint32_t rs_u = static_cast<uint32_t>(rs); const int32_t rt_reg = instr->rtValue(); const int32_t rt = getRegister(rt_reg); const uint32_t rt_u = static_cast<uint32_t>(rt); const int32_t rd_reg = instr->rdValue(); const int32_t fr_reg = instr->frValue(); const int32_t fs_reg = instr->fsValue(); const int32_t ft_reg = instr->ftValue(); const int32_t fd_reg = instr->fdValue(); int64_t i64hilo = 0; uint64_t u64hilo = 0; // ALU output. // It should not be used as is. Instructions using it should always // initialize it first. int32_t alu_out = 0x12345678; // For break and trap instructions. bool do_interrupt = false; // For jr and jalr. // Get current pc. int32_t current_pc = get_pc(); // Next pc int32_t next_pc = 0; int32_t return_addr_reg = 31; // Set up the variables if needed before executing the instruction. configureTypeRegister(instr, alu_out, i64hilo, u64hilo, next_pc, return_addr_reg, do_interrupt); // ---------- Raise exceptions triggered. signalExceptions(); // ---------- Execution. switch (op) { case op_cop1: switch (instr->rsFieldRaw()) { case rs_bc1: // Branch on coprocessor condition. MOZ_CRASH(); break; case rs_cfc1: setRegister(rt_reg, alu_out); case rs_mfc1: setRegister(rt_reg, alu_out); break; case rs_mfhc1: MOZ_CRASH(); break; case rs_ctc1: // At the moment only FCSR is supported. MOZ_ASSERT(fs_reg == kFCSRRegister); FCSR_ = registers_[rt_reg]; break; case rs_mtc1: FPUregisters_[fs_reg] = registers_[rt_reg]; break; case rs_mthc1: MOZ_CRASH(); break; case rs_s: float f, ft_value, fs_value; uint32_t cc, fcsr_cc; int64_t i64; fs_value = getFpuRegisterFloat(fs_reg); ft_value = getFpuRegisterFloat(ft_reg); cc = instr->fcccValue(); fcsr_cc = GetFCSRConditionBit(cc); switch (instr->functionFieldRaw()) { case ff_add_fmt: setFpuRegisterFloat(fd_reg, fs_value + ft_value); break; case ff_sub_fmt: setFpuRegisterFloat(fd_reg, fs_value - ft_value); break; case ff_mul_fmt: setFpuRegisterFloat(fd_reg, fs_value * ft_value); break; case ff_div_fmt: setFpuRegisterFloat(fd_reg, fs_value / ft_value); break; case ff_abs_fmt: setFpuRegisterFloat(fd_reg, fabsf(fs_value)); break; case ff_mov_fmt: setFpuRegisterFloat(fd_reg, fs_value); break; case ff_neg_fmt: setFpuRegisterFloat(fd_reg, -fs_value); break; case ff_sqrt_fmt: setFpuRegisterFloat(fd_reg, sqrtf(fs_value)); break; case ff_c_un_fmt: setFCSRBit(fcsr_cc, mozilla::IsNaN(fs_value) || mozilla::IsNaN(ft_value)); break; case ff_c_eq_fmt: setFCSRBit(fcsr_cc, (fs_value == ft_value)); break; case ff_c_ueq_fmt: setFCSRBit(fcsr_cc, (fs_value == ft_value) || (mozilla::IsNaN(fs_value) || mozilla::IsNaN(ft_value))); break; case ff_c_olt_fmt: setFCSRBit(fcsr_cc, (fs_value < ft_value)); break; case ff_c_ult_fmt: setFCSRBit(fcsr_cc, (fs_value < ft_value) || (mozilla::IsNaN(fs_value) || mozilla::IsNaN(ft_value))); break; case ff_c_ole_fmt: setFCSRBit(fcsr_cc, (fs_value <= ft_value)); break; case ff_c_ule_fmt: setFCSRBit(fcsr_cc, (fs_value <= ft_value) || (mozilla::IsNaN(fs_value) || mozilla::IsNaN(ft_value))); break; case ff_cvt_d_fmt: f = getFpuRegisterFloat(fs_reg); setFpuRegisterDouble(fd_reg, static_cast<double>(f)); break; case ff_cvt_w_fmt: // Convert float to word. // Rounding modes are not yet supported. MOZ_ASSERT((FCSR_ & 3) == 0); // In rounding mode 0 it should behave like ROUND. case ff_round_w_fmt: { // Round double to word (round half to even). float rounded = std::floor(fs_value + 0.5); int32_t result = static_cast<int32_t>(rounded); if ((result & 1) != 0 && result - fs_value == 0.5) { // If the number is halfway between two integers, // round to the even one. result--; } setFpuRegister(fd_reg, result); if (setFCSRRoundError(fs_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_trunc_w_fmt: { // Truncate float to word (round towards 0). float rounded = truncf(fs_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(fs_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_floor_w_fmt: { // Round float to word towards negative infinity. float rounded = std::floor(fs_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(fs_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_ceil_w_fmt: { // Round double to word towards positive infinity. float rounded = std::ceil(fs_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(fs_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_cvt_l_fmt: { // Mips32r2: Truncate float to 64-bit long-word. float rounded = truncf(fs_value); i64 = static_cast<int64_t>(rounded); setFpuRegisterFloat(fd_reg, i64); break; } case ff_round_l_fmt: { // Mips32r2 instruction. float rounded = fs_value > 0 ? std::floor(fs_value + 0.5) : std::ceil(fs_value - 0.5); i64 = static_cast<int64_t>(rounded); setFpuRegisterFloat(fd_reg, i64); break; } case ff_trunc_l_fmt: { // Mips32r2 instruction. float rounded = truncf(fs_value); i64 = static_cast<int64_t>(rounded); setFpuRegisterFloat(fd_reg, i64); break; } case ff_floor_l_fmt: // Mips32r2 instruction. i64 = static_cast<int64_t>(std::floor(fs_value)); setFpuRegisterFloat(fd_reg, i64); break; case ff_ceil_l_fmt: // Mips32r2 instruction. i64 = static_cast<int64_t>(std::ceil(fs_value)); setFpuRegisterFloat(fd_reg, i64); break; case ff_cvt_ps_s: case ff_c_f_fmt: MOZ_CRASH(); break; default: MOZ_CRASH(); } break; case rs_d: double dt_value, ds_value; ds_value = getFpuRegisterDouble(fs_reg); dt_value = getFpuRegisterDouble(ft_reg); cc = instr->fcccValue(); fcsr_cc = GetFCSRConditionBit(cc); switch (instr->functionFieldRaw()) { case ff_add_fmt: setFpuRegisterDouble(fd_reg, ds_value + dt_value); break; case ff_sub_fmt: setFpuRegisterDouble(fd_reg, ds_value - dt_value); break; case ff_mul_fmt: setFpuRegisterDouble(fd_reg, ds_value * dt_value); break; case ff_div_fmt: setFpuRegisterDouble(fd_reg, ds_value / dt_value); break; case ff_abs_fmt: setFpuRegisterDouble(fd_reg, fabs(ds_value)); break; case ff_mov_fmt: setFpuRegisterDouble(fd_reg, ds_value); break; case ff_neg_fmt: setFpuRegisterDouble(fd_reg, -ds_value); break; case ff_sqrt_fmt: setFpuRegisterDouble(fd_reg, sqrt(ds_value)); break; case ff_c_un_fmt: setFCSRBit(fcsr_cc, mozilla::IsNaN(ds_value) || mozilla::IsNaN(dt_value)); break; case ff_c_eq_fmt: setFCSRBit(fcsr_cc, (ds_value == dt_value)); break; case ff_c_ueq_fmt: setFCSRBit(fcsr_cc, (ds_value == dt_value) || (mozilla::IsNaN(ds_value) || mozilla::IsNaN(dt_value))); break; case ff_c_olt_fmt: setFCSRBit(fcsr_cc, (ds_value < dt_value)); break; case ff_c_ult_fmt: setFCSRBit(fcsr_cc, (ds_value < dt_value) || (mozilla::IsNaN(ds_value) || mozilla::IsNaN(dt_value))); break; case ff_c_ole_fmt: setFCSRBit(fcsr_cc, (ds_value <= dt_value)); break; case ff_c_ule_fmt: setFCSRBit(fcsr_cc, (ds_value <= dt_value) || (mozilla::IsNaN(ds_value) || mozilla::IsNaN(dt_value))); break; case ff_cvt_w_fmt: // Convert double to word. // Rounding modes are not yet supported. MOZ_ASSERT((FCSR_ & 3) == 0); // In rounding mode 0 it should behave like ROUND. case ff_round_w_fmt: { // Round double to word (round half to even). double rounded = std::floor(ds_value + 0.5); int32_t result = static_cast<int32_t>(rounded); if ((result & 1) != 0 && result - ds_value == 0.5) { // If the number is halfway between two integers, // round to the even one. result--; } setFpuRegister(fd_reg, result); if (setFCSRRoundError(ds_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_trunc_w_fmt: { // Truncate double to word (round towards 0). double rounded = trunc(ds_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(ds_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_floor_w_fmt: { // Round double to word towards negative infinity. double rounded = std::floor(ds_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(ds_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_ceil_w_fmt: { // Round double to word towards positive infinity. double rounded = std::ceil(ds_value); int32_t result = static_cast<int32_t>(rounded); setFpuRegister(fd_reg, result); if (setFCSRRoundError(ds_value, rounded)) { setFpuRegister(fd_reg, kFPUInvalidResult); } break; } case ff_cvt_s_fmt: // Convert double to float (single). setFpuRegisterFloat(fd_reg, static_cast<float>(ds_value)); break; case ff_cvt_l_fmt: { // Mips32r2: Truncate double to 64-bit long-word. double rounded = trunc(ds_value); i64 = static_cast<int64_t>(rounded); setFpuRegisterDouble(fd_reg, i64); break; } case ff_trunc_l_fmt: { // Mips32r2 instruction. double rounded = trunc(ds_value); i64 = static_cast<int64_t>(rounded); setFpuRegisterDouble(fd_reg, i64); break; } case ff_round_l_fmt: { // Mips32r2 instruction. double rounded = ds_value > 0 ? std::floor(ds_value + 0.5) : std::ceil(ds_value - 0.5); i64 = static_cast<int64_t>(rounded); setFpuRegisterDouble(fd_reg, i64); break; } case ff_floor_l_fmt: // Mips32r2 instruction. i64 = static_cast<int64_t>(std::floor(ds_value)); setFpuRegisterDouble(fd_reg, i64); break; case ff_ceil_l_fmt: // Mips32r2 instruction. i64 = static_cast<int64_t>(std::ceil(ds_value)); setFpuRegisterDouble(fd_reg, i64); break; case ff_c_f_fmt: MOZ_CRASH(); break; default: MOZ_CRASH(); } break; case rs_w: switch (instr->functionFieldRaw()) { case ff_cvt_s_fmt: // Convert word to float (single). alu_out = getFpuRegister(fs_reg); setFpuRegisterFloat(fd_reg, static_cast<float>(alu_out)); break; case ff_cvt_d_fmt: // Convert word to double. alu_out = getFpuRegister(fs_reg); setFpuRegisterDouble(fd_reg, static_cast<double>(alu_out)); break; default: MOZ_CRASH(); } break; case rs_l: switch (instr->functionFieldRaw()) { case ff_cvt_d_fmt: // Mips32r2 instruction. // Watch the signs here, we want 2 32-bit vals // to make a sign-64. i64 = static_cast<uint32_t>(getFpuRegister(fs_reg)); i64 |= static_cast<int64_t>(getFpuRegister(fs_reg + 1)) << 32; setFpuRegisterDouble(fd_reg, static_cast<double>(i64)); break; case ff_cvt_s_fmt: MOZ_CRASH(); break; default: MOZ_CRASH(); } break; case rs_ps: break; default: MOZ_CRASH(); } break; case op_cop1x: switch (instr->functionFieldRaw()) { case ff_madd_s: float fr, ft, fs; fr = getFpuRegisterFloat(fr_reg); fs = getFpuRegisterFloat(fs_reg); ft = getFpuRegisterFloat(ft_reg); setFpuRegisterFloat(fd_reg, fs * ft + fr); break; case ff_madd_d: double dr, dt, ds; dr = getFpuRegisterDouble(fr_reg); ds = getFpuRegisterDouble(fs_reg); dt = getFpuRegisterDouble(ft_reg); setFpuRegisterDouble(fd_reg, ds * dt + dr); break; default: MOZ_CRASH(); } break; case op_special: switch (instr->functionFieldRaw()) { case ff_jr: { SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>( current_pc + SimInstruction::kInstrSize); branchDelayInstructionDecode(branch_delay_instr); set_pc(next_pc); pc_modified_ = true; break; } case ff_jalr: { SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>( current_pc + SimInstruction::kInstrSize); setRegister(return_addr_reg, current_pc + 2 * SimInstruction::kInstrSize); branchDelayInstructionDecode(branch_delay_instr); set_pc(next_pc); pc_modified_ = true; break; } // Instructions using HI and LO registers. case ff_mult: setRegister(LO, static_cast<int32_t>(i64hilo & 0xffffffff)); setRegister(HI, static_cast<int32_t>(i64hilo >> 32)); break; case ff_multu: setRegister(LO, static_cast<int32_t>(u64hilo & 0xffffffff)); setRegister(HI, static_cast<int32_t>(u64hilo >> 32)); break; case ff_div: // Divide by zero and overflow was not checked in the configuration // step - div and divu do not raise exceptions. On division by 0 // the result will be UNPREDICTABLE. On overflow (INT_MIN/-1), // return INT_MIN which is what the hardware does. if (rs == INT_MIN && rt == -1) { setRegister(LO, INT_MIN); setRegister(HI, 0); } else if (rt != 0) { setRegister(LO, rs / rt); setRegister(HI, rs % rt); } break; case ff_divu: if (rt_u != 0) { setRegister(LO, rs_u / rt_u); setRegister(HI, rs_u % rt_u); } break; // Break and trap instructions. case ff_break: case ff_tge: case ff_tgeu: case ff_tlt: case ff_tltu: case ff_teq: case ff_tne: if (do_interrupt) { softwareInterrupt(instr); } break; // Conditional moves. case ff_movn: if (rt) setRegister(rd_reg, rs); break; case ff_movci: { uint32_t cc = instr->fbccValue(); uint32_t fcsr_cc = GetFCSRConditionBit(cc); if (instr->bit(16)) { // Read Tf bit. if (testFCSRBit(fcsr_cc)) setRegister(rd_reg, rs); } else { if (!testFCSRBit(fcsr_cc)) setRegister(rd_reg, rs); } break; } case ff_movz: if (!rt) setRegister(rd_reg, rs); break; default: // For other special opcodes we do the default operation. setRegister(rd_reg, alu_out); } break; case op_special2: switch (instr->functionFieldRaw()) { case ff_mul: setRegister(rd_reg, alu_out); // HI and LO are UNPREDICTABLE after the operation. setRegister(LO, Unpredictable); setRegister(HI, Unpredictable); break; default: // For other special2 opcodes we do the default operation. setRegister(rd_reg, alu_out); } break; case op_special3: switch (instr->functionFieldRaw()) { case ff_ins: // Ins instr leaves result in Rt, rather than Rd. setRegister(rt_reg, alu_out); break; case ff_ext: // Ext instr leaves result in Rt, rather than Rd. setRegister(rt_reg, alu_out); break; default: MOZ_CRASH(); } break; // Unimplemented opcodes raised an error in the configuration step before, // so we can use the default here to set the destination register in common // cases. default: setRegister(rd_reg, alu_out); } } // Type 2: instructions using a 16 bytes immediate. (e.g. addi, beq). void Simulator::decodeTypeImmediate(SimInstruction* instr) { // Instruction fields. Opcode op = instr->opcodeFieldRaw(); int32_t rs = getRegister(instr->rsValue()); uint32_t rs_u = static_cast<uint32_t>(rs); int32_t rt_reg = instr->rtValue(); // Destination register. int32_t rt = getRegister(rt_reg); int16_t imm16 = instr->imm16Value(); int32_t ft_reg = instr->ftValue(); // Destination register. // Zero extended immediate. uint32_t oe_imm16 = 0xffff & imm16; // Sign extended immediate. int32_t se_imm16 = imm16; // Get current pc. int32_t current_pc = get_pc(); // Next pc. int32_t next_pc = bad_ra; // Used for conditional branch instructions. bool do_branch = false; bool execute_branch_delay_instruction = false; // Used for arithmetic instructions. int32_t alu_out = 0; // Floating point. double fp_out = 0.0; uint32_t cc, cc_value, fcsr_cc; // Used for memory instructions. uint32_t addr = 0x0; // Value to be written in memory. uint32_t mem_value = 0x0; // ---------- Configuration (and execution for op_regimm). switch (op) { // ------------- op_cop1. Coprocessor instructions. case op_cop1: switch (instr->rsFieldRaw()) { case rs_bc1: // Branch on coprocessor condition. cc = instr->fbccValue(); fcsr_cc = GetFCSRConditionBit(cc); cc_value = testFCSRBit(fcsr_cc); do_branch = (instr->fbtrueValue()) ? cc_value : !cc_value; execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize; } else { next_pc = current_pc + kBranchReturnOffset; } break; default: MOZ_CRASH(); } break; // ------------- op_regimm class. case op_regimm: switch (instr->rtFieldRaw()) { case rt_bltz: do_branch = (rs < 0); break; case rt_bltzal: do_branch = rs < 0; break; case rt_bgez: do_branch = rs >= 0; break; case rt_bgezal: do_branch = rs >= 0; break; default: MOZ_CRASH(); } switch (instr->rtFieldRaw()) { case rt_bltz: case rt_bltzal: case rt_bgez: case rt_bgezal: // Branch instructions common part. execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize; if (instr->isLinkingInstruction()) { setRegister(31, current_pc + kBranchReturnOffset); } } else { next_pc = current_pc + kBranchReturnOffset; } default: break; } break; // case op_regimm. // ------------- Branch instructions. // When comparing to zero, the encoding of rt field is always 0, so we don't // need to replace rt with zero. case op_beq: do_branch = (rs == rt); break; case op_bne: do_branch = rs != rt; break; case op_blez: do_branch = rs <= 0; break; case op_bgtz: do_branch = rs > 0; break; // ------------- Arithmetic instructions. case op_addi: if (HaveSameSign(rs, se_imm16)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (kRegisterskMaxValue - se_imm16); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (kRegisterskMinValue - se_imm16); } } alu_out = rs + se_imm16; break; case op_addiu: alu_out = rs + se_imm16; break; case op_slti: alu_out = (rs < se_imm16) ? 1 : 0; break; case op_sltiu: alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0; break; case op_andi: alu_out = rs & oe_imm16; break; case op_ori: alu_out = rs | oe_imm16; break; case op_xori: alu_out = rs ^ oe_imm16; break; case op_lui: alu_out = (oe_imm16 << 16); break; // ------------- Memory instructions. case op_lb: addr = rs + se_imm16; alu_out = readB(addr); break; case op_lh: addr = rs + se_imm16; alu_out = readH(addr, instr); break; case op_lwl: { // al_offset is offset of the effective address within an aligned word. uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = (1 << byte_shift * 8) - 1; addr = rs + se_imm16 - al_offset; alu_out = readW(addr, instr); alu_out <<= byte_shift * 8; alu_out |= rt & mask; break; } case op_lw: addr = rs + se_imm16; alu_out = readW(addr, instr); break; case op_lbu: addr = rs + se_imm16; alu_out = readBU(addr); break; case op_lhu: addr = rs + se_imm16; alu_out = readHU(addr, instr); break; case op_lwr: { // al_offset is offset of the effective address within an aligned word. uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0; addr = rs + se_imm16 - al_offset; alu_out = readW(addr, instr); alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8; alu_out |= rt & mask; break; } case op_sb: addr = rs + se_imm16; break; case op_sh: addr = rs + se_imm16; break; case op_swl: { uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0; addr = rs + se_imm16 - al_offset; mem_value = readW(addr, instr) & mask; mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8; break; } case op_sw: addr = rs + se_imm16; break; case op_swr: { uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint32_t mask = (1 << al_offset * 8) - 1; addr = rs + se_imm16 - al_offset; mem_value = readW(addr, instr); mem_value = (rt << al_offset * 8) | (mem_value & mask); break; } case op_lwc1: addr = rs + se_imm16; alu_out = readW(addr, instr); break; case op_ldc1: addr = rs + se_imm16; fp_out = readD(addr, instr); break; case op_swc1: case op_sdc1: addr = rs + se_imm16; break; default: MOZ_CRASH(); } // ---------- Raise exceptions triggered. signalExceptions(); // ---------- Execution. switch (op) { // ------------- Branch instructions. case op_beq: case op_bne: case op_blez: case op_bgtz: // Branch instructions common part. execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + SimInstruction::kInstrSize; if (instr->isLinkingInstruction()) { setRegister(31, current_pc + 2 * SimInstruction::kInstrSize); } } else { next_pc = current_pc + 2 * SimInstruction::kInstrSize; } break; // ------------- Arithmetic instructions. case op_addi: case op_addiu: case op_slti: case op_sltiu: case op_andi: case op_ori: case op_xori: case op_lui: setRegister(rt_reg, alu_out); break; // ------------- Memory instructions. case op_lb: case op_lh: case op_lwl: case op_lw: case op_lbu: case op_lhu: case op_lwr: setRegister(rt_reg, alu_out); break; case op_sb: writeB(addr, static_cast<int8_t>(rt)); break; case op_sh: writeH(addr, static_cast<uint16_t>(rt), instr); break; case op_swl: writeW(addr, mem_value, instr); break; case op_sw: writeW(addr, rt, instr); break; case op_swr: writeW(addr, mem_value, instr); break; case op_lwc1: setFpuRegister(ft_reg, alu_out); break; case op_ldc1: setFpuRegisterDouble(ft_reg, fp_out); break; case op_swc1: addr = rs + se_imm16; writeW(addr, getFpuRegister(ft_reg), instr); break; case op_sdc1: addr = rs + se_imm16; writeD(addr, getFpuRegisterDouble(ft_reg), instr); break; default: break; } if (execute_branch_delay_instruction) { // Execute branch delay slot // We don't check for end_sim_pc. First it should not be met as the current // pc is valid. Secondly a jump should always execute its branch delay slot. SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>(current_pc + SimInstruction::kInstrSize); branchDelayInstructionDecode(branch_delay_instr); } // If needed update pc after the branch delay execution. if (next_pc != bad_ra) set_pc(next_pc); } // Type 3: instructions using a 26 bytes immediate. (e.g. j, jal). void Simulator::decodeTypeJump(SimInstruction* instr) { // Get current pc. int32_t current_pc = get_pc(); // Get unchanged bits of pc. int32_t pc_high_bits = current_pc & 0xf0000000; // Next pc. int32_t next_pc = pc_high_bits | (instr->imm26Value() << 2); // Execute branch delay slot. // We don't check for end_sim_pc. First it should not be met as the current pc // is valid. Secondly a jump should always execute its branch delay slot. SimInstruction* branch_delay_instr = reinterpret_cast<SimInstruction*>(current_pc + SimInstruction::kInstrSize); branchDelayInstructionDecode(branch_delay_instr); // Update pc and ra if necessary. // Do this after the branch delay execution. if (instr->isLinkingInstruction()) setRegister(31, current_pc + 2 * SimInstruction::kInstrSize); set_pc(next_pc); pc_modified_ = true; } // Executes the current instruction. void Simulator::instructionDecode(SimInstruction* instr) { if (Simulator::ICacheCheckingEnabled) { AutoLockSimulatorCache als(this); checkICacheLocked(icache(), instr); } pc_modified_ = false; switch (instr->instructionType()) { case SimInstruction::kRegisterType: decodeTypeRegister(instr); break; case SimInstruction::kImmediateType: decodeTypeImmediate(instr); break; case SimInstruction::kJumpType: decodeTypeJump(instr); break; default: UNSUPPORTED(); } if (!pc_modified_) setRegister(pc, reinterpret_cast<int32_t>(instr) + SimInstruction::kInstrSize); } void Simulator::branchDelayInstructionDecode(SimInstruction* instr) { if (instr->instructionBits() == NopInst) { // Short-cut generic nop instructions. They are always valid and they // never change the simulator state. return; } if (instr->isForbiddenInBranchDelay()) { MOZ_CRASH("Eror:Unexpected opcode in a branch delay slot."); } instructionDecode(instr); } template<bool enableStopSimAt> void Simulator::execute() { // Get the PC to simulate. Cannot use the accessor here as we need the // raw PC value and not the one used as input to arithmetic instructions. int program_counter = get_pc(); WasmActivation* activation = TlsPerThreadData.get()->runtimeFromMainThread()->wasmActivationStack(); while (program_counter != end_sim_pc) { if (enableStopSimAt && (icount_ == Simulator::StopSimAt)) { MipsDebugger dbg(this); dbg.debug(); } else { SimInstruction* instr = reinterpret_cast<SimInstruction*>(program_counter); instructionDecode(instr); icount_++; int32_t rpc = resume_pc_; if (MOZ_UNLIKELY(rpc != 0)) { // wasm signal handler ran and we have to adjust the pc. activation->setResumePC((void*)get_pc()); set_pc(rpc); resume_pc_ = 0; } } program_counter = get_pc(); } } void Simulator::callInternal(uint8_t* entry) { // Prepare to execute the code at entry. setRegister(pc, reinterpret_cast<int32_t>(entry)); // Put down marker for end of simulation. The simulator will stop simulation // when the PC reaches this value. By saving the "end simulation" value into // the LR the simulation stops when returning to this call point. setRegister(ra, end_sim_pc); // Remember the values of callee-saved registers. // The code below assumes that r9 is not used as sb (static base) in // simulator code and therefore is regarded as a callee-saved register. int32_t s0_val = getRegister(s0); int32_t s1_val = getRegister(s1); int32_t s2_val = getRegister(s2); int32_t s3_val = getRegister(s3); int32_t s4_val = getRegister(s4); int32_t s5_val = getRegister(s5); int32_t s6_val = getRegister(s6); int32_t s7_val = getRegister(s7); int32_t gp_val = getRegister(gp); int32_t sp_val = getRegister(sp); int32_t fp_val = getRegister(fp); // Set up the callee-saved registers with a known value. To be able to check // that they are preserved properly across JS execution. int32_t callee_saved_value = icount_; setRegister(s0, callee_saved_value); setRegister(s1, callee_saved_value); setRegister(s2, callee_saved_value); setRegister(s3, callee_saved_value); setRegister(s4, callee_saved_value); setRegister(s5, callee_saved_value); setRegister(s6, callee_saved_value); setRegister(s7, callee_saved_value); setRegister(gp, callee_saved_value); setRegister(fp, callee_saved_value); // Start the simulation. if (Simulator::StopSimAt != -1) execute<true>(); else execute<false>(); // Check that the callee-saved registers have been preserved. MOZ_ASSERT(callee_saved_value == getRegister(s0)); MOZ_ASSERT(callee_saved_value == getRegister(s1)); MOZ_ASSERT(callee_saved_value == getRegister(s2)); MOZ_ASSERT(callee_saved_value == getRegister(s3)); MOZ_ASSERT(callee_saved_value == getRegister(s4)); MOZ_ASSERT(callee_saved_value == getRegister(s5)); MOZ_ASSERT(callee_saved_value == getRegister(s6)); MOZ_ASSERT(callee_saved_value == getRegister(s7)); MOZ_ASSERT(callee_saved_value == getRegister(gp)); MOZ_ASSERT(callee_saved_value == getRegister(fp)); // Restore callee-saved registers with the original value. setRegister(s0, s0_val); setRegister(s1, s1_val); setRegister(s2, s2_val); setRegister(s3, s3_val); setRegister(s4, s4_val); setRegister(s5, s5_val); setRegister(s6, s6_val); setRegister(s7, s7_val); setRegister(gp, gp_val); setRegister(sp, sp_val); setRegister(fp, fp_val); } int32_t Simulator::call(uint8_t* entry, int argument_count, ...) { va_list parameters; va_start(parameters, argument_count); int original_stack = getRegister(sp); // Compute position of stack on entry to generated code. int entry_stack = original_stack; if (argument_count > kCArgSlotCount) entry_stack = entry_stack - argument_count * sizeof(int32_t); else entry_stack = entry_stack - kCArgsSlotsSize; entry_stack &= ~(ABIStackAlignment - 1); intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack); // Setup the arguments. for (int i = 0; i < argument_count; i++) { js::jit::Register argReg; if (GetIntArgReg(i, &argReg)) setRegister(argReg.code(), va_arg(parameters, int32_t)); else stack_argument[i] = va_arg(parameters, int32_t); } va_end(parameters); setRegister(sp, entry_stack); callInternal(entry); // Pop stack passed arguments. MOZ_ASSERT(entry_stack == getRegister(sp)); setRegister(sp, original_stack); int32_t result = getRegister(v0); return result; } uintptr_t Simulator::pushAddress(uintptr_t address) { int new_sp = getRegister(sp) - sizeof(uintptr_t); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp); *stack_slot = address; setRegister(sp, new_sp); return new_sp; } uintptr_t Simulator::popAddress() { int current_sp = getRegister(sp); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp); uintptr_t address = *stack_slot; setRegister(sp, current_sp + sizeof(uintptr_t)); return address; } } // namespace jit } // namespace js js::jit::Simulator* JSRuntime::simulator() const { return simulator_; } js::jit::Simulator* js::PerThreadData::simulator() const { return runtime_->simulator(); } uintptr_t* JSRuntime::addressOfSimulatorStackLimit() { return simulator_->addressOfStackLimit(); }
mpl-2.0
MozillaSecurity/FuzzManager
server/ec2spotmanager/templatetags/recursetags.py
1156
from django import template from django.utils.safestring import mark_safe register = template.Library() class RecurseConfigTree(template.Node): def __init__(self, template_nodes, config_var): self.template_nodes = template_nodes self.config_var = config_var def _render_node(self, context, node): context.push() context['node'] = node children = [self._render_node(context, x) for x in node.children] if node.children: context['children'] = mark_safe(''.join(children)) rendered = self.template_nodes.render(context) context.pop() return rendered def render(self, context): return self._render_node(context, self.config_var.resolve(context)) @register.tag def recurseconfig(parser, token): bits = token.contents.split() if len(bits) != 2: raise template.TemplateSyntaxError(_('%s tag requires a start configuration') % bits[0]) # noqa config_var = template.Variable(bits[1]) template_nodes = parser.parse(('endrecurseconfig',)) parser.delete_first_token() return RecurseConfigTree(template_nodes, config_var)
mpl-2.0
richardwilkes/gcs
com.trollworks.gcs/src/com/trollworks/gcs/ui/widget/Checkbox.java
7714
/* * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package com.trollworks.gcs.ui.widget; import com.trollworks.gcs.ui.Colors; import com.trollworks.gcs.ui.FontAwesome; import com.trollworks.gcs.ui.Fonts; import com.trollworks.gcs.ui.GraphicsUtilities; import com.trollworks.gcs.ui.MouseCapture; import com.trollworks.gcs.ui.TextDrawing; import com.trollworks.gcs.ui.UIUtilities; import com.trollworks.gcs.ui.scale.Scale; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.SwingConstants; public class Checkbox extends Panel implements MouseListener, MouseMotionListener, KeyListener, FocusListener { private String mText; private ClickFunction mClickFunction; private Rectangle mOverBounds; private boolean mInMouseDown; private boolean mPressed; private boolean mChecked; public interface ClickFunction { void checkboxClicked(Checkbox checkbox); } public Checkbox(String text, boolean checked, ClickFunction clickFunction) { super(null, false); mOverBounds = new Rectangle(); setText(text); setCursor(Cursor.getDefaultCursor()); setClickFunction(clickFunction); setFocusable(true); addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); addFocusListener(this); mChecked = checked; } /** @return The text. */ public String getText() { return mText; } /** @param text The text to use. */ public void setText(String text) { if (text == null) { text = ""; } if (!text.equals(mText)) { mText = text; invalidate(); } } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { mChecked = checked; repaint(); } public void setClickFunction(ClickFunction clickFunction) { mClickFunction = clickFunction; } public void click() { boolean wasPressed = mPressed; mPressed = true; int width = getWidth(); int height = getHeight(); paintImmediately(0, 0, width, height); try { Thread.sleep(100); } catch (InterruptedException ex) { // Ignore } mChecked = !mChecked; mPressed = wasPressed; paintImmediately(0, 0, width, height); if (mClickFunction != null) { mClickFunction.checkboxClicked(this); } } @Override public void focusGained(FocusEvent event) { repaint(); scrollRectToVisible(UIUtilities.getLocalBounds(this)); } @Override public void focusLost(FocusEvent event) { repaint(); } @Override public void keyTyped(KeyEvent event) { if (isEnabled() && event.getKeyChar() == ' ' && event.getModifiersEx() == 0) { click(); } } @Override public void keyPressed(KeyEvent event) { // Unused } @Override public void keyReleased(KeyEvent event) { // Unused } @Override public void mouseClicked(MouseEvent event) { // Unused } @Override public void mousePressed(MouseEvent event) { if (isEnabled() && !event.isPopupTrigger() && event.getButton() == 1) { mInMouseDown = true; mPressed = mOverBounds.contains(event.getPoint()); repaint(); MouseCapture.start(this, Cursor.getDefaultCursor()); } } @Override public void mouseReleased(MouseEvent event) { if (isEnabled()) { mouseDragged(event); mInMouseDown = false; MouseCapture.stop(this); if (mPressed) { mPressed = false; click(); } repaint(); } } @Override public void mouseEntered(MouseEvent event) { // Unused } @Override public void mouseExited(MouseEvent event) { // Unused } @Override public void mouseDragged(MouseEvent event) { if (isEnabled()) { boolean wasPressed = mPressed; mPressed = mOverBounds.contains(event.getPoint()); if (mPressed != wasPressed) { repaint(); } } } @Override public void mouseMoved(MouseEvent event) { // Unused } @Override public Dimension getPreferredSize() { if (isPreferredSizeSet()) { return super.getPreferredSize(); } Insets insets = getInsets(); Scale scale = Scale.get(this); Font font = scale.scale(getFont()); Dimension size = TextDrawing.getPreferredSize(new Font(Fonts.FONT_AWESOME_SOLID, Font.PLAIN, font.getSize()), FontAwesome.CHECK_CIRCLE); if (!mText.isBlank()) { Dimension textSize = TextDrawing.getPreferredSize(font, mText); size.width += textSize.width + scale.scale(4); size.height = Math.max(size.height, textSize.height); } size.width += insets.left + insets.right; size.height += insets.top + insets.bottom + scale.scale(4); return size; } @Override protected void paintComponent(Graphics g) { Rectangle bounds = UIUtilities.getLocalInsetBounds(this); Color color; if (mPressed) { color = Colors.ICON_BUTTON_PRESSED; } else if (isEnabled()) { color = Colors.ICON_BUTTON; } else { color = Colors.getWithAlpha(Colors.ICON_BUTTON, 96); } Graphics2D gc = GraphicsUtilities.prepare(g); Scale scale = Scale.get(this); Font font = scale.scale(getFont()); boolean focusOwner = isFocusOwner(); Font iconFont = new Font(focusOwner ? Fonts.FONT_AWESOME_SOLID : Fonts.FONT_AWESOME_REGULAR, Font.PLAIN, font.getSize()); Dimension size = TextDrawing.getPreferredSize(iconFont, FontAwesome.CHECK_CIRCLE); gc.setFont(iconFont); gc.setColor(color); mOverBounds.x = bounds.x; mOverBounds.y = bounds.y; mOverBounds.width = size.width; mOverBounds.height = bounds.height; String unchecked = focusOwner ? FontAwesome.DOT_CIRCLE : FontAwesome.CIRCLE; TextDrawing.draw(gc, mOverBounds, mChecked ? FontAwesome.CHECK_CIRCLE : unchecked, SwingConstants.CENTER, SwingConstants.CENTER); if (!mText.isBlank()) { gc.setFont(font); gc.setColor(getForeground()); bounds.x += size.width + scale.scale(4); bounds.width -= size.width + scale.scale(4); TextDrawing.draw(gc, bounds, TextDrawing.truncateIfNecessary(font, mText, bounds.width, SwingConstants.CENTER), SwingConstants.LEFT, SwingConstants.CENTER); } } }
mpl-2.0
Photolude/Mob-Platform
PlatformWebsite/src/main/java/com/mob/www/platform/controller/AppsController.java
5347
package com.mob.www.platform.controller; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.mob.commons.plugins.servicemodel.ExternalAttribution; import com.mob.commons.plugins.servicemodel.PluginDataCall; import com.mob.commons.plugins.servicemodel.PluginDefinition; import com.mob.commons.plugins.servicemodel.PluginPage; import com.mob.commons.plugins.servicemodel.PluginScript; import com.mob.commons.service.clients.IPluginService; import com.mob.www.platform.model.DataCallResponse; import com.mob.www.platform.services.IServiceCallManager; import com.mob.www.platform.services.IServiceContracts; import com.mob.www.platform.services.ServiceCallContext; @Controller @RequestMapping("/apps/") public class AppsController { private IPluginService pluginService; public IPluginService getPluginService(){ return this.pluginService; } public AppsController setPluginService(IPluginService value) { this.pluginService = value; return this; } private IServiceContracts contractService; public IServiceContracts getContractService(){ return this.contractService; } public AppsController setContractService(IServiceContracts value) { this.contractService = value; return this; } private IServiceCallManager callManager; public IServiceCallManager getCallManager(){ return this.callManager; } public AppsController setCallManager(IServiceCallManager value) { this.callManager = value; return this; } @RequestMapping(value="/{target}", method = RequestMethod.POST) public ModelAndView pluginAppPost(@PathVariable String target, HttpServletRequest request) { return processPluginRequest(target, request); } @RequestMapping(value = "/{target}", method = RequestMethod.GET) public ModelAndView pluginAppGet(@PathVariable String target, HttpServletRequest request) { return processPluginRequest(target, request); } public ModelAndView processPluginRequest(@PathVariable String target, HttpServletRequest request) { if(target == null || target.length() == 0) { return new ModelAndView(PlatformController.REDIRECT_TO_HOME); } ServiceCallContext context = null; try { context = new ServiceCallContext(request); } catch(IllegalArgumentException e) { return new ModelAndView(PlatformController.REDIRECT_TO_HOME); } PluginPage page = this.pluginService.getPagePlugins(context.getUserToken(), target); if(request.getRequestURI() != null && !request.getRequestURI().equals("/") && (page == null || page.getScripts() == null || page.getScripts().length == 0)) { return new ModelAndView(PlatformController.REDIRECT_TO_HOME); } this.contractService.setExternalServices(page, context); PluginDataCall[] dataCalls = page.getDataCalls(); DataCallResponse[] responses = this.callManager.callDataCalls(dataCalls, context); context.setActiveScripts(page.getScripts()); List<ExternalAttribution> attributionsList = new LinkedList<ExternalAttribution>(); if(page.getPlugins() != null) { for(PluginDefinition plugin : page.getPlugins()) { if(plugin.getAttributions() != null) { for(ExternalAttribution attribute : plugin.getAttributions()) { attributionsList.add(attribute); } } } } String attributionString = "[]"; if(attributionsList.size() > 0) { ObjectMapper mapper = new ObjectMapper(); try { attributionString = new String(mapper.writeValueAsBytes(attributionsList.toArray(new ExternalAttribution[attributionsList.size()]))); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ModelAndView retval = new ModelAndView("index"); retval.addObject(PlatformController.MODEL_PLUGINS, page.getScripts()); retval.addObject(PlatformController.MODEL_DATA_CALLS, responses); retval.addObject(PlatformController.MODEL_ATTRIBUTIONS, attributionString.replace("\\", "\\\\").replace("\"", "\\\"")); return retval; } @RequestMapping(value = "/script/{scriptName:.+}", method = RequestMethod.GET) @ResponseBody public String getScript(@PathVariable String scriptName, HttpServletRequest request, HttpServletResponse response) { ServiceCallContext context = new ServiceCallContext(request); PluginScript[] scripts = context.getActiveScripts(); if(scripts == null) { return ""; } String retval = ""; for(PluginScript script : scripts) { if(script.getName() != null && script.getName().equals(scriptName)) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/javascript"); retval = script.getScript(); break; } } return retval; } }
mpl-2.0
ubschmidt2/terraform-provider-google
google/resource_spanner_instance_generated_test.go
2245
// ---------------------------------------------------------------------------- // // *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** // // ---------------------------------------------------------------------------- // // This file is automatically generated by Magic Modules and manual // changes will be clobbered when the file is regenerated. // // Please read more about how to change this file in // .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package google import ( "fmt" "strings" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccSpannerInstance_spannerInstanceBasicExample(t *testing.T) { t.Parallel() context := map[string]interface{}{ "random_suffix": acctest.RandString(10), } resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckSpannerInstanceDestroy, Steps: []resource.TestStep{ { Config: testAccSpannerInstance_spannerInstanceBasicExample(context), }, { ResourceName: "google_spanner_instance.example", ImportState: true, ImportStateVerify: true, }, }, }) } func testAccSpannerInstance_spannerInstanceBasicExample(context map[string]interface{}) string { return Nprintf(` resource "google_spanner_instance" "example" { config = "regional-us-central1" display_name = "Test Spanner Instance" num_nodes = 2 labels = { "foo" = "bar" } } `, context) } func testAccCheckSpannerInstanceDestroy(s *terraform.State) error { for name, rs := range s.RootModule().Resources { if rs.Type != "google_spanner_instance" { continue } if strings.HasPrefix(name, "data.") { continue } config := testAccProvider.Meta().(*Config) url, err := replaceVarsForTest(config, rs, "{{SpannerBasePath}}projects/{{project}}/instances/{{name}}") if err != nil { return err } _, err = sendRequest(config, "GET", "", url, nil) if err == nil { return fmt.Errorf("SpannerInstance still exists at %s", url) } } return nil }
mpl-2.0
vladikoff/fxa-relier-client
tasks/bump.js
479
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ module.exports = function (grunt) { 'use strict'; grunt.config('bump', { options: { files: ['package.json', 'bower.json'], push: false, createTag: false, commitFiles: ['-a'], commitMessage: 'Start of release %VERSION%' } }); };
mpl-2.0
jryans/servo
components/script/dom/xmlhttprequest.rs
41626
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMethods; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseTypeValues::{_empty, Document, Json, Text}; use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast, XMLHttpRequestDerived}; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible, InvalidState, InvalidAccess}; use dom::bindings::error::{Network, Syntax, Security, Abort, Timeout}; use dom::bindings::global::{GlobalField, GlobalRef, WorkerField}; use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootedRootable}; use dom::bindings::str::ByteString; use dom::bindings::trace::{Traceable, Untraceable}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::document::Document; use dom::event::Event; use dom::eventtarget::{EventTarget, EventTargetHelpers, XMLHttpRequestTargetTypeId}; use dom::progressevent::ProgressEvent; use dom::urlsearchparams::URLSearchParamsHelpers; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use dom::xmlhttprequestupload::XMLHttpRequestUpload; use encoding::all::UTF_8; use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecodeReplace, Encoding, EncodingRef, EncodeReplace}; use http::headers::response::HeaderCollection as ResponseHeaderCollection; use http::headers::request::HeaderCollection as RequestHeaderCollection; use http::headers::content_type::MediaType; use http::headers::{HeaderEnum, HeaderValueByteIterator}; use http::headers::request::Header; use http::method::{Method, Get, Head, Connect, Trace, ExtensionMethod}; use http::status::Status; use js::jsapi::{JS_AddObjectRoot, JS_ParseJSON, JS_RemoveObjectRoot, JSContext}; use js::jsapi::JS_ClearPendingException; use js::jsval::{JSVal, NullValue, UndefinedValue}; use libc; use libc::c_void; use net::resource_task::{ResourceTask, ResourceCORSData, Load, LoadData, Payload, Done}; use cors::{allow_cross_origin_request, CORSRequest, CORSMode, ForcedPreflightMode}; use script_task::{ScriptChan, XHRProgressMsg}; use servo_util::str::DOMString; use servo_util::task::spawn_named; use std::ascii::StrAsciiExt; use std::cell::{Cell, RefCell}; use std::comm::{Sender, Receiver, channel}; use std::io::{BufReader, MemWriter, Timer}; use std::from_str::FromStr; use std::path::BytesContainer; use std::task::TaskBuilder; use std::time::duration::Duration; use std::num::Zero; use time; use url::{Url, UrlParser}; use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams, StringOrURLSearchParams}; pub type SendParam = StringOrURLSearchParams; #[deriving(PartialEq,Encodable)] pub enum XMLHttpRequestId { XMLHttpRequestTypeId, XMLHttpRequestUploadTypeId } #[deriving(PartialEq, Encodable)] enum XMLHttpRequestState { Unsent = 0, Opened = 1, HeadersReceived = 2, Loading = 3, XHRDone = 4, // So as not to conflict with the ProgressMsg `Done` } pub enum XHRProgress { /// Notify that headers have been received HeadersReceivedMsg(Option<ResponseHeaderCollection>, Status), /// Partial progress (after receiving headers), containing portion of the response LoadingMsg(ByteString), /// Loading is done DoneMsg, /// There was an error (Abort or Timeout). For a network or other error, just pass None ErroredMsg(Option<Error>), /// Timeout was reached TimeoutMsg } enum SyncOrAsync<'a> { Sync(JSRef<'a, XMLHttpRequest>), Async(TrustedXHRAddress, ScriptChan) } #[deriving(Encodable)] #[must_root] pub struct XMLHttpRequest { eventtarget: XMLHttpRequestEventTarget, ready_state: Traceable<Cell<XMLHttpRequestState>>, timeout: Traceable<Cell<u32>>, with_credentials: Traceable<Cell<bool>>, upload: JS<XMLHttpRequestUpload>, response_url: DOMString, status: Traceable<Cell<u16>>, status_text: Traceable<RefCell<ByteString>>, response: Traceable<RefCell<ByteString>>, response_type: Traceable<Cell<XMLHttpRequestResponseType>>, response_xml: Cell<Option<JS<Document>>>, response_headers: Untraceable<RefCell<ResponseHeaderCollection>>, // Associated concepts request_method: Untraceable<RefCell<Method>>, request_url: Untraceable<RefCell<Option<Url>>>, request_headers: Untraceable<RefCell<RequestHeaderCollection>>, request_body_len: Traceable<Cell<uint>>, sync: Traceable<Cell<bool>>, upload_complete: Traceable<Cell<bool>>, upload_events: Traceable<Cell<bool>>, send_flag: Traceable<Cell<bool>>, global: GlobalField, pinned_count: Traceable<Cell<uint>>, timer: Untraceable<RefCell<Timer>>, fetch_time: Traceable<Cell<i64>>, timeout_pinned: Traceable<Cell<bool>>, terminate_sender: Untraceable<RefCell<Option<Sender<Error>>>>, } impl XMLHttpRequest { pub fn new_inherited(global: &GlobalRef) -> XMLHttpRequest { XMLHttpRequest { eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestTypeId), ready_state: Traceable::new(Cell::new(Unsent)), timeout: Traceable::new(Cell::new(0u32)), with_credentials: Traceable::new(Cell::new(false)), upload: JS::from_rooted(XMLHttpRequestUpload::new(global)), response_url: "".to_string(), status: Traceable::new(Cell::new(0)), status_text: Traceable::new(RefCell::new(ByteString::new(vec!()))), response: Traceable::new(RefCell::new(ByteString::new(vec!()))), response_type: Traceable::new(Cell::new(_empty)), response_xml: Cell::new(None), response_headers: Untraceable::new(RefCell::new(ResponseHeaderCollection::new())), request_method: Untraceable::new(RefCell::new(Get)), request_url: Untraceable::new(RefCell::new(None)), request_headers: Untraceable::new(RefCell::new(RequestHeaderCollection::new())), request_body_len: Traceable::new(Cell::new(0)), sync: Traceable::new(Cell::new(false)), send_flag: Traceable::new(Cell::new(false)), upload_complete: Traceable::new(Cell::new(false)), upload_events: Traceable::new(Cell::new(false)), global: GlobalField::from_rooted(global), pinned_count: Traceable::new(Cell::new(0)), timer: Untraceable::new(RefCell::new(Timer::new().unwrap())), fetch_time: Traceable::new(Cell::new(0)), timeout_pinned: Traceable::new(Cell::new(false)), terminate_sender: Untraceable::new(RefCell::new(None)), } } pub fn new(global: &GlobalRef) -> Temporary<XMLHttpRequest> { reflect_dom_object(box XMLHttpRequest::new_inherited(global), global, XMLHttpRequestBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<XMLHttpRequest>> { Ok(XMLHttpRequest::new(global)) } pub fn handle_xhr_progress(addr: TrustedXHRAddress, progress: XHRProgress) { unsafe { let xhr = JS::from_trusted_xhr_address(addr).root(); xhr.deref().process_partial_response(progress); } } fn fetch(fetch_type: &SyncOrAsync, resource_task: ResourceTask, mut load_data: LoadData, terminate_receiver: Receiver<Error>, cors_request: Result<Option<CORSRequest>,()>) -> ErrorResult { fn notify_partial_progress(fetch_type: &SyncOrAsync, msg: XHRProgress) { match *fetch_type { Sync(xhr) => { xhr.process_partial_response(msg); }, Async(addr, ref script_chan) => { let ScriptChan(ref chan) = *script_chan; chan.send(XHRProgressMsg(addr, msg)); } } } match cors_request { Err(_) => return Err(Network), // Happens in case of cross-origin non-http URIs Ok(Some(ref req)) => { let response = req.http_fetch(); if response.network_error { return Err(Network) } else { load_data.cors = Some(ResourceCORSData { preflight: req.preflight_flag, origin: req.origin.clone() }) } }, _ => {} } // Step 10, 13 let (start_chan, start_port) = channel(); resource_task.send(Load(load_data, start_chan)); let response = start_port.recv(); match terminate_receiver.try_recv() { Ok(e) => return Err(e), _ => {} } match cors_request { Ok(Some(ref req)) => { match response.metadata.headers { Some(ref h) if allow_cross_origin_request(req, h) => {}, _ => return Err(Network) } }, _ => {} } // XXXManishearth Clear cache entries in case of a network error notify_partial_progress(fetch_type, HeadersReceivedMsg( response.metadata.headers.clone(), response.metadata.status.clone())); let mut buf = vec!(); loop { let progress = response.progress_port.recv(); match terminate_receiver.try_recv() { Ok(e) => return Err(e), _ => {} } match progress { Payload(data) => { buf.push_all(data.as_slice()); notify_partial_progress(fetch_type, LoadingMsg(ByteString::new(buf.clone()))); }, Done(Ok(())) => { notify_partial_progress(fetch_type, DoneMsg); return Ok(()); }, Done(Err(_)) => { notify_partial_progress(fetch_type, ErroredMsg(None)); return Err(Network) } } } } } impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> { fn GetOnreadystatechange(self) -> Option<EventHandlerNonNull> { let eventtarget: JSRef<EventTarget> = EventTargetCast::from_ref(self); eventtarget.get_event_handler_common("readystatechange") } fn SetOnreadystatechange(self, listener: Option<EventHandlerNonNull>) { let eventtarget: JSRef<EventTarget> = EventTargetCast::from_ref(self); eventtarget.set_event_handler_common("readystatechange", listener) } fn ReadyState(self) -> u16 { self.ready_state.deref().get() as u16 } fn Open(self, method: ByteString, url: DOMString) -> ErrorResult { // Clean up from previous requests, if any: self.cancel_timeout(); let uppercase_method = method.as_str().map(|s| { let upper = s.to_ascii_upper(); match upper.as_slice() { "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" | "TRACK" => upper, _ => s.to_string() } }); let maybe_method: Option<Method> = uppercase_method.and_then(|s| { // Note: rust-http tests against the uppercase versions // Since we want to pass methods not belonging to the short list above // without changing capitalization, this will actually sidestep rust-http's type system // since methods like "patch" or "PaTcH" will be considered extension methods // despite the there being a rust-http method variant for them Method::from_str_or_new(s.as_slice()) }); // Step 2 match maybe_method { // Step 4 Some(Connect) | Some(Trace) => Err(Security), Some(ExtensionMethod(ref t)) if t.as_slice() == "TRACK" => Err(Security), Some(_) if method.is_token() => { *self.request_method.deref().borrow_mut() = maybe_method.unwrap(); // Step 6 let base = self.global.root().root_ref().get_url(); let parsed_url = match UrlParser::new().base_url(&base).parse(url.as_slice()) { Ok(parsed) => parsed, Err(_) => return Err(Syntax) // Step 7 }; // XXXManishearth Do some handling of username/passwords if self.sync.deref().get() { // FIXME: This should only happen if the global environment is a document environment if self.timeout.deref().get() != 0 || self.with_credentials.deref().get() || self.response_type.deref().get() != _empty { return Err(InvalidAccess) } } // XXXManishearth abort existing requests // Step 12 *self.request_url.deref().borrow_mut() = Some(parsed_url); *self.request_headers.deref().borrow_mut() = RequestHeaderCollection::new(); self.send_flag.deref().set(false); *self.status_text.deref().borrow_mut() = ByteString::new(vec!()); self.status.deref().set(0); // Step 13 if self.ready_state.deref().get() != Opened { self.change_ready_state(Opened); } Ok(()) }, // This includes cases where as_str() returns None, and when is_token() returns false, // both of which indicate invalid extension method names _ => Err(Syntax), // Step 3 } } fn Open_(self, method: ByteString, url: DOMString, async: bool, _username: Option<DOMString>, _password: Option<DOMString>) -> ErrorResult { self.sync.deref().set(!async); self.Open(method, url) } fn SetRequestHeader(self, name: ByteString, mut value: ByteString) -> ErrorResult { if self.ready_state.deref().get() != Opened || self.send_flag.deref().get() { return Err(InvalidState); // Step 1, 2 } if !name.is_token() || !value.is_field_value() { return Err(Syntax); // Step 3, 4 } let name_str = match name.to_lower().as_str() { Some(s) => { match s { // Disallowed headers "accept-charset" | "accept-encoding" | "access-control-request-headers" | "access-control-request-method" | "connection" | "content-length" | "cookie" | "cookie2" | "date" |"dnt" | "expect" | "host" | "keep-alive" | "origin" | "referer" | "te" | "trailer" | "transfer-encoding" | "upgrade" | "user-agent" | "via" => { return Ok(()); // Step 5 }, _ => String::from_str(s) } }, None => return Err(Syntax) }; let mut collection = self.request_headers.deref().borrow_mut(); // Steps 6,7 let old_header = collection.iter().find(|ref h| -> bool { // XXXManishearth following line waiting on the rust upgrade: ByteString::new(h.header_name().into_bytes()).eq_ignore_case(&value) }); match old_header { Some(h) => { unsafe { // By step 4, the value is a subset of valid utf8 // So this unsafe block should never fail let mut buf = h.header_value(); buf.push_bytes(&[0x2C, 0x20]); buf.push_bytes(value.as_slice()); value = ByteString::new(buf.container_into_owned_bytes()); } }, None => {} } let mut reader = BufReader::new(value.as_slice()); let maybe_header: Option<Header> = HeaderEnum::value_from_stream( name_str, &mut HeaderValueByteIterator::new(&mut reader)); match maybe_header { Some(h) => { // Overwrites existing headers, which we want since we have // prepended the new header value with the old one already collection.insert(h); Ok(()) }, None => Err(Syntax) } } fn Timeout(self) -> u32 { self.timeout.deref().get() } fn SetTimeout(self, timeout: u32) -> ErrorResult { if self.sync.deref().get() { // FIXME: Not valid for a worker environment Err(InvalidState) } else { self.timeout.deref().set(timeout); if self.send_flag.deref().get() { if timeout == 0 { self.cancel_timeout(); return Ok(()); } let progress = time::now().to_timespec().sec - self.fetch_time.deref().get(); if timeout > (progress * 1000) as u32 { self.set_timeout(timeout - (progress * 1000) as u32); } else { // Immediately execute the timeout steps self.set_timeout(0); } } Ok(()) } } fn WithCredentials(self) -> bool { self.with_credentials.deref().get() } fn SetWithCredentials(self, with_credentials: bool) { self.with_credentials.deref().set(with_credentials); } fn Upload(self) -> Temporary<XMLHttpRequestUpload> { Temporary::new(self.upload) } fn Send(self, data: Option<SendParam>) -> ErrorResult { if self.ready_state.deref().get() != Opened || self.send_flag.deref().get() { return Err(InvalidState); // Step 1, 2 } let data = match *self.request_method.deref().borrow() { Get | Head => None, // Step 3 _ => data }; let extracted = data.map(|d| d.extract()); self.request_body_len.set(extracted.as_ref().map(|e| e.len()).unwrap_or(0)); // Step 6 self.upload_events.deref().set(false); // Step 7 self.upload_complete.deref().set(match extracted { None => true, Some (ref v) if v.len() == 0 => true, _ => false }); let mut addr = None; if !self.sync.deref().get() { // If one of the event handlers below aborts the fetch, // the assertion in release_once() will fail since we haven't pinned it yet. // Pin early to avoid dealing with this unsafe { addr = Some(self.to_trusted()); } // Step 8 let upload_target = *self.upload.root(); let event_target: JSRef<EventTarget> = EventTargetCast::from_ref(upload_target); if event_target.has_handlers() { self.upload_events.deref().set(true); } // Step 9 self.send_flag.deref().set(true); self.dispatch_response_progress_event("loadstart".to_string()); if !self.upload_complete.deref().get() { self.dispatch_upload_progress_event("loadstart".to_string(), Some(0)); } } if self.ready_state.deref().get() == Unsent { // The progress events above might have run abort(), in which case we terminate the fetch. return Ok(()); } let global = self.global.root(); let resource_task = global.root_ref().resource_task(); let mut load_data = LoadData::new(self.request_url.deref().borrow().clone().unwrap()); load_data.data = extracted; // Default headers let request_headers = self.request_headers.deref(); if request_headers.borrow().content_type.is_none() { let parameters = vec!((String::from_str("charset"), String::from_str("UTF-8"))); request_headers.borrow_mut().content_type = match data { Some(eString(_)) => Some(MediaType { type_: String::from_str("text"), subtype: String::from_str("plain"), parameters: parameters }), Some(eURLSearchParams(_)) => Some(MediaType { type_: String::from_str("application"), subtype: String::from_str("x-www-form-urlencoded"), parameters: parameters }), None => None } } if request_headers.borrow().accept.is_none() { request_headers.borrow_mut().accept = Some(String::from_str("*/*")) } load_data.headers = (*self.request_headers.deref().borrow()).clone(); load_data.method = (*self.request_method.deref().borrow()).clone(); let (terminate_sender, terminate_receiver) = channel(); *self.terminate_sender.deref().borrow_mut() = Some(terminate_sender); // CORS stuff let referer_url = self.global.root().root_ref().get_url(); let mode = if self.upload_events.deref().get() { ForcedPreflightMode } else { CORSMode }; let cors_request = CORSRequest::maybe_new(referer_url.clone(), load_data.url.clone(), mode, load_data.method.clone(), load_data.headers.clone()); match cors_request { Ok(None) => { let mut buf = String::new(); buf.push_str(referer_url.scheme.as_slice()); buf.push_str("://".as_slice()); referer_url.serialize_host().map(|ref h| buf.push_str(h.as_slice())); referer_url.port().as_ref().map(|&p| { buf.push_str(":".as_slice()); buf.push_str(format!("{:u}", p).as_slice()); }); referer_url.serialize_path().map(|ref h| buf.push_str(h.as_slice())); self.request_headers.deref().borrow_mut().referer = Some(buf); }, Ok(Some(ref req)) => self.insert_trusted_header("origin".to_string(), format!("{}", req.origin)), _ => {} } if self.sync.deref().get() { return XMLHttpRequest::fetch(&mut Sync(self), resource_task, load_data, terminate_receiver, cors_request); } else { let builder = TaskBuilder::new().named("XHRTask"); self.fetch_time.deref().set(time::now().to_timespec().sec); let script_chan = global.root_ref().script_chan().clone(); builder.spawn(proc() { let _ = XMLHttpRequest::fetch(&mut Async(addr.unwrap(), script_chan), resource_task, load_data, terminate_receiver, cors_request); }); let timeout = self.timeout.deref().get(); if timeout > 0 { self.set_timeout(timeout); } } Ok(()) } fn Abort(self) { self.terminate_sender.deref().borrow().as_ref().map(|s| s.send_opt(Abort)); match self.ready_state.deref().get() { Opened if self.send_flag.deref().get() => self.process_partial_response(ErroredMsg(Some(Abort))), HeadersReceived | Loading => self.process_partial_response(ErroredMsg(Some(Abort))), _ => {} }; self.ready_state.deref().set(Unsent); } fn ResponseURL(self) -> DOMString { self.response_url.clone() } fn Status(self) -> u16 { self.status.deref().get() } fn StatusText(self) -> ByteString { self.status_text.deref().borrow().clone() } fn GetResponseHeader(self, name: ByteString) -> Option<ByteString> { self.filter_response_headers().iter().find(|h| { name.eq_ignore_case(&FromStr::from_str(h.header_name().as_slice()).unwrap()) }).map(|h| { // rust-http doesn't decode properly, we'll convert it back to bytes here ByteString::new(h.header_value().as_slice().chars().map(|c| { assert!(c <= '\u00FF'); c as u8 }).collect()) }) } fn GetAllResponseHeaders(self) -> ByteString { let mut writer = MemWriter::new(); self.filter_response_headers().write_all(&mut writer).ok().expect("Writing response headers failed"); let mut vec = writer.unwrap(); // rust-http appends an extra "\r\n" when using write_all vec.pop(); vec.pop(); ByteString::new(vec) } fn ResponseType(self) -> XMLHttpRequestResponseType { self.response_type.deref().get() } fn SetResponseType(self, response_type: XMLHttpRequestResponseType) -> ErrorResult { match self.global { WorkerField(_) if response_type == Document => return Ok(()), _ => {} } match self.ready_state.deref().get() { Loading | XHRDone => Err(InvalidState), _ if self.sync.deref().get() => Err(InvalidAccess), _ => { self.response_type.deref().set(response_type); Ok(()) } } } fn Response(self, cx: *mut JSContext) -> JSVal { match self.response_type.deref().get() { _empty | Text => { let ready_state = self.ready_state.deref().get(); if ready_state == XHRDone || ready_state == Loading { self.text_response().to_jsval(cx) } else { "".to_string().to_jsval(cx) } }, _ if self.ready_state.deref().get() != XHRDone => NullValue(), Json => { let decoded = UTF_8.decode(self.response.deref().borrow().as_slice(), DecodeReplace).unwrap().to_string(); let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect(); let mut vp = UndefinedValue(); unsafe { if JS_ParseJSON(cx, decoded.as_ptr(), decoded.len() as u32, &mut vp) == 0 { JS_ClearPendingException(cx); return NullValue(); } } vp } _ => { // XXXManishearth handle other response types self.response.deref().borrow().to_jsval(cx) } } } fn GetResponseText(self) -> Fallible<DOMString> { match self.response_type.deref().get() { _empty | Text => { match self.ready_state.deref().get() { Loading | XHRDone => Ok(self.text_response()), _ => Ok("".to_string()) } }, _ => Err(InvalidState) } } fn GetResponseXML(self) -> Option<Temporary<Document>> { self.response_xml.get().map(|response| Temporary::new(response)) } } impl Reflectable for XMLHttpRequest { fn reflector<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } } impl XMLHttpRequestDerived for EventTarget { fn is_xmlhttprequest(&self) -> bool { match self.type_id { XMLHttpRequestTargetTypeId(XMLHttpRequestTypeId) => true, _ => false } } } pub struct TrustedXHRAddress(pub *const c_void); impl TrustedXHRAddress { pub fn release_once(self) { unsafe { JS::from_trusted_xhr_address(self).root().release_once(); } } } trait PrivateXMLHttpRequestHelpers { unsafe fn to_trusted(self) -> TrustedXHRAddress; fn release_once(self); fn change_ready_state(self, XMLHttpRequestState); fn process_partial_response(self, progress: XHRProgress); fn insert_trusted_header(self, name: String, value: String); fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>); fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option<u64>); fn dispatch_response_progress_event(self, type_: DOMString); fn text_response(self) -> DOMString; fn set_timeout(self, timeout:u32); fn cancel_timeout(self); fn filter_response_headers(self) -> ResponseHeaderCollection; } impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // Creates a trusted address to the object, and roots it. Always pair this with a release() unsafe fn to_trusted(self) -> TrustedXHRAddress { if self.pinned_count.deref().get() == 0 { JS_AddObjectRoot(self.global.root().root_ref().get_cx(), self.reflector().rootable()); } let pinned_count = self.pinned_count.deref().get(); self.pinned_count.deref().set(pinned_count + 1); TrustedXHRAddress(self.deref() as *const XMLHttpRequest as *const libc::c_void) } fn release_once(self) { if self.sync.deref().get() { // Lets us call this at various termination cases without having to // check self.sync every time, since the pinning mechanism only is // meaningful during an async fetch return; } assert!(self.pinned_count.deref().get() > 0) let pinned_count = self.pinned_count.deref().get(); self.pinned_count.deref().set(pinned_count - 1); if self.pinned_count.deref().get() == 0 { unsafe { JS_RemoveObjectRoot(self.global.root().root_ref().get_cx(), self.reflector().rootable()); } } } fn change_ready_state(self, rs: XMLHttpRequestState) { assert!(self.ready_state.deref().get() != rs) self.ready_state.deref().set(rs); let global = self.global.root(); let event = Event::new(&global.root_ref(), "readystatechange".to_string(), false, true).root(); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); target.dispatch_event_with_target(None, *event).ok(); } fn process_partial_response(self, progress: XHRProgress) { match progress { HeadersReceivedMsg(headers, status) => { // For synchronous requests, this should not fire any events, and just store data // XXXManishearth Find a way to track partial progress of the send (onprogresss for XHRUpload) // Part of step 13, send() (processing request end of file) // Substep 1 self.upload_complete.deref().set(true); // Substeps 2-4 if !self.sync.deref().get() { self.dispatch_upload_progress_event("progress".to_string(), None); self.dispatch_upload_progress_event("load".to_string(), None); self.dispatch_upload_progress_event("loadend".to_string(), None); } // Part of step 13, send() (processing response) // XXXManishearth handle errors, if any (substep 1) // Substep 2 *self.status_text.deref().borrow_mut() = ByteString::new(status.reason().container_into_owned_bytes()); self.status.deref().set(status.code()); match headers { Some(ref h) => { *self.response_headers.deref().borrow_mut() = h.clone(); } None => {} }; // Substep 3 if self.ready_state.deref().get() == Opened && !self.sync.deref().get() { self.change_ready_state(HeadersReceived); } }, LoadingMsg(partial_response) => { // For synchronous requests, this should not fire any events, and just store data // Part of step 13, send() (processing response body) // XXXManishearth handle errors, if any (substep 1) // Substep 2 if self.ready_state.deref().get() == HeadersReceived && !self.sync.deref().get() { self.change_ready_state(Loading); } // Substep 3 *self.response.deref().borrow_mut() = partial_response; // Substep 4 if !self.sync.deref().get() { self.dispatch_response_progress_event("progress".to_string()); } }, DoneMsg => { // Part of step 13, send() (processing response end of file) // XXXManishearth handle errors, if any (substep 1) // Substep 3 if self.ready_state.deref().get() == Loading || self.sync.deref().get() { // Subsubsteps 2-4 self.send_flag.deref().set(false); self.change_ready_state(XHRDone); // Subsubsteps 5-7 self.dispatch_response_progress_event("progress".to_string()); self.dispatch_response_progress_event("load".to_string()); self.dispatch_response_progress_event("loadend".to_string()); } self.cancel_timeout(); self.release_once(); }, ErroredMsg(e) => { self.send_flag.deref().set(false); // XXXManishearth set response to NetworkError self.change_ready_state(XHRDone); let errormsg = match e { Some(Abort) => "abort", Some(Timeout) => "timeout", None => "error", _ => unreachable!() }; let upload_complete: &Cell<bool> = self.upload_complete.deref(); if !upload_complete.get() { upload_complete.set(true); self.dispatch_upload_progress_event("progress".to_string(), None); self.dispatch_upload_progress_event(errormsg.to_string(), None); self.dispatch_upload_progress_event("loadend".to_string(), None); } self.dispatch_response_progress_event("progress".to_string()); self.dispatch_response_progress_event(errormsg.to_string()); self.dispatch_response_progress_event("loadend".to_string()); self.cancel_timeout(); self.release_once(); }, TimeoutMsg => { match self.ready_state.deref().get() { Opened if self.send_flag.deref().get() => self.process_partial_response(ErroredMsg(Some(Timeout))), Loading | HeadersReceived => self.process_partial_response(ErroredMsg(Some(Timeout))), _ => self.release_once() }; } } } fn insert_trusted_header(self, name: String, value: String) { // Insert a header without checking spec-compliance // Use for hardcoded headers let mut collection = self.request_headers.deref().borrow_mut(); let value_bytes = value.into_bytes(); let mut reader = BufReader::new(value_bytes.as_slice()); let maybe_header: Option<Header> = HeaderEnum::value_from_stream( String::from_str(name.as_slice()), &mut HeaderValueByteIterator::new(&mut reader)); collection.insert(maybe_header.unwrap()); } fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>) { let global = self.global.root(); let upload_target = *self.upload.root(); let progressevent = ProgressEvent::new(&global.root_ref(), type_, false, false, total.is_some(), loaded, total.unwrap_or(0)).root(); let target: JSRef<EventTarget> = if upload { EventTargetCast::from_ref(upload_target) } else { EventTargetCast::from_ref(self) }; let event: JSRef<Event> = EventCast::from_ref(*progressevent); target.dispatch_event_with_target(None, event).ok(); } fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option<u64>) { // If partial_load is None, loading has completed and we can just use the value from the request body let total = self.request_body_len.get() as u64; self.dispatch_progress_event(true, type_, partial_load.unwrap_or(total), Some(total)); } fn dispatch_response_progress_event(self, type_: DOMString) { let len = self.response.deref().borrow().len() as u64; let total = self.response_headers.deref().borrow().content_length.map(|x| {x as u64}); self.dispatch_progress_event(false, type_, len, total); } fn set_timeout(self, timeout: u32) { // Sets up the object to timeout in a given number of milliseconds // This will cancel all previous timeouts let oneshot = self.timer.deref().borrow_mut() .oneshot(Duration::milliseconds(timeout as i64)); let addr = unsafe { self.to_trusted() // This will increment the pin counter by one }; if self.timeout_pinned.deref().get() { // Already pinned due to a timeout, no need to pin it again since the old timeout was cancelled above self.release_once(); } self.timeout_pinned.deref().set(true); let global = self.global.root(); let script_chan = global.root_ref().script_chan().clone(); let terminate_sender = (*self.terminate_sender.deref().borrow()).clone(); spawn_named("XHR:Timer", proc () { match oneshot.recv_opt() { Ok(_) => { let ScriptChan(ref chan) = script_chan; terminate_sender.map(|s| s.send_opt(Timeout)); chan.send(XHRProgressMsg(addr, TimeoutMsg)); }, Err(_) => { // This occurs if xhr.timeout (the sender) goes out of scope (i.e, xhr went out of scope) // or if the oneshot timer was overwritten. The former case should not happen due to pinning. debug!("XHR timeout was overwritten or canceled") } } } ); } fn cancel_timeout(self) { // Cancels timeouts on the object, if any if self.timeout_pinned.deref().get() { self.timeout_pinned.deref().set(false); self.release_once(); } // oneshot() closes the previous channel, canceling the timeout self.timer.deref().borrow_mut().oneshot(Zero::zero()); } fn text_response(self) -> DOMString { let mut encoding = UTF_8 as EncodingRef; match self.response_headers.deref().borrow().content_type { Some(ref x) => { for &(ref name, ref value) in x.parameters.iter() { if name.as_slice().eq_ignore_ascii_case("charset") { encoding = encoding_from_whatwg_label(value.as_slice()).unwrap_or(encoding); } } }, None => {} } // According to Simon, decode() should never return an error, so unwrap()ing // the result should be fine. XXXManishearth have a closer look at this later encoding.decode(self.response.deref().borrow().as_slice(), DecodeReplace).unwrap().to_string() } fn filter_response_headers(self) -> ResponseHeaderCollection { // http://fetch.spec.whatwg.org/#concept-response-header-list let mut headers = ResponseHeaderCollection::new(); for header in self.response_headers.deref().borrow().iter() { match header.header_name().as_slice().to_ascii_lower().as_slice() { "set-cookie" | "set-cookie2" => {}, // XXXManishearth additional CORS filtering goes here _ => headers.insert(header) }; } headers } } trait Extractable { fn extract(&self) -> Vec<u8>; } impl Extractable for SendParam { fn extract(&self) -> Vec<u8> { // http://fetch.spec.whatwg.org/#concept-fetchbodyinit-extract let encoding = UTF_8 as EncodingRef; match *self { eString(ref s) => encoding.encode(s.as_slice(), EncodeReplace).unwrap(), eURLSearchParams(ref usp) => usp.root().serialize(None) // Default encoding is UTF8 } } }
mpl-2.0
ricardclau/packer
builder/hcloud/step_create_server.go
6706
package hcloud import ( "context" "fmt" "io/ioutil" "sort" "strings" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" "github.com/hetznercloud/hcloud-go/hcloud" ) type stepCreateServer struct { serverId int } func (s *stepCreateServer) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { client := state.Get("hcloudClient").(*hcloud.Client) ui := state.Get("ui").(packersdk.Ui) c := state.Get("config").(*Config) sshKeyId := state.Get("ssh_key_id").(int) // Create the server based on configuration ui.Say("Creating server...") userData := c.UserData if c.UserDataFile != "" { contents, err := ioutil.ReadFile(c.UserDataFile) if err != nil { state.Put("error", fmt.Errorf("Problem reading user data file: %s", err)) return multistep.ActionHalt } userData = string(contents) } sshKeys := []*hcloud.SSHKey{{ID: sshKeyId}} for _, k := range c.SSHKeys { sshKey, _, err := client.SSHKey.Get(ctx, k) if err != nil { ui.Error(err.Error()) state.Put("error", fmt.Errorf("Error fetching SSH key: %s", err)) return multistep.ActionHalt } if sshKey == nil { state.Put("error", fmt.Errorf("Could not find key: %s", k)) return multistep.ActionHalt } sshKeys = append(sshKeys, sshKey) } var image *hcloud.Image if c.Image != "" { image = &hcloud.Image{Name: c.Image} } else { var err error image, err = getImageWithSelectors(ctx, client, c) if err != nil { ui.Error(err.Error()) state.Put("error", err) return multistep.ActionHalt } ui.Message(fmt.Sprintf("Using image %s with ID %d", image.Description, image.ID)) } serverCreateResult, _, err := client.Server.Create(ctx, hcloud.ServerCreateOpts{ Name: c.ServerName, ServerType: &hcloud.ServerType{Name: c.ServerType}, Image: image, SSHKeys: sshKeys, Location: &hcloud.Location{Name: c.Location}, UserData: userData, }) if err != nil { err := fmt.Errorf("Error creating server: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("server_ip", serverCreateResult.Server.PublicNet.IPv4.IP.String()) // We use this in cleanup s.serverId = serverCreateResult.Server.ID // Store the server id for later state.Put("server_id", serverCreateResult.Server.ID) // instance_id is the generic term used so that users can have access to the // instance id inside of the provisioners, used in step_provision. state.Put("instance_id", serverCreateResult.Server.ID) if err := waitForAction(ctx, client, serverCreateResult.Action); err != nil { err := fmt.Errorf("Error creating server: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } for _, nextAction := range serverCreateResult.NextActions { if err := waitForAction(ctx, client, nextAction); err != nil { err := fmt.Errorf("Error creating server: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } } if c.RescueMode != "" { ui.Say("Enabling Rescue Mode...") rootPassword, err := setRescue(ctx, client, serverCreateResult.Server, c.RescueMode, sshKeys) if err != nil { err := fmt.Errorf("Error enabling rescue mode: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } ui.Say("Reboot server...") action, _, err := client.Server.Reset(ctx, serverCreateResult.Server) if err != nil { err := fmt.Errorf("Error rebooting server: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } if err := waitForAction(ctx, client, action); err != nil { err := fmt.Errorf("Error rebooting server: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } if c.RescueMode == "freebsd64" { // We will set this only on freebsd ui.Say("Using Root Password instead of SSH Keys...") c.Comm.SSHPassword = rootPassword } } return multistep.ActionContinue } func (s *stepCreateServer) Cleanup(state multistep.StateBag) { // If the serverID isn't there, we probably never created it if s.serverId == 0 { return } client := state.Get("hcloudClient").(*hcloud.Client) ui := state.Get("ui").(packersdk.Ui) // Destroy the server we just created ui.Say("Destroying server...") _, err := client.Server.Delete(context.TODO(), &hcloud.Server{ID: s.serverId}) if err != nil { ui.Error(fmt.Sprintf( "Error destroying server. Please destroy it manually: %s", err)) } } func setRescue(ctx context.Context, client *hcloud.Client, server *hcloud.Server, rescue string, sshKeys []*hcloud.SSHKey) (string, error) { rescueChanged := false if server.RescueEnabled { rescueChanged = true action, _, err := client.Server.DisableRescue(ctx, server) if err != nil { return "", err } if err := waitForAction(ctx, client, action); err != nil { return "", err } } if rescue != "" { rescueChanged = true if rescue == "freebsd64" { sshKeys = nil // freebsd64 doesn't allow ssh keys so we will remove them here } res, _, err := client.Server.EnableRescue(ctx, server, hcloud.ServerEnableRescueOpts{ Type: hcloud.ServerRescueType(rescue), SSHKeys: sshKeys, }) if err != nil { return "", err } if err := waitForAction(ctx, client, res.Action); err != nil { return "", err } return res.RootPassword, nil } if rescueChanged { action, _, err := client.Server.Reset(ctx, server) if err != nil { return "", err } if err := waitForAction(ctx, client, action); err != nil { return "", err } } return "", nil } func waitForAction(ctx context.Context, client *hcloud.Client, action *hcloud.Action) error { _, errCh := client.Action.WatchProgress(ctx, action) if err := <-errCh; err != nil { return err } return nil } func getImageWithSelectors(ctx context.Context, client *hcloud.Client, c *Config) (*hcloud.Image, error) { var allImages []*hcloud.Image var selector = strings.Join(c.ImageFilter.WithSelector, ",") opts := hcloud.ImageListOpts{ ListOpts: hcloud.ListOpts{LabelSelector: selector}, Status: []hcloud.ImageStatus{hcloud.ImageStatusAvailable}, } allImages, err := client.Image.AllWithOpts(ctx, opts) if err != nil { return nil, err } if len(allImages) == 0 { return nil, fmt.Errorf("no image found for selector %q", selector) } if len(allImages) > 1 { if !c.ImageFilter.MostRecent { return nil, fmt.Errorf("more than one image found for selector %q", selector) } sort.Slice(allImages, func(i, j int) bool { return allImages[i].Created.After(allImages[j].Created) }) } return allImages[0], nil }
mpl-2.0
diging/giles-eco-giles-web
giles-eco/src/main/java/edu/asu/diging/gilesecosystem/web/core/files/IFilesManager.java
2068
package edu.asu.diging.gilesecosystem.web.core.files; import java.util.List; import java.util.Map; import edu.asu.diging.gilesecosystem.util.exceptions.UnstorableObjectException; import edu.asu.diging.gilesecosystem.web.core.files.impl.StorageStatus; import edu.asu.diging.gilesecosystem.web.core.model.DocumentAccess; import edu.asu.diging.gilesecosystem.web.core.model.DocumentType; import edu.asu.diging.gilesecosystem.web.core.model.IDocument; import edu.asu.diging.gilesecosystem.web.core.model.IFile; import edu.asu.diging.gilesecosystem.web.core.users.User; public interface IFilesManager { /** * This method saves the given files to the database. It generates an id for * each file and an upload id that is the same for all files. * * @param files * The files to save. * @return The list of saved files with ids and upload id set. */ public abstract List<StorageStatus> addFiles(Map<IFile, byte[]> files, User user, DocumentType docType, DocumentAccess access, String uploadProgressId); public abstract List<IDocument> getDocumentsByUploadId(String uploadId); public abstract List<IFile> getFilesOfDocument(IDocument doc); public abstract String getFileUrl(IFile file); public abstract byte[] getFileContent(IFile file); public abstract List<IFile> getTextFilesOfDocument(IDocument doc); public abstract Map<String, Map<String, String>> getUploadedFilenames(String username); /** * This method changes access type for document and all files attached * as pages to this document to provided new access type * * @param doc document for which access type is requested to change * @param docAccess new access type for document * @return true if the document access change was successfully; otherwise false. * @throws UnstorableObjectException for exception while saving updated document */ public abstract boolean changeDocumentAccess(IDocument doc, DocumentAccess docAccess) throws UnstorableObjectException; }
mpl-2.0
mozilla/remote-newtab
tests/index.js
199
const req = require.context(".", true, /\.test.js$/); const files = req.keys(); const chai = require("chai"); chai.use(require("chai-as-promised")); chai.should(); files.forEach(file => req(file));
mpl-2.0
DominoTree/servo
tests/wpt/web-platform-tests/offscreen-canvas/compositing/2d.composite.image.destination-in.worker.js
1142
// DO NOT EDIT! This test has been generated by tools/gentest.py. // OffscreenCanvas test in a worker:2d.composite.image.destination-in // Description: // Note: importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test(""); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); ctx.fillStyle = 'rgba(0, 255, 255, 0.5)'; ctx.fillRect(0, 0, 100, 50); ctx.globalCompositeOperation = 'destination-in'; var promise = new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET", '/images/yellow75.png'); xhr.responseType = 'blob'; xhr.send(); xhr.onload = function() { resolve(xhr.response); }; }); promise.then(function(response) { createImageBitmap(response).then(bitmap => { ctx.drawImage(bitmap, 0, 0); _assertPixelApprox(offscreenCanvas, 50,25, 0,255,255,96, "50,25", "0,255,255,96", 5); }, t_fail); }).then(t_pass, t_fail); }); done();
mpl-2.0
jimberlage/servo
components/script/dom/console.rs
5161
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use crate::dom::workerglobalscope::WorkerGlobalScope; use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use std::io; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); impl Console { fn send_to_devtools(global: &GlobalScope, level: LogLevel, message: DOMString) { if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); let worker_id = global .downcast::<WorkerGlobalScope>() .map(|worker| worker.get_worker_id()); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, worker_id, ); chan.send(devtools_message).unwrap(); } } } // In order to avoid interleaving the stdout output of the Console API methods // with stderr that could be in use on other threads, we lock stderr until // we're finished with stdout. Since the stderr lock is reentrant, there is // no risk of deadlock if the callback ends up trying to write to stderr for // any reason. fn with_stderr_lock<F>(f: F) where F: FnOnce(), { let stderr = io::stderr(); let _handle = stderr.lock(); f() } impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log pub fn Log(global: &GlobalScope, messages: Vec<DOMString>) { with_stderr_lock(move || { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console pub fn Debug(global: &GlobalScope, messages: Vec<DOMString>) { with_stderr_lock(move || { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info pub fn Info(global: &GlobalScope, messages: Vec<DOMString>) { with_stderr_lock(move || { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn pub fn Warn(global: &GlobalScope, messages: Vec<DOMString>) { with_stderr_lock(move || { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error pub fn Error(global: &GlobalScope, messages: Vec<DOMString>) { with_stderr_lock(move || { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert pub fn Assert(global: &GlobalScope, condition: bool, message: Option<DOMString>) { with_stderr_lock(move || { if !condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); Self::send_to_devtools(global, LogLevel::Error, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: &GlobalScope, label: DOMString) { with_stderr_lock(move || { if let Ok(()) = global.time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); } }) } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: &GlobalScope, label: DOMString) { with_stderr_lock(move || { if let Ok(delta) = global.time_end(&label) { let message = DOMString::from(format!("{}: {}ms", label, delta)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); }; }) } } fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { message: String::from(message), logLevel: log_level, filename: "test".to_owned(), lineNumber: 1, columnNumber: 1, } }
mpl-2.0
richardkiene/sdc-cn-agent
lib/tasks/machine_reprovision.js
6225
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ var Task = require('../task_agent/task'); var vmadm = require('vmadm'); var async = require('async'); var common = require('../common'); var fs = require('fs'); var imgadm = require('../imgadm'); var path = require('path'); var spawn = require('child_process').spawn; var util = require('util'); var zfs = require('zfs').zfs; var MachineReprovisionTask = module.exports = function (req) { Task.call(this); this.req = req; this.zpool = req.params.zfs_storage_pool_name || 'zones'; }; Task.createTask(MachineReprovisionTask); function start(callback) { var self = this; var provisionGuardFilename; self.vmadmLogger = common.makeVmadmLogger(self); self.pre_check(function (error) { if (error) { self.fatal(error.message); return; } async.waterfall([ function (cb) { common.provisionInProgressFile( self.req.params.uuid, function (err, filename) { provisionGuardFilename = filename; cb(); return; }); }, self.ensure_dataset_present.bind(self), function (found, cb) { // The previous step (ensure..) returns a boolean indicating // whether the dataset was found. If that flag is set, we'll // run this (fetch) step and skip it if not. if (!found) { return self.fetch_dataset(cb); } else { return cb(); } }, self.reprovision_machine.bind(self) ], function (err) { fs.unlink(provisionGuardFilename, function () { var loadOpts = {}; loadOpts.log = self.log; loadOpts.req_id = self.req.req_id; loadOpts.uuid = self.req.params.uuid; loadOpts.vmadmLogger = self.vmadmLogger; if (err) { self.fatal(err.message); return; } vmadm.load( loadOpts, function (loadError, machine) { if (loadError) { self.fatal('vmadm.load error: ' + loadError.message); return; } self.finish({ vm: machine }); }); }); }); }); } function pre_check(callback) { var self = this; async.waterfall([ function (cb) { // fail if zone with uuid does not exist common.zoneList(self.req.params.uuid, function (error, zones) { if (!zones[self.req.params.uuid]) { cb(new Error( 'VM ' + self.req.params.uuid + ' does not exist.')); return; } cb(); }); } ], function (error) { if (error) { callback(error); return; } callback(); }); } function ensure_dataset_present(callback) { var self = this; var fullDataset; var params = self.req.params; // TODO Enable provisioner to be able to check a list of image_uuids and // fetch any that are not installed self.toImport = null; if (params.image_uuid) { self.toImport = params.image_uuid; } else if (self.req.params.disks && self.req.params.disks.length) { self.toImport = self.req.params.disks[0].image_uuid; } fullDataset = this.zpool + '/' + self.toImport; self.log.info( 'Checking whether zone template dataset ' + fullDataset + ' exists on the system.'); zfs.list( fullDataset, { type: 'all' }, function (error, fields, list) { if (!error && list.length) { self.log.info('Dataset ' + fullDataset + ' exists.'); callback(null, true); return; } else if (error && error.toString().match(/does not exist/)) { self.log.info('Dataset template didn\'t appear to exist.'); callback(null, false); return; } }); } function fetch_dataset(callback) { var self = this; var options = { uuid: self.toImport, zpool: self.zpool, log: self.log }; imgadm.importImage(options, function (err) { if (err) { self.log.error(err); callback(err); return; } callback(); }); } function normalizeError(error) { if (error instanceof String || typeof (error === 'string')) { return new Error(error); } return error; } function reprovision_machine(callback) { var self = this; var opts = {}; opts = self.req.params; opts.log = self.log; opts.req_id = self.req.req_id; opts.uuid = self.req.params.uuid; opts.vmadmLogger = self.vmadmLogger; vmadm.reprovision(opts, function (error) { if (error) { var msg = error instanceof Error ? error.message : error; return callback(new Error('vmadm.reprovision error: ' + msg)); } return callback(); }); } MachineReprovisionTask.setStart(start); MachineReprovisionTask.createSteps({ pre_check: { fn: pre_check, progress: 20, description: 'Pre-flight sanity check' }, ensure_dataset_present: { fn: ensure_dataset_present, progress: 30, description: 'Checking for zone template dataset' }, fetch_dataset: { fn: fetch_dataset, progress: 50, description: 'Fetching zone template dataset' }, reprovision_machine: { fn: reprovision_machine, progress: 100, description: 'Reprovisioning machine' } });
mpl-2.0
WanionCane/BiggerCraftingTables
src/main/java/wanion/biggercraftingtables/block/TileEntityBiggerCraftingTable.java
4810
package wanion.biggercraftingtables.block; /* * Created by WanionCane(https://github.com/WanionCane). * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import javax.annotation.Nonnull; public abstract class TileEntityBiggerCraftingTable extends TileEntity implements ISidedInventory { private NonNullList<ItemStack> itemStacks = NonNullList.withSize(getSizeInventory(), ItemStack.EMPTY); @Override public boolean isEmpty() { for (final ItemStack itemStack : itemStacks) if (!itemStack.isEmpty()) return false; return true; } @Nonnull @Override public ItemStack getStackInSlot(final int slot) { return itemStacks.get(slot); } @Nonnull @Override public ItemStack decrStackSize(final int slot, final int howMuch) { final ItemStack slotStack = itemStacks.get(slot); if (slotStack.isEmpty()) return ItemStack.EMPTY; final ItemStack newStack = slotStack.copy(); newStack.setCount(howMuch); slotStack.setCount(slotStack.getCount() - howMuch); if ((slotStack.getCount()) == 0) itemStacks.set(slot, ItemStack.EMPTY); return newStack; } @Nonnull @Override public ItemStack removeStackFromSlot(final int index) { final ItemStack itemStack = itemStacks.get(index); itemStacks.set(index, ItemStack.EMPTY); return itemStack; } @Override public void setInventorySlotContents(final int slot, @Nonnull final ItemStack itemStack) { itemStacks.set(slot, itemStack); } @Override public int getInventoryStackLimit() { return 64; } @Override public boolean isUsableByPlayer(@Nonnull final EntityPlayer entityPlayer) { return world.getTileEntity(pos) == this && entityPlayer.getDistanceSq((double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) getPos().getZ() + 0.5D) <= 64.0D; } @Override public void openInventory(@Nonnull final EntityPlayer player) {} @Override public void closeInventory(@Nonnull final EntityPlayer player) {} @Override public boolean isItemValidForSlot(final int slot, @Nonnull final ItemStack itemStack) { return true; } @Override public int getField(final int id) { return 0; } @Override public void setField(final int id, final int value) {} @Override public int getFieldCount() { return 0; } @Override public void clear() {} @Override public final void readFromNBT(final NBTTagCompound nbtTagCompound) { super.readFromNBT(nbtTagCompound); readCustomNBT(nbtTagCompound); } @Nonnull @Override public NBTTagCompound writeToNBT(@Nonnull final NBTTagCompound nbtTagCompound) { super.writeToNBT(nbtTagCompound); writeCustomNBT(nbtTagCompound); return nbtTagCompound; } @Nonnull public ITextComponent getDisplayName() { return new TextComponentTranslation(getName()); } void readCustomNBT(final NBTTagCompound nbtTagCompound) { final NBTTagList nbtTagList = nbtTagCompound.getTagList("Contents", 10); final int max = getSizeInventory() - 1; for (int i = 0; i < nbtTagList.tagCount(); i++) { final NBTTagCompound slotCompound = nbtTagList.getCompoundTagAt(i); final int slot = slotCompound.getShort("Slot"); if (slot >= 0 && slot < getSizeInventory()) setInventorySlotContents(slot, new ItemStack(slotCompound)); } } NBTTagCompound writeCustomNBT(final NBTTagCompound nbtTagCompound) { final NBTTagList nbtTagList = new NBTTagList(); final int max = getSizeInventory() - 1; for (int i = 0; i < max; i++) { final ItemStack itemStack = getStackInSlot(i); if (itemStack.isEmpty()) continue; final NBTTagCompound slotCompound = new NBTTagCompound(); slotCompound.setShort("Slot", (short) i); nbtTagList.appendTag(itemStack.writeToNBT(slotCompound)); } nbtTagCompound.setTag("Contents", nbtTagList); return nbtTagCompound; } @Override public boolean hasCustomName() { return false; } @Nonnull @Override public int[] getSlotsForFace(@Nonnull final EnumFacing side) { return new int[0]; } @Override public boolean canInsertItem(int index, @Nonnull final ItemStack itemStackIn, @Nonnull final EnumFacing direction) { return false; } @Override public boolean canExtractItem(final int index, @Nonnull final ItemStack stack, @Nonnull final EnumFacing direction) { return false; } }
mpl-2.0
olegccc/streams-client
src/interfaces/IConfiguration.ts
57
interface IConfiguration { ConnectionPath: string; }
mpl-2.0
wlach/treeherder
treeherder/etl/pushlog.py
8595
import logging import requests from django.core.cache import cache from treeherder.client import TreeherderResultSetCollection from treeherder.etl.common import (fetch_json, generate_revision_hash, get_not_found_onhold_push) from .mixins import ClientLoaderMixin logger = logging.getLogger(__name__) class HgPushlogTransformerMixin(object): def transform(self, pushlog, repository): # this contain the whole list of transformed pushes th_collections = {} # iterate over the pushes for push in pushlog.values(): result_set = dict() result_set['push_timestamp'] = push['date'] result_set['revisions'] = [] # Author of the push/resultset result_set['author'] = push['user'] result_set['active_status'] = push.get('active_status', 'active') # TODO: Remove this with Bug 1257602 is addressed rev_hash_components = [] # iterate over the revisions # we only want to ingest the last 200 revisions. for change in push['changesets'][-200:]: revision = dict() revision['revision'] = change['node'] revision['author'] = change['author'] revision['branch'] = change['branch'] revision['comment'] = change['desc'] revision['repository'] = repository rev_hash_components.append(change['node']) rev_hash_components.append(change['branch']) # append the revision to the push result_set['revisions'].append(revision) result_set['revision_hash'] = generate_revision_hash(rev_hash_components) result_set['revision'] = result_set["revisions"][-1]["revision"] if repository not in th_collections: th_collections[repository] = TreeherderResultSetCollection() th_resultset = th_collections[repository].get_resultset(result_set) th_collections[repository].add(th_resultset) return th_collections class HgPushlogProcess(HgPushlogTransformerMixin, ClientLoaderMixin): # For more info on Mercurial Pushes, see: # https://mozilla-version-control-tools.readthedocs.org/en/latest/hgmo/pushlog.html def extract(self, url): try: return fetch_json(url) except requests.exceptions.HTTPError as e: logger.warning("HTTPError %s fetching: %s", e.response.status_code, url) raise def run(self, source_url, repository, changeset=None): # get the last object seen from cache. this will # reduce the number of pushes processed every time last_push_id = cache.get("{0}:last_push_id".format(repository)) if not changeset and last_push_id: startid_url = "{}&startID={}".format(source_url, last_push_id) logger.info("Extracted last push for '%s', '%s', from cache, " "attempting to get changes only from that point at: %s" % (repository, last_push_id, startid_url)) # Use the cached ``last_push_id`` value (saved from the last time # this API was called) for this repo. Use that value as the # ``startID`` to get all new pushes from that point forward. extracted_content = self.extract(startid_url) if extracted_content['lastpushid'] < last_push_id: # Push IDs from Mercurial are incremental. If we cached a value # from one call to this API, and a subsequent call told us that # the ``lastpushid`` is LOWER than the one we have cached, then # the Mercurial IDs were reset. # In this circumstance, we can't rely on the cached id, so must # throw it out and get the latest 10 pushes. logger.warning(("Got a ``lastpushid`` value of {} lower than " "the cached value of {} due to Mercurial repo reset. " "Getting latest changes for '{}' instead").format( extracted_content['lastpushid'], last_push_id, repository ) ) cache.delete("{0}:last_push_id".format(repository)) extracted_content = self.extract(source_url) else: if changeset: logger.info("Getting all pushes for '%s' corresponding to " "changeset '%s'" % (repository, changeset)) extracted_content = self.extract(source_url + "&changeset=" + changeset) else: logger.warning("Unable to get last push from cache for '%s', " "getting all pushes" % repository) extracted_content = self.extract(source_url) # ``pushes`` could be empty if there are no new ones since we last # fetched pushes = extracted_content['pushes'] if not pushes: return None last_push_id = max(map(lambda x: int(x), pushes.keys())) last_push = pushes[str(last_push_id)] top_revision = last_push["changesets"][-1]["node"] transformed = self.transform(pushes, repository) self.load(transformed) if not changeset: # only cache the last push if we're not fetching a specific # changeset cache.set("{0}:last_push_id".format(repository), last_push_id) return top_revision class MissingHgPushlogProcess(HgPushlogTransformerMixin, ClientLoaderMixin): def extract(self, url, revision): logger.info("extracting missing resultsets: {0}".format(url)) try: return fetch_json(url) except requests.exceptions.HTTPError as e: status_code = e.response.status_code if status_code == 404: # we will sometimes get here because builds4hr/pending/running have a # job with a resultset that json-pushes doesn't know about. So far # I have only found this to be the case when it uses a revision from # the wrong repo. For example: mozilla-central, but l10n. The l10n # is a separate repo, but buildbot shows it as the same. So we # create this dummy resultset with ``active_status`` of ``onhold``. # # The effect of this is that we won't keep trying to re-fetch # the bogus pushlog, but the jobs are (correctly) not shown in the # UI, since they're bad data. logger.warn(("no pushlog in json-pushes. generating a dummy" " onhold placeholder: {0}").format(url)) # we want to make a "dummy" resultset that is "onhold", # because json-pushes doesn't know about it. # This is, in effect, what TBPL does. # These won't show in the UI, because they only fetch "active" # resultsets return get_not_found_onhold_push(url, revision) logger.warning("HTTPError %s fetching: %s", status_code, url) raise def run(self, source_url, repository, revision): try: extracted_content = self.extract(source_url, revision) if extracted_content: transformed = self.transform( extracted_content['pushes'], repository ) for project, coll in transformed.iteritems(): logger.info("loading missing resultsets for {0}: {1}".format( project, coll.to_json())) self.load(transformed) logger.info("done loading missing resultsets for {0}".format(repository)) else: assert extracted_content, ( "Got no content response for missing resultsets: {0}".format( source_url) ) except Exception: logger.exception("error loading missing resultsets: {0}".format( source_url )) raise
mpl-2.0
taskcluster/taskcluster-client-java
src/main/java/org/mozilla/taskcluster/client/awsprovisioner/RegionLaunchSpec.java
422
package org.mozilla.taskcluster.client.awsprovisioner; /** * LaunchSpecification entries unique to this Region * * See http://schemas.taskcluster.net/aws-provisioner/v1/region-launch-spec.json# */ public class RegionLaunchSpec { /** * Per-region AMI ImageId * * See http://schemas.taskcluster.net/aws-provisioner/v1/region-launch-spec.json#/properties/ImageId */ public String ImageId; }
mpl-2.0
mozilla-iot/gateway
src/controllers/push_controller.js
1206
/** * Push API Controller. * * Implements the Push API for notifications to use * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const PromiseRouter = require('express-promise-router'); const PushService = require('../push-service'); const PushController = PromiseRouter(); /** * Handle requests for the public key */ PushController.get('/vapid-public-key', async (request, response) => { const vapid = await PushService.getVAPIDKeys(); if (!vapid) { response.status(500).json({error: 'vapid not configured'}); return; } response.status(200).json({publicKey: vapid.publicKey}); }); PushController.post('/register', async (request, response) => { const subscription = request.body.subscription; try { await PushService.createPushSubscription(subscription); } catch (err) { console.error(`PushController: Failed to register ${subscription}`, err); response.status(500).json({error: 'register failed'}); return; } response.status(200).json({}); }); module.exports = PushController;
mpl-2.0
cal-r/sscctd
src/simulator/util/Response.java
2335
/** * */ package simulator.util; import java.util.List; /** * City University BSc Computing with Artificial Intelligence Project title: * Building a TD Simulator for Real-Time Classical Conditioning * * @supervisor Dr. Eduardo Alonso * @author Jonathan Gray **/ public enum Response { CHURCH_KIRKPATRICK("Church-Kirkpatrick") { /** * Simulate a response per minute according to the Church-Kirkpatrick * rule. REF * * @param threshold * Response threshold * @param thresholds * Pregenerated list of variable thresholds for a response * @param strength * V value of this cue. * @return */ @Override public double get(double threshold, List<Double> thresholds, double strength, double decay) { int responses = 0; try { for (double boundary : thresholds) { int response = strength > boundary * threshold ? 1 : 0; response = boundary < 4 / thresholds.size() ? 1 : response; responses += response; } } catch (ArrayIndexOutOfBoundsException e) {// swallow this, // response is zero. } catch (IndexOutOfBoundsException e) {// swallow this, response is // zero. } return responses; } }, LUDVIG("Ludvig") { /** * Simulate a response per minute according to the Ludvig rule. REF * * @param threshold * Response threshold * @param thresholds * Pregenerated list of variable thresholds for a response * @param strength * V value of this cue. * @return */ @Override public double get(double threshold, List<Double> thresholds, double strength, double decay) { double responses = 0; for (double t : thresholds) { try { responses = responses * decay + strength * (strength > threshold ? 1 : 0); } catch (ArrayIndexOutOfBoundsException e) {// swallow this, // response is zero. } catch (IndexOutOfBoundsException e) {// swallow this, response // is zero. } } return responses; } }; private String nameStr; private Response(String nameStr) { this.nameStr = nameStr; } public abstract double get(double threshold, List<Double> thresholds, double strength, double decay); @Override public String toString() { return nameStr; } }
mpl-2.0
servo/doc.servo.org
euclid/matrix/sidebar-items.js
44
initSidebarItems({"type":[["Matrix4",""]]});
mpl-2.0
hazzik/Rhino.Net
src/Rhino.Tests/Tests/FunctionTest.cs
1603
/* * This code is derived from rhino (http://github.com/mozilla/rhino) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using NUnit.Framework; using Rhino; using Rhino.Tests; using Sharpen; namespace Rhino.Tests { /// <summary>Unit tests for Function.</summary> /// <remarks>Unit tests for Function.</remarks> /// <author>Marc Guillemot</author> [NUnit.Framework.TestFixture] public class FunctionTest { /// <summary> /// Test for bug #600479 /// https://bugzilla.mozilla.org/show_bug.cgi?id=600479 /// Syntax of function built from Function's constructor string parameter was not correct /// when this string contained "//". /// </summary> /// <remarks> /// Test for bug #600479 /// https://bugzilla.mozilla.org/show_bug.cgi?id=600479 /// Syntax of function built from Function's constructor string parameter was not correct /// when this string contained "//". /// </remarks> [NUnit.Framework.Test] public virtual void TestFunctionWithSlashSlash() { AssertEvaluates(true, "new Function('return true//;').call()"); } private static void AssertEvaluates(object expected, string source) { Utils.RunWithAllOptimizationLevels(cx => { Scriptable scope = cx.InitStandardObjects(); object rep = cx.EvaluateString(scope, source, "test.js", 0, null); NUnit.Framework.Assert.AreEqual(expected, rep); return null; }); } } }
mpl-2.0
Farof/cleaner-web
lib/main.js
14614
"use strict"; const pageMod = require('sdk/page-mod'); const self = require('sdk/self'); const data = self.data; const cm = require('sdk/context-menu'); const simplePrefs = require('sdk/simple-prefs'); const prefs = simplePrefs.prefs; const str = require('sdk/l10n').get; const ss = require('sdk/simple-storage').storage; const Request = require('sdk/request').Request const { indexedDB } = require('sdk/indexed-db'); const tabs = require('sdk/tabs'); const { defer, all } = require('sdk/core/promise'); /* augmentation */ Object.defineProperties(Object, { forEach: { value: function (obj, fn) { Object.keys(obj).forEach(key => { fn(obj[key], key, obj); }); } }, map: { value: function (obj, fn) { let o = {}; Object.keys(obj).forEach(key => { o[key] = fn(obj[key], key, obj); }); return o; } } }); Object.defineProperties(Array.prototype, { contains: { value: function (item) { return this.indexOf(item) > -1; } } }); let cw = { init: () => { let deferred = defer(); cw.ui.init(); cw.page.init(); simplePrefs.on('isEnabled', () => prefs.isEnabled ? cw.mod.attachAll() : cw.mod.detachAll()); simplePrefs.on('showContextMenu', () => prefs.showContextMenu ? cw.contextMenu.attachAll() : cw.contextMenu.detachAll()); simplePrefs.on('configuration', cw.page.open); // loadRemote(); cw.db.init().then(cw.remote.updateAll, ev => { console.log('error initialiazing Cleaner Web database: ', ev.target.error.name); deferred.reject(); }).then(() => { if (prefs.isEnabled) { cw.mod.attachAll(); } deferred.resolve(); }); return deferred.promise; }, /* DATABASE */ db: { ref: null, onerror: ev => console.log('db error: ', ev.target.error.name), init: () => { let deferred = defer(); let request = indexedDB.open('userstyles', '15'); request.onupgradeneeded = ev => { console.log('upgrading db'); let db = ev.target.result; ev.target.transaction.onerror = cw.db.onerror; // mods if (db.objectStoreNames.contains('mods')) { db.deleteObjectStore('mods'); } let modsStore = db.createObjectStore('mods', { keyPath: 'uid' }); // modsStore.createIndex('source', 'source'); // modsStore.createIndex('pattern', 'pattern'); // remotes if (db.objectStoreNames.contains('remotes')) { db.deleteObjectStore('remotes'); } let remotes = ['https://raw.github.com/Farof/userstyles/master']; // let remotes = ['http://127.0.0.1:8090']; let remotesStore = db.createObjectStore('remotes', { keyPath: 'url' }); for (let remote of remotes) { remotesStore.add({ url: remote }); } }; request.onsuccess = ev => { cw.db.ref = ev.target.result; cw.db.ref.onerror = cw.db.onerror; deferred.resolve(cw.db.ref); }; request.onerror = deferred.reject; return deferred.promise; }, transaction: (storeName, mode = 'readonly') => cw.db.ref.transaction(storeName, mode), store: (storeName, mode = 'readonly') => cw.db.transaction(storeName, mode).objectStore(storeName), cursor: (storeName, mode = 'readonly') => cw.db.store(storeName, mode).openCursor(), // storeKeyPath: storeName => cw.db.store(storeName).keyPath, each: (storeName, fn, mode = 'readonly') => { let deferred = defer(); cw.db.cursor(storeName, mode).onsuccess = ev => { let cursor = ev.target.result; if (cursor) { fn(cursor); cursor.continue(); } else { deferred.resolve(); } }; return deferred.promise; }, getAllKeys: storeName => { let deferred = defer(); let keys = []; cw.db.each(storeName, cursor => { keys.push(cursor.key); }).then(() => deferred.resolve(keys)); return deferred.promise; }, get: (storeName, key, mode = 'readonly') => { let deferred = defer(); let req = cw.db.store(storeName, mode).get(key); req.onsuccess = ev => deferred.resolve([ev.target.result, ev.target.source]); req.onerror = deferred.reject; return deferred.promise; }, add: (storeName, obj) => { let deferred = defer(); let req = cw.db.store(storeName, 'readwrite').add(obj); req.onsuccess = () => deferred.resolve(obj); req.onerror = deferred.reject; return deferred.promise; }, put: (storeName, obj) => { let deferred = defer(); let req = cw.db.store(storeName, 'readwrite').put(obj); req.onsuccess = () => deferred.resolve(obj); req.onerror = deferred.reject; return deferred.promise; }, delete: (storeName, key) => { let deferred = defer(); let req = cw.db.store(storeName, 'readwrite').delete(key); req.onsuccess = deferred.resolve; req.onerror = deferred.reject; return deferred.promise; }, update: (storeName, key, updates) => { let deferred = defer(); cw.db.get(storeName, key, 'readwrite').then(([obj, store]) => { for (let key in updates) { obj[key] = updates[key]; } let req = store.put(obj); req.onsuccess = () => deferred.resolve(obj); req.onerror = deferred.reject; }, deferred.reject); return deferred.promise; } }, /* UI */ ui: { getWidgetTooltip: () => str(prefs.isEnabled ? 'CW_tooltip_on' : 'CW_tooltip_off'), getWidgetContent: () => str(prefs.isEnabled ? 'CW_content_on' : 'CW_content_off'), init: () => { let widget = require('sdk/widget').Widget({ id: 'cleanerWebWidget', label: str('CW_toggle'), tooltip: cw.ui.getWidgetTooltip(), content: cw.ui.getWidgetContent(), width: 40, onClick: () => prefs.isEnabled = !prefs.isEnabled }); simplePrefs.on('isEnabled', name => { widget.content = cw.ui.getWidgetContent(); widget.tooltip = cw.ui.getWidgetTooltip(); }); } }, /* REMOTE */ remote: { get: baseUrl => { let deferred = defer(); Request({ url: [baseUrl, 'package.json'].join('/'), onComplete: response => { let ret = response.json; if (ret) { ret.source = baseUrl; } deferred.resolve(ret); } }).get(); return deferred.promise; }, getAll: () => { let deferred = defer(); cw.db.getAllKeys('remotes').then(urls => { if (urls.length === 0) { deferred.resolve([]); } else { all(urls.map(cw.remote.get)).then(deferred.resolve, console.log); } }); return deferred.promise; }, loadAll: configurations => { let deferred = defer(); let mods = cw.mod.formatFromConfigurations(configurations); console.log('load mods: ', configurations); all(mods.map(cw.mod.register)) .then(() => cw.mod.cleanAllButKeys(mods.map(mod => mod.uid)), console.log) .then(deferred.resolve, console.log); return deferred.promise; }, updateAll: () => { return cw.remote.getAll().then(cw.remote.loadAll).then(null, console.log); } }, /* MOD */ mod: { refs: {}, attachAll: () => { cw.db.each('mods', cursor => { // attach only if not allready attached and css was obtained if (!cw.mod.refs[cursor.key] && cursor.value.css && cursor.value.enabled) { cw.mod.attach(cursor.value); } }).then(() => { if (prefs.showContextMenu) { cw.contextMenu.attachAll(); } }); }, detachAll: (toggling = true) => { cw.db.each('mods', cursor => { if (cw.mod.refs[cursor.key]) { cw.mod.detach(cursor.value, toggling); } }).then(() => { if (prefs.showContextMenu) { cw.contextMenu.detachAll(); } }); }, attach: mod => { let deferred = defer(); if (cw.mod.refs[mod.uid]) cw.mod.detach(mod); let options = { include: mod.pattern, attachTo: ['top', 'existing'], contentStyle: mod.css }; cw.mod.refs[mod.uid] = pageMod.PageMod(options); cw.db.update('mods', mod.uid, { enabled: true }).then(deferred.resolve, deferred.reject); console.log('mod attached: ', mod.uid); return deferred.promise; }, attachByUid: uid => cw.db.get('mods', uid).then(([obj]) => cw.mod.attach(obj)), detach: (mod, toggling = false) => cw.mod.detacByUid(mod.uid, toggling), detacByUid: (uid, toggling = false) => { let deferred = defer(); if (cw.mod.refs[uid]) { cw.mod.refs[uid].destroy(); delete cw.mod.refs[uid]; if (!toggling) { cw.db.update('mods', uid, { enabled: false }).then(deferred.resolve, deferred.reject); } console.log('mod detached: ', uid); } else { deferred.reject(new Error()); } return deferred.promise; }, toggle: mod => mod.enabled ? cw.mod.detach(mod) : cw.mod.attach(mod), toggleByUid: uid => cw.db.get('mods', uid).then(([obj]) => cw.mod.toggle(obj)), getCss: mod => { let deferred = defer(); Request({ url: [mod.source, mod.domain, mod.id + '.css'].join('/'), onComplete: response => deferred.resolve(response.text) }).get(); return deferred.promise; }, formatFromConfigurations: configurations => { return configurations.reduce((a, b) => a.concat(cw.mod.formatFromConfiguration(b)), []); }, formatFromConfiguration: conf => { let mods = []; let source = conf.source; for (let domain in conf.websites) { let website = conf.websites[domain]; for (let id in website.mods) { mods.push({ uid: [source, domain, id].join('::'), id: id, domain: domain, source: source, pattern: website.include, version: website.mods[id], enabled: true, css: null }); } } return mods; }, register: mod => { let deferred = defer(); cw.db.get('mods', mod.uid).then(([result]) => { if (result) { if (result.version !== mod.version) { console.log('updating mod: ', mod.uid); cw.mod.getCss(mod).then(css => { mod.css = css; // preserve enabled status; mod.enabled = result.enabled; cw.db.put('mods', mod).then(deferred.resolve, deferred.resolve); }); } else if (!result.css) { console.log('mod css missing: ', mod.uid); cw.mod.getCss(mod).then(css => { cw.db.update('mods', mod.uid, { css: css }).then(deferred.resolve, deferred.resolve); }); } else { console.log('mod up-to-date: ', mod.uid); deferred.resolve(); } } else { console.log('new mod: ', mod.uid) cw.mod.getCss(mod).then(css => { mod.css = css; cw.db.add('mods', mod).then(deferred.resolve, deferred.resolve); }); } }, err => { console.log('failed loading mod: ', mod.uid, err); deferred.resolve(); }); return deferred.promise; }, cleanAllButKeys: keys => { let deferred = defer(); cw.db.each('mods', cursor => { if (!keys.contains(cursor.key)) { cursor.source.delete(cursor.key); } }, 'readwrite').then(deferred.resolve); return deferred.promise; } }, /* CONTEXT MENU */ contextMenu: { refs: {}, label: mod => '(' + (mod.enabled ? 'x' : '-') + ') ' + str(mod.id), updateLabel: mod => { let menu = cw.contextMenu.refs[mod.domain]; if (menu) { let items = menu.items; for (let item of items) { if (item.data === mod.uid) { item.label = cw.contextMenu.label(mod); break; } } } }, updateLabelByUid: uid => { cw.db.get('mods', uid).then(([obj]) => cw.contextMenu.updateLabel(obj)); }, attachMod: mod => { let ctx = cm.URLContext(mod.pattern); let menu = cw.contextMenu.refs[mod.domain]; if (!menu) { menu = cw.contextMenu.refs[mod.domain] = cm.Menu({ context: ctx, label: str('CW'), contentScript: 'self.on("click", (node, data) => self.postMessage(data))', onMessage: uid => { cw.db.get('mods', uid).then(([mod]) => { cw.mod.toggle(mod).then(mod => { menu.items[menu.items.map(item => item.data).indexOf(uid)].label = cw.contextMenu.label(mod); }, console.log).then(null, console.log); }) } }); } if (!menu.items.some(item => item.data === mod.uid)) { menu.addItem(cm.Item({ label: cw.contextMenu.label(mod), data: mod.uid })); } }, detachModByUid: uid => { cw.db.get('mods', uid).then(([mod]) => cw.contextMenu.detachMod(mod)).then(null, console.log); }, detachMod: mod => { let menu = cw.contextMenu.refs[mod.domain]; if (menu) { let item = -1; for (let i = 0, ln = menu.items.length; i < ln; i++) { if (menu.items[i].data === mod.uid) { menu.removeItem(menu.items[i]); break; } } if (menu.items.length === 0) { menu.destroy(); delete cw.contextMenu.refs[mod.domain]; } } }, attachAll: () => { cw.db.each('mods', cursor => cw.contextMenu.attachMod(cursor.value)).then(null, console.log); }, detachAll: () => { cw.db.each('mods', cursor => cw.contextMenu.detachMod(cursor.value)).then(null, console.log); } }, /* ADDON PAGE */ page: { open: () => { tabs.open(data.url('addon-page/index.html')); }, init: () => { pageMod.PageMod({ include: data.url('addon-page/index.html'), contentScriptFile: data.url('addon-page/worker.js'), onAttach: worker => { console.log('addon-page worker attached'); } }); } } } console.log(self.name + ' (' + self.version + ') started.'); cw.init().then(() => { console.log('initialized'); });
mpl-2.0
Yukarumya/Yukarum-Redfoxes
js/src/proxy/DeadObjectProxy.cpp
4397
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "proxy/DeadObjectProxy.h" #include "jsapi.h" #include "jsfun.h" // XXXefaust Bug 1064662 #include "proxy/ScriptedProxyHandler.h" #include "vm/ProxyObject.h" using namespace js; using namespace js::gc; static void ReportDead(JSContext *cx) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); } bool DeadObjectProxy::getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, MutableHandle<PropertyDescriptor> desc) const { ReportDead(cx); return false; } bool DeadObjectProxy::defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, Handle<PropertyDescriptor> desc, ObjectOpResult& result) const { ReportDead(cx); return false; } bool DeadObjectProxy::ownPropertyKeys(JSContext* cx, HandleObject wrapper, AutoIdVector& props) const { ReportDead(cx); return false; } bool DeadObjectProxy::delete_(JSContext* cx, HandleObject wrapper, HandleId id, ObjectOpResult& result) const { ReportDead(cx); return false; } bool DeadObjectProxy::getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const { protop.set(nullptr); return true; } bool DeadObjectProxy::getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, MutableHandleObject protop) const { *isOrdinary = false; return true; } bool DeadObjectProxy::preventExtensions(JSContext* cx, HandleObject proxy, ObjectOpResult& result) const { ReportDead(cx); return false; } bool DeadObjectProxy::isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const { // This is kind of meaningless, but dead-object semantics aside, // [[Extensible]] always being true is consistent with other proxy types. *extensible = true; return true; } bool DeadObjectProxy::call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const { ReportDead(cx); return false; } bool DeadObjectProxy::construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const { ReportDead(cx); return false; } bool DeadObjectProxy::nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args) const { ReportDead(cx); return false; } bool DeadObjectProxy::hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp) const { ReportDead(cx); return false; } bool DeadObjectProxy::getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) const { ReportDead(cx); return false; } bool DeadObjectProxy::isArray(JSContext* cx, HandleObject obj, JS::IsArrayAnswer* answer) const { ReportDead(cx); return false; } const char* DeadObjectProxy::className(JSContext* cx, HandleObject wrapper) const { return "DeadObject"; } JSString* DeadObjectProxy::fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const { ReportDead(cx); return nullptr; } bool DeadObjectProxy::regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const { ReportDead(cx); return false; } bool DeadObjectProxy::isCallable(JSObject* obj) const { static const uint32_t slot = ScriptedProxyHandler::IS_CALLCONSTRUCT_EXTRA; uint32_t callConstruct = obj->as<ProxyObject>().extra(slot).toPrivateUint32(); return !!(callConstruct & ScriptedProxyHandler::IS_CALLABLE); } bool DeadObjectProxy::isConstructor(JSObject* obj) const { static const uint32_t slot = ScriptedProxyHandler::IS_CALLCONSTRUCT_EXTRA; uint32_t callConstruct = obj->as<ProxyObject>().extra(slot).toPrivateUint32(); return !!(callConstruct & ScriptedProxyHandler::IS_CONSTRUCTOR); } const char DeadObjectProxy::family = 0; const DeadObjectProxy DeadObjectProxy::singleton; bool js::IsDeadProxyObject(JSObject* obj) { return IsDerivedProxyObject(obj, &DeadObjectProxy::singleton); }
mpl-2.0
anom0ly/WoWAnalyzer
src/interface/report/ProgressBar.tsx
1239
import React from 'react'; interface Props { width: number; height: number; percentage: number; } const ProgressBar = ({ width, height, percentage }: Props) => { const backgroundColor = 'rgba(0,0,0,.6)'; const wipeFillColor = '#fb6d35'; const killFillColor = '#1d9c07'; // We use round stroke so there is additional width created by the border radius. // Remove the height(radius of the bar) from the width to make sure the bars presented at the correct width. const adjustedWidth = width - 2 * height; const fillColor = percentage === 100 ? killFillColor : wipeFillColor; return ( <svg className="ProgressBar icon" style={{ width, height }}> <path strokeWidth={height} stroke={backgroundColor} strokeLinejoin="round" strokeLinecap="round" fill="none" d={`M${height} ${height / 2} h 0 ${adjustedWidth}`} /> {Boolean(percentage) && ( <path strokeWidth={height} stroke={fillColor} strokeLinejoin="round" strokeLinecap="round" fill="none" d={`M${height} ${height / 2} h 0 ${(adjustedWidth * percentage) / 100}`} /> )} </svg> ); }; export default ProgressBar;
agpl-3.0
SentinelDataHub/DataHubSystem
client/webclient/src/main/frontend/app/components/management-users/directive.js
9637
/* * Data HUb Service (DHuS) - For Space data distribution. * Copyright (C) 2013,2014,2015,2016 European Space Agency (ESA) * Copyright (C) 2013,2014,2015,2016 GAEL Systems * Copyright (C) 2013,2014,2015,2016 Serco Spa * * This file is part of DHuS software sources. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; angular.module('DHuS-webclient') .directive('managementUsers', function(UIUtils, $document,$window, UserModel, AdminUserService ) { var PAGE_LABEL_ID = '#page-label-id', PAGE_COUNT_ID = '#page-count-id', PAGE_NUM_ID = '#page-num-id', FAB_MNGUSER_CLASS = '.fab-mnguser', MNGUSER_BUTTON_CLASS = '.mnguser-button'; var showHideLabel = function(){ UIUtils.responsiveLayout( function xs(){ $(PAGE_LABEL_ID).css('display','none'); $(PAGE_NUM_ID).css('display','none'); $(PAGE_COUNT_ID).css('display','none'); $(FAB_MNGUSER_CLASS).css('display','none'); $(MNGUSER_BUTTON_CLASS).css('display','inline'); //console.warn('xs'); }, function sm(){ $(PAGE_LABEL_ID).css('display','none'); $(PAGE_NUM_ID).css('display','none'); $(PAGE_COUNT_ID).css('display','none'); $(MNGUSER_BUTTON_CLASS).css('display','inline'); $(FAB_MNGUSER_CLASS).css('display','none'); //console.warn('sm'); }, function md(){ $(PAGE_LABEL_ID).css('display','inline-block'); $(PAGE_NUM_ID).css('display','inline-block'); $(PAGE_COUNT_ID).css('display','inline-block'); $(MNGUSER_BUTTON_CLASS).css('display','inline'); $(FAB_MNGUSER_CLASS).css('display','none'); //console.warn('md'); }, function lg(){ $(PAGE_LABEL_ID).css('display','inline-block'); $(PAGE_NUM_ID).css('display','inline-block'); $(PAGE_COUNT_ID).css('display','inline-block'); $(MNGUSER_BUTTON_CLASS).css('display','inline'); $(FAB_MNGUSER_CLASS).css('display','none'); } ); }; return { restrict: 'AE', replace: true, templateUrl: 'components/management-users/view.html', scope: { text: "=" }, // SearchModelService Protocol implemenation createdUserModel: function(){}, compile: function(tElem, tAttrs){ var self = this; return { pre: function(scope, iElem, iAttrs){ UserModel.sub(self); scope.usersCount = 0; scope.currentPage = 1; setTimeout(function(){angular.element($document).ready(showHideLabel);},0); }, post: function(scope, iElem, iAttrs){ self.usersPerPagePristine = true; self.currentPagePristine = true; scope.currentPage = 1; scope.currentPageCache = 1; scope.model = {}; scope.model.searchfilter = ''; AdminUserService.setFilter(scope.model.searchfilter); angular.element($document).ready(showHideLabel); angular.element($window).bind('resize',showHideLabel); function init() { //showHideLabel(); scope.initUsers(); } var goToPage = function(pageNumber,free){ console.log(pageNumber) ; if((pageNumber <= scope.pageCount && pageNumber > 0) || free){ scope.currentPage = pageNumber; scope.currentPageCache = pageNumber; AdminUserService.gotoPage(pageNumber).then(function(){ scope.refreshCounters(); }); } }; scope.setFilter = function() { console.log("scope.filter",scope.model.searchfilter); AdminUserService.setFilter(scope.model.searchfilter); }; scope.initUsers = function() { AdminUserService.getUsersList(); scope.refreshCounters(); }; scope.refreshCounters = function(){ scope.usersCount = UserModel.model.count; scope.pageCount = Math.floor(UserModel.model.count / scope.usersPerPage) + ((UserModel.model.count % scope.usersPerPage)?1:0); }; self.createdUserModel = function(){ scope.model.users = UserModel.model.list; scope.usersCount = UserModel.model.count; scope.refreshCounters(); //console.log("AdminUserService.offset",AdminUserService.offset); scope.visualizedUsersFrom = (UserModel.model.count)? parseInt(AdminUserService.offset) + 1:0; scope.visualizedUsersTo = (((UserModel.model.count)?(scope.currentPage * scope.usersPerPage):0)> scope.usersCount)?scope.usersCount:((UserModel.model.count)?(scope.currentPage * scope.usersPerPage):0); }; self.updatedUserModel = function(){ }; scope.showCreateUser = function() { AdminUserDetailsManager.getUserDetails(-1, UserModel.model.list, true); }; scope.usersPerPage = '25'; scope.$watch('usersPerPage', function(usersPerPage){ if(self.usersPerPagePristine){ self.usersPerPagePristine = false; return; } AdminUserService.setLimit(usersPerPage); goToPage(1, true); }); /*scope.$watch('searchfilter', function(searchfilter){ scope.searchfilter=searchfilter; AdminUserService.setLimit(searchfilter); console.log("searchfilter",searchfilter); }); */ var managePageSelector = function(){ var newValue = parseInt(scope.currentPage); if(isNaN(newValue)) { scope.$apply(function () { scope.currentPage = scope.currentPageCache; }); return; } if(newValue <= 0 ){ scope.$apply(function () { scope.currentPage = scope.currentPageCache; }); return; } if(newValue > scope.pageCount){ scope.$apply(function () { scope.currentPage = scope.currentPageCache; }); return; } goToPage(scope.currentPage); } $('#mnguser-page-selector').bind("enterKey",function(e){ managePageSelector(); }); $('#mnguser-page-selector').focusout(function(e){ managePageSelector(); }); $('#mnguser-page-selector').keyup(function(e){ if(e.keyCode == 13) { $(this).trigger("enterKey"); } }); $('#user-filter').bind("filterEnter",function(e){ if(self.usersPerPagePristine){ self.usersPerPagePristine = false; return; } AdminUserService.setLimit(scope.usersPerPage); goToPage(1, true); }); $('#user-filter').keyup(function(e){ if(e.keyCode == 13) { $(this).trigger("filterEnter"); } }); scope.currentPage = 1; scope.gotoFirstPage = function(){ goToPage(1); }; scope.gotoPreviousPage = function(){ goToPage(scope.currentPage - 1); }; scope.gotoNextPage = function() { goToPage(scope.currentPage + 1); }; scope.gotoLastPage = function(){ goToPage(scope.pageCount); }; scope.selectPageDidClicked = function(xx){ }; init(); } } } }; });
agpl-3.0
LYY/code2docx
vendor/baliance.com/gooxml/schema/soo/sml/CT_SharedUser.go
3661
// Copyright 2017 Baliance. All rights reserved. // // DO NOT EDIT: generated by gooxml ECMA-376 generator // // Use of this source code is governed by the terms of the Affero GNU General // Public License version 3.0 as published by the Free Software Foundation and // appearing in the file LICENSE included in the packaging of this file. A // commercial license can be purchased by contacting sales@baliance.com. package sml import ( "encoding/xml" "fmt" "log" "strconv" "time" "baliance.com/gooxml/schema/soo/ofc/sharedTypes" ) type CT_SharedUser struct { // User Revisions GUID GuidAttr string // User Name NameAttr string // User Id IdAttr int32 // Date Time DateTimeAttr time.Time ExtLst *CT_ExtensionList } func NewCT_SharedUser() *CT_SharedUser { ret := &CT_SharedUser{} ret.GuidAttr = "{00000000-0000-0000-0000-000000000000}" return ret } func (m *CT_SharedUser) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "guid"}, Value: fmt.Sprintf("%v", m.GuidAttr)}) start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "name"}, Value: fmt.Sprintf("%v", m.NameAttr)}) start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "id"}, Value: fmt.Sprintf("%v", m.IdAttr)}) start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "dateTime"}, Value: fmt.Sprintf("%v", m.DateTimeAttr)}) e.EncodeToken(start) if m.ExtLst != nil { seextLst := xml.StartElement{Name: xml.Name{Local: "ma:extLst"}} e.EncodeElement(m.ExtLst, seextLst) } e.EncodeToken(xml.EndElement{Name: start.Name}) return nil } func (m *CT_SharedUser) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { // initialize to default m.GuidAttr = "{00000000-0000-0000-0000-000000000000}" for _, attr := range start.Attr { if attr.Name.Local == "guid" { parsed, err := attr.Value, error(nil) if err != nil { return err } m.GuidAttr = parsed } if attr.Name.Local == "name" { parsed, err := attr.Value, error(nil) if err != nil { return err } m.NameAttr = parsed } if attr.Name.Local == "id" { parsed, err := strconv.ParseInt(attr.Value, 10, 32) if err != nil { return err } m.IdAttr = int32(parsed) } if attr.Name.Local == "dateTime" { parsed, err := ParseStdlibTime(attr.Value) if err != nil { return err } m.DateTimeAttr = parsed } } lCT_SharedUser: for { tok, err := d.Token() if err != nil { return err } switch el := tok.(type) { case xml.StartElement: switch el.Name { case xml.Name{Space: "http://schemas.openxmlformats.org/spreadsheetml/2006/main", Local: "extLst"}: m.ExtLst = NewCT_ExtensionList() if err := d.DecodeElement(m.ExtLst, &el); err != nil { return err } default: log.Printf("skipping unsupported element on CT_SharedUser %v", el.Name) if err := d.Skip(); err != nil { return err } } case xml.EndElement: break lCT_SharedUser case xml.CharData: } } return nil } // Validate validates the CT_SharedUser and its children func (m *CT_SharedUser) Validate() error { return m.ValidateWithPath("CT_SharedUser") } // ValidateWithPath validates the CT_SharedUser and its children, prefixing error messages with path func (m *CT_SharedUser) ValidateWithPath(path string) error { if !sharedTypes.ST_GuidPatternRe.MatchString(m.GuidAttr) { return fmt.Errorf(`%s/m.GuidAttr must match '%s' (have %v)`, path, sharedTypes.ST_GuidPatternRe, m.GuidAttr) } if m.ExtLst != nil { if err := m.ExtLst.ValidateWithPath(path + "/ExtLst"); err != nil { return err } } return nil }
agpl-3.0
pgorod/SuiteCRM
include/generic/SugarWidgets/SugarWidgetSubPanelEditSecurityGroupUserButton.php
3196
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /** * SugarWidgetSubPanelEditRoleButton * * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". */ require_once('include/generic/SugarWidgets/SugarWidgetField.php'); class SugarWidgetSubPanelEditSecurityGroupUserButton extends SugarWidgetField { public function displayHeaderCell($layout_def) { return '&nbsp;'; } public function & displayDetail($layout_def) { return $this->displayList($layout_def); } public function displayList($layout_def) { global $app_strings; global $image_path; $href = 'index.php?module=SecurityGroups' . '&action=' . 'SecurityGroupUserRelationshipEdit' . '&record=' . $layout_def['fields']['SECURITYGROUP_NONINHERIT_ID'] . '&return_module=' . $_REQUEST['module'] . '&return_action=' . 'DetailView' . '&return_id=' . $_REQUEST['record']; $edit_icon_html = SugarThemeRegistry::current()->getImage('edit_inline', 'align="absmiddle" border="0"', null, null, '.gif', $app_strings['LNK_EDIT']); //based on listview since that lets you select records if ($layout_def['ListView']) { return '<a href="' . $href . '"' . 'class="listViewTdToolsS1">' . $edit_icon_html . '&nbsp;' . $app_strings['LNK_EDIT'] .'</a>&nbsp;'; } return ''; } }
agpl-3.0
ekacnet/z-push
tools/migrate-2.0.x-2.1.0.php
7051
#!/usr/bin/env php <?php /*********************************************** * File : migrate-2.0.x-2.1.0.php * Project : Z-Push - tools * Descr : Convertes states from * Z-Push 2.0.x to Z-Push 2.1.0 * * Created : 30.11.2012 * * Copyright 2007 - 2013 Zarafa Deutschland GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Consult LICENSE file for details ************************************************/ // Please adjust to match your z-push installation directory, usually /usr/share/z-push define('ZPUSH_BASE_PATH', "../src"); /************************************************ * MAIN */ try { if (php_sapi_name() != "cli") die("This script can only be called from the CLI."); if (!defined('ZPUSH_BASE_PATH') || !file_exists(ZPUSH_BASE_PATH . "/config.php")) die("ZPUSH_BASE_PATH not set correctly or no config.php file found\n"); define('BASE_PATH_CLI', ZPUSH_BASE_PATH ."/"); set_include_path(get_include_path() . PATH_SEPARATOR . ZPUSH_BASE_PATH); include('lib/core/zpushdefs.php'); include('lib/core/zpush.php'); include('lib/core/zlog.php'); include('lib/core/statemanager.php'); include('lib/core/stateobject.php'); include('lib/core/asdevice.php'); include('lib/core/interprocessdata.php'); include('lib/exceptions/exceptions.php'); include('lib/utils/utils.php'); include('lib/request/request.php'); include('lib/request/requestprocessor.php'); include('lib/interface/ibackend.php'); include('lib/interface/ichanges.php'); include('lib/interface/iexportchanges.php'); include('lib/interface/iimportchanges.php'); include('lib/interface/isearchprovider.php'); include('lib/interface/istatemachine.php'); include('config.php'); ZPush::CheckConfig(); $migrate = new StateMigrator20xto210(); if (!$migrate->MigrationNecessary()) echo "Migration script was run before and eventually no migration is necessary. Rerunning checks\n"; $migrate->DoMigration(); } catch (ZPushException $zpe) { die(get_class($zpe) . ": ". $zpe->getMessage() . "\n"); } echo "terminated\n"; class StateMigrator20xto210 { const FROMVERSION = "1"; // IStateMachine::STATEVERSION_01 const TOVERSION = "2"; // IStateMachine::STATEVERSION_02 private $sm; /** * Constructor */ public function __construct() { $this->sm = false; } /** * Checks if the migration is necessary * * @access public * @throws FatalMisconfigurationException * @throws FatalNotImplementedException * @return boolean */ public function MigrationNecessary() { try { $this->sm = ZPush::GetStateMachine(); } catch (HTTPReturnCodeException $e) { echo "Check states: states versions do not match and need to be migrated\n\n"; // we just try to get the statemachine again // the exception is only thrown the first time $this->sm = ZPush::GetStateMachine(); } if (!$this->sm) throw new FatalMisconfigurationException("Could not get StateMachine from ZPush::GetStateMachine()"); if (!($this->sm instanceof FileStateMachine)) { throw new FatalNotImplementedException("This conversion script is only able to convert states of the FileStateMachine"); } if ($this->sm->GetStateVersion() == ZPush::GetLatestStateVersion()) return false; if ($this->sm->GetStateVersion() !== self::FROMVERSION || ZPush::GetLatestStateVersion() !== self::TOVERSION) throw new FatalNotImplementedException(sprintf("This script only converts from state version %d to %d. Currently the system is on %d and should go to %d. Please contact support.", self::FROMVERSION, self::TOVERSION, $this->sm->GetStateVersion(), ZPush::GetLatestStateVersion())); // do migration return true; } /** * Execute the migration * * @access public * @return true */ public function DoMigration() { // go through all files $files = glob(STATE_DIR. "/*/*/*", GLOB_NOSORT); $filetotal = count($files); $filecount = 0; $rencount = 0; $igncount = 0; foreach ($files as $file) { $filecount++; $newfile = strtolower($file); echo "\033[1G"; if ($file !== $newfile) { $rencount++; rename ($file, $newfile); } else $igncount++; printf("Migrating file %d/%d\t%s", $filecount, $filetotal, $file); } echo "\033[1G". sprintf("Migrated total of %d files, %d renamed and %d ignored (as already correct)%s\n\n", $filetotal, $rencount, $igncount, str_repeat(" ", 50)); // get all states of synchronized devices $alldevices = $this->sm->GetAllDevices(false); foreach ($alldevices as $devid) { $lowerDevid = strtolower($devid); echo "Processing device: ". $devid . "\t"; // update device data $devState = ZPush::GetStateMachine()->GetState($lowerDevid, IStateMachine::DEVICEDATA); $newdata = array(); foreach ($devState->devices as $user => $dev) { if (!isset($dev->deviceidOrg)) $dev->deviceidOrg = $dev->deviceid; $dev->deviceid = strtolower($dev->deviceid); $dev->useragenthistory = array_unique($dev->useragenthistory); $newdata[$user] = $dev; } $devState->devices = $newdata; $this->sm->SetState($devState, $lowerDevid, IStateMachine::DEVICEDATA); // go through the users again: device was updated sucessfully, now we change the global user <-> device link foreach ($devState->devices as $user => $dev) { printf("\n\tUn-linking %s with old device id %s", $user, $dev->deviceidOrg); $this->sm->UnLinkUserDevice($user, $dev->deviceidOrg); printf("\n\tRe-linking %s with new device id %s", $user, $dev->deviceid); $this->sm->LinkUserDevice($user, $dev->deviceid); } echo "\n\tcompleted\n"; } echo "\nSetting new StateVersion\n"; $this->sm->SetStateVersion(self::TOVERSION); echo "Migration completed!\n\n"; return true; } }
agpl-3.0
Hilfe/decidim
decidim-comments/app/frontend/comments/add_comment_form.component.tsx
13198
/* eslint-disable no-return-assign, react/no-unused-prop-types, max-lines */ import * as classnames from "classnames"; import * as React from "react"; import { graphql } from "react-apollo"; import * as uuid from "uuid"; import Icon from "../application/icon.component"; const { I18n, Translate } = require("react-i18nify"); import { AddCommentFormCommentableFragment, AddCommentFormSessionFragment, addCommentMutation, CommentFragment, GetCommentsQuery, } from "../support/schema"; interface AddCommentFormProps { session: AddCommentFormSessionFragment & { user: any; } | null; commentable: AddCommentFormCommentableFragment; rootCommentable: AddCommentFormCommentableFragment; showTitle?: boolean; submitButtonClassName?: string; autoFocus?: boolean; arguable?: boolean; addComment?: (data: { body: string, alignment: number, userGroupId?: string }) => void; onCommentAdded?: () => void; orderBy: string; } interface AddCommentFormState { disabled: boolean; error: boolean; alignment: number; remainingCharacterCount: number; } export const MAX_LENGTH = 1000; /** * Renders a form to create new comments. * @class * @augments Component */ export class AddCommentForm extends React.Component<AddCommentFormProps, AddCommentFormState> { public static defaultProps = { showTitle: true, submitButtonClassName: "button button--sc", arguable: false, autoFocus: false, }; public bodyTextArea: HTMLTextAreaElement; public userGroupIdSelect: HTMLSelectElement; constructor(props: AddCommentFormProps) { super(props); this.state = { disabled: true, error: false, alignment: 0, remainingCharacterCount: MAX_LENGTH, }; } public render() { return ( <div className="add-comment"> {this._renderHeading()} {this._renderAccountMessage()} {this._renderOpinionButtons()} {this._renderForm()} </div> ); } /** * Render the form heading based on showTitle prop * @private * @returns {Void|DOMElement} - The heading or an empty element */ private _renderHeading() { const { showTitle } = this.props; if (showTitle) { return ( <h5 className="section-heading"> {I18n.t("components.add_comment_form.title")} </h5> ); } return null; } /** * Render a message telling the user to sign in or sign up to leave a comment. * @private * @returns {Void|DOMElement} - The message or an empty element. */ private _renderAccountMessage() { const { session } = this.props; if (!session) { return ( <p> <Translate value="components.add_comment_form.account_message" sign_in_url="/users/sign_in" sign_up_url="/users/sign_up" dangerousHTML={true} /> </p> ); } return null; } /** * Render the add comment form if session is present. * @private * @returns {Void|DOMElement} - The add comment form on an empty element. */ private _renderForm() { const { session, submitButtonClassName, commentable: { id, type } } = this.props; const { disabled, remainingCharacterCount } = this.state; if (session) { return ( <form onSubmit={this.addComment}> {this._renderCommentAs()} <div className="field"> <label className="show-for-sr" htmlFor={`add-comment-${type}-${id}`}>{I18n.t("components.add_comment_form.form.body.label")}</label> {this._renderTextArea()} {this._renderTextAreaError()} <button type="submit" className={submitButtonClassName} disabled={disabled} > {I18n.t("components.add_comment_form.form.submit")} </button> <span className="remaining-character-count"> {I18n.t("components.add_comment_form.remaining_characters", { count: remainingCharacterCount })} </span> </div> </form> ); } return null; } /** * Render the form heading based on showTitle prop * @private * @returns {Void|DOMElement} - The heading or an empty element */ private _renderTextArea() { const { commentable: { id, type }, autoFocus } = this.props; const { error } = this.state; const className = classnames({ "is-invalid-input": error }); const textAreaProps: any = { ref: (textarea: HTMLTextAreaElement) => {this.bodyTextArea = textarea; }, id: `add-comment-${type}-${id}`, className, rows: "4", maxLength: MAX_LENGTH, required: "required", pattern: `^(.){0,${MAX_LENGTH}}$`, placeholder: I18n.t("components.add_comment_form.form.body.placeholder"), onChange: (evt: React.ChangeEvent<HTMLTextAreaElement>) => this._checkCommentBody(evt.target.value), }; if (autoFocus) { textAreaProps.autoFocus = "autoFocus"; } return ( <textarea {...textAreaProps} /> ); } /** * Render the text area form error if state has an error * @private * @returns {Void|DOMElement} - The error or an empty element */ private _renderTextAreaError() { const { error } = this.state; if (error) { return ( <span className="form-error is-visible"> {I18n.t("components.add_comment_form.form.form_error", { length: MAX_LENGTH })} </span> ); } return null; } private setAlignment = (alignment: number) => { return () => { this.setState({ alignment }); }; } /** * Render opinion buttons or not based on the arguable prop * @private * @returns {Void|DOMElement} - Returns nothing or a wrapper with buttons */ private _renderOpinionButtons() { const { session, arguable } = this.props; const { alignment } = this.state; const buttonClassName = classnames("button", "tiny", "button--muted"); const okButtonClassName = classnames(buttonClassName, "opinion-toggle--ok", { "is-active": alignment === 1, }); const koButtonClassName = classnames(buttonClassName, "opinion-toggle--ko", { "is-active": alignment === -1, }); const neutralButtonClassName = classnames(buttonClassName, "opinion-toggle--meh", { "is-active": alignment === 0, }); if (session && arguable) { return ( <div className="opinion-toggle button-group"> <button className={okButtonClassName} onClick={this.setAlignment(1)} > <Icon iconExtraClassName="" name="icon-thumb-up" /> </button> <button className={neutralButtonClassName} onClick={this.setAlignment(0)} > {I18n.t("components.add_comment_form.opinion.neutral")} </button> <button className={koButtonClassName} onClick={this.setAlignment(-1)} > <Icon iconExtraClassName="" name="icon-thumb-down" /> </button> </div> ); } return null; } private setUserGroupIdSelect = (select: HTMLSelectElement) => {this.userGroupIdSelect = select; }; /** * Render a select with an option for each user's verified group * @private * @returns {Void|DOMElement} - Returns nothing or a form field. */ private _renderCommentAs() { const { session, commentable: { id, type } } = this.props; if (session) { const { user, verifiedUserGroups } = session; if (verifiedUserGroups.length > 0) { return ( <div className="field"> <label htmlFor={`add-comment-${type}-${id}-user-group-id`}> {I18n.t("components.add_comment_form.form.user_group_id.label")} </label> <select ref={this.setUserGroupIdSelect} id={`add-comment-${type}-${id}-user-group-id`} > <option value="">{user.name}</option> { verifiedUserGroups.map((userGroup) => ( <option key={userGroup.id} value={userGroup.id}>{userGroup.name}</option> )) } </select> </div> ); } } return null; } /** * Check comment's body and disable form if it's empty * @private * @param {string} body - The comment's body * @returns {Void} - Returns nothing */ private _checkCommentBody(body: string) { this.setState({ disabled: body === "", error: body === "" || body.length > MAX_LENGTH, remainingCharacterCount: MAX_LENGTH - body.length, }); } /** * Handle form's submission and calls `addComment` prop with the value of the * form's textarea. It prevents the default form submission event. * @private * @param {DOMEvent} evt - The form's submission event * @returns {Void} - Returns nothing */ private addComment = (evt: React.FormEvent<HTMLFormElement>) => { const { alignment } = this.state; const { addComment, onCommentAdded } = this.props; const addCommentParams: { body: string, alignment: number, userGroupId?: string } = { body: this.bodyTextArea.value, alignment }; evt.preventDefault(); if (this.userGroupIdSelect && this.userGroupIdSelect.value !== "") { addCommentParams.userGroupId = this.userGroupIdSelect.value; } if (addComment) { addComment(addCommentParams); } this.bodyTextArea.value = ""; this.setState({ alignment: 0 }); if (onCommentAdded) { onCommentAdded(); } } } const addCommentMutation = require("../mutations/add_comment.mutation.graphql"); const getCommentsQuery = require("../queries/comments.query.graphql"); const AddCommentFormWithMutation = graphql<addCommentMutation, AddCommentFormProps>(addCommentMutation, { props: ({ ownProps, mutate }) => ({ addComment: ({ body, alignment, userGroupId }: { body: string, alignment: number, userGroupId: string }) => { if (mutate) { mutate({ variables: { commentableId: ownProps.commentable.id, commentableType: ownProps.commentable.type, body, alignment, userGroupId, }, optimisticResponse: { commentable: { __typename: "CommentableMutation", addComment: { __typename: "Comment", id: uuid(), sgid: uuid(), type: "Decidim::Comments::Comment", createdAt: new Date().toISOString(), body, alignment, author: { __typename: "User", name: ownProps.session && ownProps.session.user.name, avatarUrl: ownProps.session && ownProps.session.user.avatarUrl, deleted: false, isVerified: true, isUser: true, }, comments: [], hasComments: false, acceptsNewComments: false, upVotes: 0, upVoted: false, downVotes: 0, downVoted: false, alreadyReported: false, }, }, }, update: (store, { data }: { data: addCommentMutation }) => { const variables = { commentableId: ownProps.rootCommentable.id, commentableType: ownProps.rootCommentable.type, orderBy: ownProps.orderBy, }; const prev = store.readQuery<GetCommentsQuery>({ query: getCommentsQuery, variables, }); const { id, type } = ownProps.commentable; const newComment = data.commentable && data.commentable.addComment; let comments = []; const commentReducer = (comment: CommentFragment): CommentFragment => { const replies = comment.comments || []; if (newComment && comment.id === id) { return { ...comment, hasComments: true, comments: [ ...replies, newComment, ], }; } return { ...comment, comments: replies.map(commentReducer), }; }; if (type === "Decidim::Comments::Comment") { comments = prev.commentable.comments.map(commentReducer); } else { comments = [ ...prev.commentable.comments, newComment, ]; } store.writeQuery({ query: getCommentsQuery, data: { ...prev, commentable: { ...prev.commentable, comments, }, }, variables, }); }, }); } }, }), })(AddCommentForm); export default AddCommentFormWithMutation;
agpl-3.0
dhlab-basel/Salsah
src/app/view/dashboard/system/system-projects/system-projects.component.ts
2059
/* Copyright © 2016 Lukas Rosenthaler, André Kilchenmann, Andreas Aeschlimann, * Sofia Georgakopoulou, Ivan Subotic, Benjamin Geer, Tobias Schweizer, Sepideh Alassi * This file is part of SALSAH. * SALSAH is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * SALSAH 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. * You should have received a copy of the GNU Affero General Public * License along with SALSAH. If not, see <http://www.gnu.org/licenses/>. * */ import {Component, OnInit} from '@angular/core'; import {AddData, ListData} from '../../../modules/framework/framework-for-listings/framework-for-listings.component'; @Component({ selector: 'salsah-system-projects', templateUrl: './system-projects.component.html', styleUrls: ['./system-projects.component.scss'] }) export class SystemProjectsComponent implements OnInit { // here we can reuse the framework-for-listings component: // shows a list of projects and the possibility to create new projects // ------------------------------------------------------------------------ // DATA for FrameworkForListingsComponent // ------------------------------------------------------------------------ list: ListData = { title: 'List of projects in Knora', description: '', content: 'project', showAs: 'table', restrictedBy: undefined }; // add new projects add: AddData = { title: 'Create new project', description: '', type: 'project' }; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ constructor() { } ngOnInit() { } }
agpl-3.0
hacklabr/timtec
accounts/migrations/0004_auto_20180203_0020.py
631
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0003_timtecuser_cpf'), ] operations = [ migrations.AddField( model_name='timtecuser', name='institution', field=models.CharField(max_length=255, null=True, blank=True), ), migrations.AlterField( model_name='timtecuser', name='occupation', field=models.CharField(max_length=127, verbose_name='Occupation', blank=True), ), ]
agpl-3.0
t123/ReadingTool
app/controllers/AccountController.php
3673
<?php use RT\Core\FlashMessage; use RT\Services\IUserService; use RT\Core\Bucket; class AccountController extends BaseController { private $userService; public function __construct(IUserService $userService) { $this->userService = $userService; View::share('currentController', 'Account'); } public function index() { return View::make('account.index') ->with('user', Auth::user()) ->with('css', $this->userService->getCss()) ; } public function postIndex() { $rules = array( 'displayName' => 'max:20|alpha_dash', 'email' => 'max:50' ); $validator = Validator::make(Input::only('displayName', 'email'), $rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $user = User::find(Auth::user()->id); $user->displayName = Input::get('displayName'); $user->email = Input::get('email'); $user->save(); Session::flash(FlashMessage::MSG, new FlashMessage('Your account has been updated.', FlashMessage::SUCCESS)); return Redirect::action('AccountController@index'); } public function postCss() { $css = trim(Input::get('css')); $this->userService->saveCss($css); Session::flash(FlashMessage::MSG, new FlashMessage('Your CSS has been updated.', FlashMessage::SUCCESS)); return Redirect::action('AccountController@index'); } public function changePassword() { return View::make('account.changepassword'); } public function postChangePassword() { $rules = array( 'currentPassword' => 'required', 'newPassword' => 'required' ); $validator = Validator::make(Input::only('currentPassword', 'newPassword'), $rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator); } $user = User::find(Auth::user()->id); if (Hash::check(Input::get('currentPassword'), $user->password)) { $user->password = Hash::make(Input::get('newPassword')); $user->save(); Session::flash(FlashMessage::MSG, new FlashMessage('Your password was updated', FlashMessage::SUCCESS)); return Redirect::action('AccountController@changePassword'); } Session::flash(FlashMessage::MSG, new FlashMessage('Your current password was not correct', FlashMessage::DANGER)); return Redirect::back()->withErrors($validator); } public function deleteAccount() { return View::make('account.deleteaccount'); } public function postDeleteAccount() { $rules = array('currentPassword' => 'required'); $validator = Validator::make(Input::only('currentPassword'), $rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator); } $user = User::find(Auth::user()->id); if (Hash::check(Input::get('currentPassword'), $user->password)) { $this->userService->deleteUser(); Auth::logout(); Session::flash(FlashMessage::MSG, new FlashMessage('Your account has been deleted.', FlashMessage::SUCCESS)); return Redirect::action('HomeController@index'); } Session::flash(FlashMessage::MSG, new FlashMessage('Your current password was not correct', FlashMessage::DANGER)); return Redirect::back()->withErrors($validator); } public function thankyou() { return View::make('account.thankyou'); } }
agpl-3.0
HadoDokis/loomio
app/models/ability.rb
8192
class Ability include CanCan::Ability def user_is_member_of?(group_id) @member_group_ids.include?(group_id) end def user_is_admin_of?(group_id) @admin_group_ids.include?(group_id) end def user_is_author_of?(object) object.author_id == @user.id end def initialize(user) user ||= User.new @user = user @admin_group_ids = user.adminable_group_ids @member_group_ids = user.group_ids cannot :sign_up, User can [:approve, :decline], NetworkMembershipRequest do |request| request.pending? and request.network.coordinators.include? user end can :create, NetworkMembershipRequest do |request| request.group.coordinators.include?(request.requestor) and request.group.is_parent? and !request.network.groups.include?(request.group) end can :manage_membership_requests, Network do |network| network.coordinators.include? user end can :show, Group do |group| if group.is_archived? false else group.is_visible_to_public? or user_is_member_of?(group.id) or (group.is_visible_to_parent_members? and user_is_member_of?(group.parent_id)) end end can :see_private_content, Group do |group| if group.is_archived? false else user_is_member_of?(group.id) or (group.is_visible_to_parent_members? and user_is_member_of?(group.parent_id)) end end can [:view_payment_details, :choose_subscription_plan], Group do |group| group.is_parent? and user_is_admin_of?(group.id) and (!group.has_manual_subscription?) end can [:update, :email_members, :hide_next_steps, :archive], Group do |group| user_is_admin_of?(group.id) end can :export, Group do |group| user_is_admin_of?(group.id) && group.enabled_beta_features.include?('export') end can [:members_autocomplete, :set_volume, :see_members], Group do |group| user_is_member_of?(group.id) end can [:add_members, :invite_people, :manage_membership_requests], Group do |group| (group.members_can_add_members? && user_is_member_of?(group.id)) || user_is_admin_of?(group.id) end # please note that I don't like this duplication either. # add_subgroup checks against a parent group can [:add_subgroup], Group do |group| group.is_parent? && user_is_member_of?(group.id) && (group.members_can_create_subgroups? || user_is_admin_of?(group.id)) end # create group checks against the group to be created can :create, Group do |group| # anyone can create a top level group of their own # otherwise, the group must be a subgroup # inwhich case we need to confirm membership and permission group.is_parent? || ((user_is_member_of?(group.parent.id) && group.parent.members_can_create_subgroups?)) || user_is_admin_of?(group.parent.id) end can :join, Group do |group| can?(:show, group) and group.membership_granted_upon_request? end can [:make_admin], Membership do |membership| @admin_group_ids.include?(membership.group_id) end can [:update], DiscussionReader do |reader| reader.user.id == @user.id end can [:update], Membership do |membership| membership.user.id == @user.id end can [:remove_admin, :destroy], Membership do |membership| if membership.group.members.size == 1 false elsif membership.admin? and membership.group.admins.size == 1 false else (membership.user == user) or user_is_admin_of?(membership.group_id) end end can :deactivate, User do |user_to_deactivate| not user_to_deactivate.adminable_groups.published.any? { |g| g.admins.count == 1 } end can :update, User do |user| @user == user end can :create, MembershipRequest do |request| group = request.group can?(:show, group) and group.membership_granted_upon_approval? end can :cancel, MembershipRequest, requestor_id: user.id can :cancel, Invitation do |invitation| (invitation.inviter == user) or user_is_admin_of?(invitation.group.id) end can [:approve, :ignore], MembershipRequest do |membership_request| group = membership_request.group user_is_admin_of?(group.id) or (user_is_member_of?(group.id) and group.members_can_add_members?) end can [:show, :mark_as_read], Discussion do |discussion| if discussion.is_archived? false elsif discussion.group.is_archived? false else discussion.public? or user_is_member_of?(discussion.group_id) or (discussion.group.parent_members_can_see_discussions? and user_is_member_of?(discussion.group.parent_id)) end end can :update_version, Discussion do |discussion| user_is_author_of?(discussion) or user_is_admin_of?(discussion.group_id) end can :update, Discussion do |discussion| if discussion.group.members_can_edit_discussions? user_is_member_of?(discussion.group_id) else user_is_author_of?(discussion) or user_is_admin_of?(discussion.group_id) end end can [:destroy, :move], Discussion do |discussion| user_is_author_of?(discussion) or user_is_admin_of?(discussion.group_id) end can :create, Discussion do |discussion| (discussion.group.members_can_start_discussions? && user_is_member_of?(discussion.group_id)) || user_is_admin_of?(discussion.group_id) end can [:set_volume, :new_proposal, :show_description_history, :preview_version], Discussion do |discussion| user_is_member_of?(discussion.group_id) end can [:create], Comment do |comment| user_is_member_of?(comment.group.id) && user_is_author_of?(comment) end can [:update], Comment do |comment| user_is_member_of?(comment.group.id) && user_is_author_of?(comment) && comment.can_be_edited? end can [:like, :unlike], Comment do |comment| user_is_member_of?(comment.group.id) end can :add_comment, Discussion do |discussion| user_is_member_of?(discussion.group_id) end can [:destroy], Comment do |comment| user_is_author_of?(comment) or user_is_admin_of?(comment.discussion.group_id) end can [:destroy], Attachment do |attachment| attachment.user_id == user.id end can [:create], Motion do |motion| discussion = motion.discussion discussion.motion_can_be_raised? && ((discussion.group.members_can_raise_motions? && user_is_member_of?(discussion.group_id)) || user_is_admin_of?(discussion.group_id) ) end can [:vote], Motion do |motion| discussion = motion.discussion motion.voting? && ((discussion.group.members_can_vote? && user_is_member_of?(discussion.group_id)) || user_is_admin_of?(discussion.group_id) ) end can [:create], Vote do |vote| motion = vote.motion can? :vote, motion end can [:close, :edit_close_date], Motion do |motion| motion.persisted? && motion.voting? && ((motion.author_id == user.id) || user_is_admin_of?(motion.discussion.group_id)) end can [:close], Motion do |motion| motion.persisted? && motion.voting? && ( user_is_admin_of?(motion.discussion.group_id) or user_is_author_of?(motion) ) end can [:update], Motion do |motion| motion.voting? && (motion.can_be_edited? || (not motion.restricted_changes_made?)) && (user_is_admin_of?(motion.discussion.group_id) || user_is_author_of?(motion)) end can [:destroy, :create_outcome, :update_outcome], Motion do |motion| user_is_author_of?(motion) or user_is_admin_of?(motion.discussion.group_id) end can [:show], Comment do |comment| can?(:show, comment.discussion) end can [:show, :history], Motion do |motion| can?(:show, motion.discussion) end can [:show], Vote do |vote| can?(:show, vote.motion) end end end
agpl-3.0
artefactual/archivematica-history
src/dashboard/src/media/vendor/jquery.event.drop-1.1.js
7216
/*! jquery.event.drop.js ~ v1.1 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com) Liscensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt */ ;(function($){ // secure $ jQuery alias // Created: 2008-06-04 | Updated: 2009-01-26 /*******************************************************************************************/ // Events: drop, dropstart, dropend /*******************************************************************************************/ // JQUERY METHOD $.fn.drop = function( fn1, fn2, fn3 ){ if ( fn2 ) this.bind('dropstart', fn1 ); // 2+ args if ( fn3 ) this.bind('dropend', fn3 ); // 3 args return !fn1 ? this.trigger('drop') // 0 args : this.bind('drop', fn2 ? fn2 : fn1 ); // 1+ args }; // DROP MANAGEMENT UTILITY $.dropManage = function( opts ){ // return filtered drop target elements, cache their positions opts = opts || {}; // safely set new options... drop.data = []; drop.filter = opts.filter || '*'; drop.delay = opts.delay || drop.delay; drop.tolerance = opts.tolerance || null; drop.mode = opts.mode || drop.mode || 'intersect'; // return the filtered set of drop targets return drop.$targets.filter( drop.filter ).each(function(){ // locate and store the filtered drop targets drop.data[ drop.data.length ] = drop.locate( this ); }); }; // local refs var $event = $.event, $special = $event.special, // SPECIAL EVENT CONFIGURATION drop = $special.drop = { delay: 100, // default frequency to track drop targets mode: 'intersect', // default mode to determine valid drop targets $targets: $([]), data: [], // storage of drop targets and locations setup: function(){ drop.$targets = drop.$targets.add( this ); drop.data[ drop.data.length ] = drop.locate( this ); }, teardown: function(){ var elem = this; drop.$targets = drop.$targets.not( this ); drop.data = $.grep( drop.data, function( obj ){ return ( obj.elem !== elem ); }); }, // shared handler handler: function( event ){ var dropstart = null, dropped; event.dropTarget = drop.dropping || undefined; // dropped element if ( drop.data.length && event.dragTarget ){ // handle various events switch ( event.type ){ // drag/mousemove, from $.event.special.drag case 'drag': // TOLERATE >> drop.event = event; // store the mousemove event if ( !drop.timer ) // monitor drop targets drop.timer = setTimeout( tolerate, 20 ); break; // dragstop/mouseup, from $.event.special.drag case 'mouseup': // DROP >> DROPEND >> drop.timer = clearTimeout( drop.timer ); // delete timer if ( !drop.dropping ) break; // stop, no drop if ( drop.allowed ) dropped = hijack( event, "drop", drop.dropping ); // trigger "drop" dropstart = false; // activate new target, from tolerate (async) case drop.dropping && 'dropstart': // DROPSTART >> ( new target ) dropstart = dropstart===null && drop.allowed ? true : false; // deactivate active target, from tolerate (async) case drop.dropping && 'dropend': // DROPEND >> hijack( event, "dropend", drop.dropping ); // trigger "dropend" drop.dropping = null; // empty dropper if ( dropped === false ) event.dropTarget = undefined; if ( !dropstart ) break; // stop // activate target, from tolerate (async) case drop.allowed && 'dropstart': // DROPSTART >> event.dropTarget = this; drop.dropping = hijack( event, "dropstart", this )!==false ? this : null; // trigger "dropstart" break; } } }, // returns the location positions of an element locate: function( elem ){ // return { L:left, R:right, T:top, B:bottom, H:height, W:width } var $el = $(elem), pos = $el.offset(), h = $el.outerHeight(), w = $el.outerWidth(); return { elem: elem, L: pos.left, R: pos.left+w, T: pos.top, B: pos.top+h, W: w, H: h }; }, // test the location positions of an element against another OR an X,Y coord contains: function( target, test ){ // target { L,R,T,B,H,W } contains test [x,y] or { L,R,T,B,H,W } return ( ( test[0] || test.L ) >= target.L && ( test[0] || test.R ) <= target.R && ( test[1] || test.T ) >= target.T && ( test[1] || test.B ) <= target.B ); }, // stored tolerance modes modes: { // fn scope: "$.event.special.drop" object // target with mouse wins, else target with most overlap wins 'intersect': function( event, proxy, target ){ return this.contains( target, [ event.pageX, event.pageY ] ) ? // check cursor target : this.modes['overlap'].apply( this, arguments ); // check overlap }, // target with most overlap wins 'overlap': function( event, proxy, target ){ // calculate the area of overlap... target.overlap = Math.max( 0, Math.min( target.B, proxy.B ) - Math.max( target.T, proxy.T ) ) * Math.max( 0, Math.min( target.R, proxy.R ) - Math.max( target.L, proxy.L ) ); if ( target.overlap > ( ( this.best || {} ).overlap || 0 ) ) // compare overlap this.best = target; // set as the best match so far return null; // no winner }, // proxy is completely contained within target bounds 'fit': function( event, proxy, target ){ return this.contains( target, proxy ) ? target : null; }, // center of the proxy is contained within target bounds 'middle': function( event, proxy, target ){ return this.contains( target, [ proxy.L+proxy.W/2, proxy.T+proxy.H/2 ] ) ? target : null; } } }; // set event type to custom value, and handle it function hijack ( event, type, elem ){ event.type = type; // force the event type var result = $event.handle.call( elem, event ); return result===false ? false : result || event.result; }; // async, recursive tolerance execution function tolerate (){ var i = 0, drp, winner, // local variables xy = [ drop.event.pageX, drop.event.pageY ], // mouse location drg = drop.locate( drop.event.dragProxy ); // drag proxy location drop.tolerance = drop.tolerance || drop.modes[ drop.mode ]; // custom or stored tolerance fn do if ( drp = drop.data[i] ){ // each drop target location // tolerance function is defined, or mouse contained winner = drop.tolerance ? drop.tolerance.call( drop, drop.event, drg, drp ) : drop.contains( drp, xy ) ? drp : null; // mouse is always fallback } while ( ++i<drop.data.length && !winner ); // loop drop.event.type = ( winner = winner || drop.best ) ? 'dropstart' : 'dropend'; // start ? stop if ( drop.event.type=='dropend' || winner.elem!=drop.dropping ) // don't dropstart on active drop target drop.handler.call( winner ? winner.elem : drop.dropping, drop.event ); // handle events if ( drop.last && xy[0] == drop.last.pageX && xy[1] == drop.last.pageY ) // no movement delete drop.timer; // idle, don't recurse else drop.timer = setTimeout( tolerate, drop.delay ); // recurse drop.last = drop.event; // to compare idleness drop.best = null; // reset comparitors }; /*******************************************************************************************/ })(jQuery); // confine scope
agpl-3.0
meldio/meldio
src/mutations/validator/__tests__/validateEdgeProps.js
4158
import strip from '../../../jsutils/strip'; import { expect } from 'chai'; import { describe, it } from 'mocha'; import { parse, analyzeAST, validate } from '../../../schema'; import { newGlobalId } from '../../../jsutils/globalId'; import { validateEdgeProps } from '../validateEdgeProps'; const mutation = { name: 'test', clientMutationId: 'a', globalIds: [ ] }; const schemaDefinition = ` interface Named { name: String! } interface Countable { count: Int! } type ObjOne implements Named, Countable { name: String! count: Int! } type ObjTwo implements Named { name: String! cost: Float! } union UnionOne = ObjOne union UnionTwo = ObjOne | ObjTwo type EdgePropsOne { position: String! detail: ObjOne } type EdgePropsTwo { producedSince: Int detail: ObjTwo } type Widget implements Node { id: ID! assemblies: NodeConnection(Assembly, widgets, EdgePropsOne) producers: NodeConnection(Producer, widgets, EdgePropsTwo) parts: NodeConnection(Part, widgets) } type Assembly implements Node { id: ID! widgets: NodeConnection(Widget, assemblies, EdgePropsOne) } type Producer implements Node { id: ID! widgets: NodeConnection(Widget, producers, EdgePropsTwo) } type Part implements Node { id: ID! widgets: NodeConnection(Widget, parts) } `; const ast = parse(schemaDefinition); const schema = analyzeAST(ast); const validationResult = validate(schema); const mkContext = (nodeId, field) => ({ schema, mutation, nodeId, field, function: 'addEdge' }); describe('mutations / validator / validateEdgeProps', () => { it('test schema is valid', () => { expect(validationResult).to.have.length(0); }); it('throws when context is not passed', () => { expect(validateEdgeProps).to.throw(Error, /must pass context/); }); it('error if props are passed to conn without props', () => { const nodeId = newGlobalId('Widget'); const field = schema.Widget.fields.find(f => f.name === 'parts'); const context = mkContext(nodeId, field); const output = validateEdgeProps(context, { }); expect(output.context).to.deep.equal(context); expect(output.results).to.have.length(1); expect(output.results).to.deep.match( /Edge properties cannot be passed to addEdge/); }); it('okay if props are not passed to conn without props', () => { const nodeId = newGlobalId('Widget'); const field = schema.Widget.fields.find(f => f.name === 'parts'); const context = mkContext(nodeId, field); const output = validateEdgeProps(context); expect(output.context).to.deep.equal(context); expect(output.results).to.have.length(0); }); it('error if props are not passed to conn with props that have req. fields', () => { const nodeId = newGlobalId('Widget'); const field = schema.Widget.fields.find(f => f.name === 'assemblies'); const context = mkContext(nodeId, field); const output = validateEdgeProps(context); expect(output.context).to.deep.equal(context); expect(output.results).to.have.length(1); expect(output.results).to.deep.match( /must have a required field "position"\./); }); it('okay if props are not passed to conn with props that have no req. fields', () => { const nodeId = newGlobalId('Widget'); const field = schema.Widget.fields.find(f => f.name === 'producers'); const context = mkContext(nodeId, field); const output = validateEdgeProps(context); expect(output.context).to.deep.equal(context); expect(output.results).to.have.length(0); }); it('validates edgeProps object', () => { const nodeId = newGlobalId('Widget'); const field = schema.Widget.fields.find(f => f.name === 'assemblies'); const context = mkContext(nodeId, field); const output = validateEdgeProps(context, { position: 123 }); expect(output.context).to.deep.equal(context); expect(output.results).to.have.length(1); expect(output.results).to.include( strip`Edge properties passed to addEdge should have "String" ~ value in field "position"\.`); }); });
agpl-3.0
guillaumerobin/nlp
src/AppBundle/Entity/Poll/PollVote.php
2954
<?php namespace AppBundle\Entity\Poll; use AppBundle\Entity\User; use Gedmo\Mapping\Annotation as Gedmo; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Table(name="polls_votes") * @ORM\Entity() */ class PollVote { /** * @ORM\Column(type="integer", name="id") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var \DateTime * * @Gedmo\Timestampable(on="create") * @ORM\Column(type="datetime") */ private $created; /** * @var \DateTime * * @Gedmo\Timestampable(on="update") * @ORM\Column(type="datetime") */ private $updated; /** * @ORM\ManyToOne(targetEntity="Poll") * * @var Poll */ private $poll; /** * @var string * * @ORM\Column(type="string", length=46) * * @Assert\Ip() * @Assert\NotBlank() */ private $ip; /** * @var AppBundle\Entity\User * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User") * @ORM\JoinColumn(name="user_id", referencedColumnName="user_id") */ private $voter; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="PollQuestionVote", mappedBy="vote", cascade={"persist", "remove"}) */ private $questionVotes; /** * Constructor. */ public function __construct(Poll $poll, $ip, User $user) { $this->poll = $poll; $this->ip = $ip; $this->voter = $user; $this->questionVotes = new ArrayCollection(); foreach ($poll->getQuestions() as $question) { $this->questionVotes->add(new PollQuestionVote($this, $question)); } } /** * Get id. * * @return integer */ public function getId() { return $this->id; } /** * Get created. * * @return \DateTime */ public function getCreated() { return $this->created; } /** * Get updated. * * @return \DateTime */ public function getUpdated() { return $this->updated; } /** * Get IP. * * @return string */ public function getIp() { return $this->ip; } /** * Set IP. * * @param string $ip */ public function setIp($ip) { $this->ip = $ip; } /** * Get poll. * * @return Election */ public function getPoll() { return $this->poll; } /** * Get voter. * * @return \AppBundle\Entity\User */ public function getVoter() { return $this->voter; } /** * Get questionVotes. * * @return \Doctrine\Common\Collections\Collection */ public function getQuestionVotes() { return $this->questionVotes; } }
agpl-3.0
grupoProyecto1/gestionTienda
src/Modelo/ConexionBBDD.java
1678
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author Mario */ public class ConexionBBDD { private static Connection conn = null; /** * Realiza la conexion con la Base de Datos * * @return Objeto de la clase Connection con la conexion establecida */ public static Connection getConnection() { try { if (conn == null) { Runtime.getRuntime().addShutdownHook(new MiShDwHook()); String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost/empresa"; String usuario = "usrproged"; String password = "usrproged"; Class.forName(driver); conn = DriverManager.getConnection(url, usuario, password); } return conn; } catch (SQLException | ClassNotFoundException ex) { return null; } } /* * Creamos un hilo para que automaticamente se cierre la conexion de la BD */ static class MiShDwHook extends Thread { @Override public void run() { try { Connection conn = ConexionBBDD.getConnection(); conn.close(); } catch (SQLException ex) { System.out.println("No se ha podido cerrar la conexion."); } } } }
agpl-3.0
JuanjoA/l10n-spain
l10n_es_aeat_mod303/tests/test_l10n_es_aeat_mod303.py
4854
# -*- coding: utf-8 -*- # © 2016 Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0 from openerp.tests import common class TestL10nEsAeatMod303Base(object): def setUp(self): super(TestL10nEsAeatMod303Base, self).setUp() self.partner = self.env['res.partner'].create({'name': 'Test partner'}) self.product = self.env['product.product'].create({ 'name': 'Test product', }) self.account_type = self.env['account.account.type'].create({ 'name': 'Test account type', 'code': 'TEST', }) self.account_expense = self.env['account.account'].create({ 'name': 'Test expense account', 'code': 'EXP', 'type': 'other', 'user_type': self.account_type.id, }) self.analytic_account_1 = self.env['account.analytic.account'].create({ 'name': 'Test analytic account 1', 'type': 'normal', }) self.analytic_account_2 = self.env['account.analytic.account'].create({ 'name': 'Test analytic account 2', 'type': 'normal', }) self.account_tax = self.env['account.account'].create({ 'name': 'Test tax account', 'code': 'TAX', 'type': 'other', 'user_type': self.account_type.id, }) self.base_code = self.env['account.tax.code'].create({ 'name': '[28] Test base code', 'code': 'OICBI', }) self.tax_code = self.env['account.tax.code'].create({ 'name': '[29] Test tax code', 'code': 'SOICC', }) self.tax = self.env['account.tax'].create({ 'name': 'Test tax 10%', 'type_tax_use': 'purchase', 'type': 'percent', 'amount': '0.10', 'account_collected_id': self.account_tax.id, 'base_code_id': self.base_code.id, 'base_sign': 1, 'tax_code_id': self.tax_code.id, 'tax_sign': 1, }) self.period = self.env['account.period'].find() self.invoice = self.env['account.invoice'].create({ 'partner_id': self.partner.id, 'type': 'in_invoice', 'period_id': self.period.id, 'account_id': self.partner.property_account_payable.id, 'invoice_line': [ (0, 0, { 'product_id': self.product.id, 'account_id': self.account_expense.id, 'account_analytic_id': self.analytic_account_1.id, 'name': 'Test line', 'price_unit': 100, 'quantity': 1, 'invoice_line_tax_id': [(6, 0, self.tax.ids)], }), (0, 0, { 'product_id': self.product.id, 'account_id': self.account_expense.id, 'account_analytic_id': self.analytic_account_2.id, 'name': 'Test line', 'price_unit': 100, 'quantity': 2, 'invoice_line_tax_id': [(6, 0, self.tax.ids)], }), (0, 0, { 'product_id': self.product.id, 'account_id': self.account_expense.id, 'name': 'Test line', 'price_unit': 100, 'quantity': 1, 'invoice_line_tax_id': [(6, 0, self.tax.ids)], }), ], }) self.invoice.signal_workflow('invoice_open') self.model303 = self.env['l10n.es.aeat.mod303.report'].create({ 'company_vat': '1234567890', 'contact_phone': 'X', 'fiscalyear_id': self.period.fiscalyear_id.id, 'periods': [(6, 0, self.period.ids)], }) class TestL10nEsAeatMod303(TestL10nEsAeatMod303Base, common.TransactionCase): def test_model_303(self): self.model303.button_calculate() self.assertEqual(self.model303.total_deducir, 40) self.assertEqual(self.model303.casilla_46, -40) self.assertEqual(self.model303.casilla_69, -40) # Export to BOE export_to_boe = self.env['l10n.es.aeat.report.export_to_boe'].create({ 'name': 'test_export_to_boe.txt', }) export_config_xml_ids = [ 'l10n_es_aeat_mod303.aeat_mod303_2018_main_export_config', 'l10n_es_aeat_mod303.aeat_mod303_2021_main_export_config', 'l10n_es_aeat_mod303.aeat_mod303_202107_main_export_config', ] for xml_id in export_config_xml_ids: export_config = self.env.ref(xml_id) self.assertTrue( export_to_boe._export_config(self.model303, export_config) )
agpl-3.0
akvo/akvo-sites-zz-template
code/wp-content/plugins/ninja-forms/includes/Config/BatchProcesses.php
620
<?php if ( ! defined( 'ABSPATH' ) ) exit; return apply_filters( 'ninja_forms_batch_processes', array( 'chunked_publish' => array( 'class_name' => 'NF_Admin_Processes_ChunkPublish', ), 'data_cleanup' => array( 'class_name' => 'NF_Admin_Processes_DataCleanup', ), 'expired_submission_cleanup' => array( 'class_name' => 'NF_Admin_Processes_ExpiredSubmissionCleanup', ), 'import_form' => array( 'class_name' => 'NF_Admin_Processes_ImportForm', ), 'import_form_template' => array( 'class_name' => 'NF_Admin_Processes_ImportFormTemplate', ), ));
agpl-3.0
Program-AR/pilas-bloques
tests/helpers/actividadTest.js
7468
import { run } from '@ember/runloop'; import setupMirage from "ember-cli-mirage/test-support/setup-mirage"; import 'ember-qunit'; import { setupPBIntegrationTest, acceptTerms } from '../helpers/utils' import hbs from 'htmlbars-inline-precompile'; import jQuery from 'jquery'; import { module, skip, test } from 'qunit'; import simulateRouterHooks from "./simulate-router.hooks"; import { failAllApiFetchs } from './utils'; /** * Inicia los tests de la actividad definiendo un grupo para qunit. */ export function moduloActividad(nombre, runActivityTests) { module(`Integration | Actividad | ${nombre}`, (hooks) => { setupPBIntegrationTest(hooks); setupMirage(hooks); acceptTerms(hooks); runActivityTests(hooks); }); } /** * Realiza una validación en la cantidad de actores, este función se utiliza * como helper para aquellos tests que intentan contar actores antes y * después de realizar una actividad. */ function validarCantidadDeActores(actoresEsperadosPorEtiqueta, assert, pilas) { $.each(actoresEsperadosPorEtiqueta, (etiqueta, cantidadEsperada) => { let mensaje = `Hay ${cantidadEsperada} actores con la etiqueta ${etiqueta}.`; assert.equal(pilas.contarActoresConEtiqueta(etiqueta), cantidadEsperada, mensaje); }); } /** * Valida las opciones enviadas al test de la actividad para detectar * errores o inconsistencias en las opciones antes de iniciar cualquier * test. * * Retorna True si alguna de las opciones enviadas es incorrecta. */ function validarOpciones(opciones) { let listaDeOpciones = Object.keys(opciones); let opcionesValidas = [ 'solucion', 'descripcionAdicional', 'errorEsperado', 'resuelveDesafio', 'cantidadDeActoresAlComenzar', 'cantidadDeActoresAlTerminar', 'fps', 'skip' ]; function esOpcionInvalida(opcion) { return (opcionesValidas.indexOf(opcion) === -1); } let opcionesInvalidas = $.grep(listaDeOpciones, esOpcionInvalida); $.map(opcionesInvalidas, (opcionInvalida) => { let error = `La opcion enviada al test (${opcionInvalida}) es inválida.`; throw new Error(error); }); if (opciones.errorEsperado && opciones.cantidadDeActoresAlTerminar) { let error = `Es inválido escribir un test que incluya un errorEsperado y conteo de actores al terminar.`; throw new Error(error); } return (opcionesInvalidas.length > 0); } /** * Permite realizar una prueba sobre una actividad y su comportamiento. * * Argumentos: * * - nombre: El identificador de la actividad, por ejemplo "AlienTocaBoton". * - opciones: Un diccionario de opciones, con las siguientes claves: * * - solucion (obligatorio): El código xml de la solución en base64. * - descripcionAdicional: Un string con un detalle del objetivo del test. * - errorEsperado: El string que debería llevar una excepción esperada. * - cantidadDeActoresAlComenzar: Un diccionario para validar la cantidad de actores en la escena. * - cantidadDeActoresAlTerminar: Un diccionario para validar la cantidad de actores en la escena. * - fps: Los cuadros por segundo esperados (por omisión 200 en los test y 60 normalmente). * - resuelveDesafio: Si es false, verifica que la solución NO resuelva el problema. * - skip: Si es true, se salteara este test. * * Para ejemplos de invocación podés ver: actividadElAlienYLasTuercas-test.js */ export function actividadTest(nombre, opciones) { if (validarOpciones(opciones)) { throw new Error(`Se ha iniciado el tests ${nombre} con opciones inválidas.`); } let descripcion = opciones.descripcionAdicional || 'Se puede resolver'; ((opciones.skip) ? skip : test)(descripcion, function (assert) { let store = this.owner.lookup('service:store'); let pilas = this.owner.lookup('service:pilas'); failAllApiFetchs() this.owner.lookup('service:pilas-bloques-api').logout(); //let actividades = this.owner.lookup('service:actividades'); return new Promise((success) => { run(async () => { // Simulate the model hook from router. simulateRouterHooks(store); /** * TODO: replace the findAll and findBy functions by a * more specific ember-data query, like findRecord which * fetchs only one record. * * (This only exist because mirage must be need fixed before). */ const model = (await store.findAll("desafio")).findBy('nombre', nombre); if (!model) { throw new Error(`No existe una actividad con el nombre ${nombre}`); } this.set('model', model); this.set('pilas', pilas); // Carga la solución en base64, el formato que espera el componente. this.set('solucion', window.btoa(opciones.solucion)); // Captura el evento de inicialización de pilas: this.set('onReady', () => { if (opciones.cantidadDeActoresAlComenzar) { validarCantidadDeActores(opciones.cantidadDeActoresAlComenzar, assert, pilas); } setTimeout(() => { jQuery('#turbo-button').click(); jQuery('#run-button').click(); }, 1000); }); /** * Si hay un error en la actividad intenta determinar * si es un error esperado o no. Y en cualquiera de los * dos casos finaliza el test. */ this.set("onErrorDeActividad", function (motivoDelError) { let errorEsperado = opciones.errorEsperado; if (errorEsperado) { assert.equal(motivoDelError, errorEsperado, `Ocurrió el error esperado: '${errorEsperado}'. Bien!`); } else { assert.notOk(`Ocurrió un error inesperado: '${motivoDelError}'`); } success(); }); this.set('onTerminoEjecucion', () => { if (opciones.cantidadDeActoresAlTerminar) { validarCantidadDeActores(opciones.cantidadDeActoresAlTerminar, assert, pilas); } // Los errores esperados no deberían llegar a este punto, así // que se emite un error. let errorEsperado = opciones.errorEsperado; if (errorEsperado) { assert.notOk(`No ocurrió el error esperado: '${errorEsperado}'`); } else if (opciones.resuelveDesafio === false) { assert.ok(!pilas.estaResueltoElProblema(), "Se esperaba que la solución no resuelva el problema"); } else { assert.ok(pilas.estaResueltoElProblema(), "Se puede resolver el problema"); } success(); }); /** * Se instancia el componente challenge-workspace con los paneles que * observará el usuario y una solución pre-cargada, tal y como se * hace dentro de la aplicación. */ this.render(hbs` {{challenge-workspace debug=false pilas=pilas model=model showCode=false onReady=onReady codigo=solucion codigoJavascript="" persistirSolucionEnURL=false onTerminoEjecucion=onTerminoEjecucion onErrorDeActividad=onErrorDeActividad debeMostrarFinDeDesafio=false }} `); }); }); }); }
agpl-3.0
see-r/SeerDataCruncher
src/main/java/com/datacruncher/jpa/entity/FieldTypeEntity.java
4181
/* * DataCruncher * Copyright (c) Mario Altimari. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.datacruncher.jpa.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author danilo */ @Entity @Table(name = "jv_fields_types") @NamedQueries({ @NamedQuery(name = "FieldTypeEntity.findAll", query = "SELECT j FROM FieldTypeEntity j"), @NamedQuery(name = "FieldTypeEntity.findByIdFieldType", query = "SELECT j FROM FieldTypeEntity j WHERE j.idFieldType = :idFieldType"), @NamedQuery(name = "FieldTypeEntity.findByDescription", query = "SELECT j FROM FieldTypeEntity j WHERE j.description = :description"), @NamedQuery(name = "FieldTypeEntity.findByMappedType", query = "SELECT j FROM FieldTypeEntity j WHERE j.mappedType = :mappedType"), @NamedQuery(name = "FieldTypeEntity.findByFieldLength", query = "SELECT j FROM FieldTypeEntity j WHERE j.fieldLength = :fieldLength"), @NamedQuery(name = "FieldTypeEntity.count", query = "SELECT COUNT(j) FROM FieldTypeEntity j")}) public class FieldTypeEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id_field_type") private Integer idFieldType; @Basic(optional = false) @Column(name = "description") private String description; @Basic(optional = false) @Column(name = "mapped_type") private String mappedType; @Column(name = "field_length") private Integer fieldLength; public FieldTypeEntity() { } public FieldTypeEntity(Integer idFieldType) { this.idFieldType = idFieldType; } public FieldTypeEntity(Integer idFieldType, String description, String mappedType) { this.idFieldType = idFieldType; this.description = description; this.mappedType = mappedType; } public Integer getIdFieldType() { return idFieldType; } public void setIdFieldType(Integer idFieldType) { this.idFieldType = idFieldType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMappedType() { return mappedType; } public void setMappedType(String mappedType) { this.mappedType = mappedType; } public Integer getFieldLength() { return fieldLength; } public void setFieldLength(Integer fieldLength) { this.fieldLength = fieldLength; } @Override public int hashCode() { int hash = 0; hash += (idFieldType != null ? idFieldType.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof FieldTypeEntity)) { return false; } FieldTypeEntity other = (FieldTypeEntity) object; if ((this.idFieldType == null && other.idFieldType != null) || (this.idFieldType != null && !this.idFieldType.equals(other.idFieldType))) { return false; } return true; } @Override public String toString() { return "FieldTypeEntity[idFieldType=" + idFieldType + "]"; } }
agpl-3.0
bluestreak01/questdb
core/src/main/java/io/questdb/cutlass/http/HttpResponseSink.java
22932
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2022 QuestDB * * 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 io.questdb.cutlass.http; import io.questdb.log.Log; import io.questdb.log.LogFactory; import io.questdb.network.*; import io.questdb.std.*; import io.questdb.std.datetime.millitime.DateFormatUtils; import io.questdb.std.datetime.millitime.MillisecondClock; import io.questdb.std.ex.ZLibException; import io.questdb.std.str.AbstractCharSink; import io.questdb.std.str.CharSink; import io.questdb.std.str.StdoutSink; import java.io.Closeable; public class HttpResponseSink implements Closeable, Mutable { private final static Log LOG = LogFactory.getLog(HttpResponseSink.class); private static final IntObjHashMap<String> httpStatusMap = new IntObjHashMap<>(); static { httpStatusMap.put(200, "OK"); httpStatusMap.put(206, "Partial content"); httpStatusMap.put(304, "Not Modified"); httpStatusMap.put(400, "Bad request"); httpStatusMap.put(404, "Not Found"); httpStatusMap.put(416, "Request range not satisfiable"); httpStatusMap.put(431, "Headers too large"); httpStatusMap.put(500, "Internal server error"); } private final ChunkBuffer buffer; private ChunkBuffer compressOutBuffer; private final HttpResponseHeaderImpl headerImpl; private final SimpleResponseImpl simple = new SimpleResponseImpl(); private final ResponseSinkImpl sink = new ResponseSinkImpl(); private final ChunkedResponseImpl chunkedResponse = new ChunkedResponseImpl(); private final HttpRawSocketImpl rawSocket = new HttpRawSocketImpl(); private final NetworkFacade nf; private final int responseBufferSize; private final boolean dumpNetworkTraffic; private final String httpVersion; private long fd; private long z_streamp = 0; private boolean deflateBeforeSend = false; private int crc = 0; private long total = 0; private long totalBytesSent = 0; private final boolean connectionCloseHeader; private boolean headersSent; private boolean chunkedRequestDone; private boolean compressedHeaderDone; private boolean compressedOutputReady; private boolean compressionComplete; public HttpResponseSink(HttpContextConfiguration configuration) { this.responseBufferSize = Numbers.ceilPow2(configuration.getSendBufferSize()); this.nf = configuration.getNetworkFacade(); this.buffer = new ChunkBuffer(responseBufferSize); this.headerImpl = new HttpResponseHeaderImpl(configuration.getClock()); this.dumpNetworkTraffic = configuration.getDumpNetworkTraffic(); this.httpVersion = configuration.getHttpVersion(); this.connectionCloseHeader = !configuration.getServerKeepAlive(); } public HttpChunkedResponseSocket getChunkedSocket() { return chunkedResponse; } @Override public void clear() { headerImpl.clear(); totalBytesSent = 0; headersSent = false; chunkedRequestDone = false; resetZip(); } @Override public void close() { if (z_streamp != 0) { Zip.deflateEnd(z_streamp); z_streamp = 0; compressOutBuffer.close(); compressOutBuffer = null; } buffer.close(); } public void setDeflateBeforeSend(boolean deflateBeforeSend) { this.deflateBeforeSend = deflateBeforeSend; if (z_streamp == 0 && deflateBeforeSend) { z_streamp = Zip.deflateInit(); compressOutBuffer = new ChunkBuffer(responseBufferSize); } } public int getCode() { return headerImpl.getCode(); } public SimpleResponseImpl getSimple() { return simple; } public void resumeSend() throws PeerDisconnectedException, PeerIsSlowToReadException { if (!headersSent || !deflateBeforeSend) { sendBuffer(buffer); return; } while (true) { if (!compressedOutputReady && !compressionComplete) { deflate(); } if (compressedOutputReady) { sendBuffer(compressOutBuffer); compressedOutputReady = false; if (compressionComplete) { break; } } else { break; } } } private void deflate() { if (!compressedHeaderDone) { int len = Zip.gzipHeaderLen; Vect.memcpy(compressOutBuffer.getWriteAddress(len), Zip.gzipHeader, len); compressOutBuffer.onWrite(len); compressedHeaderDone = true; } int nInAvailable = (int) buffer.getReadNAvailable(); if (nInAvailable > 0) { long inAddress = buffer.getReadAddress(); LOG.debug().$("Zip.setInput [inAddress=").$(inAddress).$(", nInAvailable=").$(nInAvailable).$(']').$(); buffer.write64BitZeroPadding(); Zip.setInput(z_streamp, inAddress, nInAvailable); } int ret; int len; // compress input until we run out of either input or output do { int sz = (int) compressOutBuffer.getWriteNAvailable() - 8; long p = compressOutBuffer.getWriteAddress(0); LOG.debug().$("deflate starting [p=").$(p).$(", sz=").$(sz).$(", chunkedRequestDone=").$(chunkedRequestDone).$(']').$(); ret = Zip.deflate(z_streamp, p, sz, chunkedRequestDone); len = sz - Zip.availOut(z_streamp); compressOutBuffer.onWrite(len); if (ret < 0) { // This is not an error, zlib just couldn't do any work with the input/output buffers it was provided. // This happens often (will depend on output buffer size) when there is no new input and zlib has finished generating // output from previously provided input if (ret != Zip.Z_BUF_ERROR || len != 0) { throw HttpException.instance("could not deflate [ret=").put(ret); } } int availIn = Zip.availIn(z_streamp); int nInConsumed = nInAvailable - availIn; if (nInConsumed > 0) { this.crc = Zip.crc32(this.crc, buffer.getReadAddress(), nInConsumed); this.total += nInConsumed; buffer.onRead(nInConsumed); nInAvailable = availIn; } LOG.debug().$("deflate finished [ret=").$(ret).$(", len=").$(len).$(", availIn=").$(availIn).$(']').$(); } while (len == 0 && nInAvailable > 0); if (nInAvailable == 0) { buffer.clearAndPrepareToWriteToBuffer(); } if (len == 0) { compressedOutputReady = false; return; } compressedOutputReady = true; // this is ZLib error, can't continue if (len < 0) { throw ZLibException.INSTANCE; } // trailer boolean finished = chunkedRequestDone && ret == Zip.Z_STREAM_END; if (finished) { long p = compressOutBuffer.getWriteAddress(0); Unsafe.getUnsafe().putInt(p, crc); // crc Unsafe.getUnsafe().putInt(p + 4, (int) total); // total compressOutBuffer.onWrite(8); compressionComplete = true; } compressOutBuffer.prepareToReadFromBuffer(true, finished); } private void flushSingle() throws PeerDisconnectedException, PeerIsSlowToReadException { sendBuffer(buffer); } HttpResponseHeader getHeader() { return headerImpl; } HttpRawSocket getRawSocket() { return rawSocket; } void of(long fd) { this.fd = fd; } private void prepareHeaderSink() { buffer.prepareToReadFromBuffer(false, false); headerImpl.prepareToSend(); } private void resetZip() { if (z_streamp != 0) { Zip.deflateReset(z_streamp); compressOutBuffer.clear(); this.crc = 0; this.total = 0; compressedHeaderDone = false; compressedOutputReady = false; compressionComplete = false; } } private void sendBuffer(ChunkBuffer sendBuf) throws PeerDisconnectedException, PeerIsSlowToReadException { int nSend = (int) sendBuf.getReadNAvailable(); while (nSend > 0) { int n = nf.send(fd, sendBuf.getReadAddress(), nSend); if (n < 0) { // disconnected LOG.error() .$("disconnected [errno=").$(nf.errno()) .$(", fd=").$(fd) .$(']').$(); throw PeerDisconnectedException.INSTANCE; } if (n == 0) { // test how many times we tried to send before parking up throw PeerIsSlowToReadException.INSTANCE; } else { dumpBuffer(sendBuf.getReadAddress(), n); sendBuf.onRead(n); nSend -= n; totalBytesSent += n; } } assert sendBuf.getReadNAvailable() == 0; sendBuf.clearAndPrepareToWriteToBuffer(); } private void dumpBuffer(long buffer, int size) { if (dumpNetworkTraffic && size > 0) { StdoutSink.INSTANCE.put('<'); Net.dump(buffer, size); } } long getTotalBytesSent() { return totalBytesSent; } public class HttpResponseHeaderImpl extends AbstractCharSink implements Mutable, HttpResponseHeader { private final MillisecondClock clock; private boolean chunky; private int code; public HttpResponseHeaderImpl(MillisecondClock clock) { this.clock = clock; } @Override public void clear() { buffer.clearAndPrepareToWriteToBuffer(); chunky = false; } // this is used for HTTP access logging public int getCode() { return code; } @Override public CharSink put(CharSequence cs) { int len = cs.length(); Chars.asciiStrCpy(cs, len, buffer.getWriteAddress(len)); buffer.onWrite(len); return this; } @Override public CharSink put(char c) { Unsafe.getUnsafe().putByte(buffer.getWriteAddress(1), (byte) c); buffer.onWrite(1); return this; } @Override public CharSink put(char[] chars, int start, int len) { throw new UnsupportedOperationException(); } @Override public void send() throws PeerDisconnectedException, PeerIsSlowToReadException { headerImpl.prepareToSend(); flushSingle(); } @Override public String status(CharSequence httpProtocolVersion, int code, CharSequence contentType, long contentLength) { this.code = code; String status = httpStatusMap.get(code); if (status == null) { throw new IllegalArgumentException("Illegal status code: " + code); } buffer.clearAndPrepareToWriteToBuffer(); put(httpProtocolVersion).put(code).put(' ').put(status).put(Misc.EOL); put("Server: ").put("questDB/1.0").put(Misc.EOL); put("Date: "); DateFormatUtils.formatHTTP(this, clock.getTicks()); put(Misc.EOL); if (contentLength > -2) { this.chunky = (contentLength == -1); if (this.chunky) { put("Transfer-Encoding: ").put("chunked").put(Misc.EOL); } else { put("Content-Length: ").put(contentLength).put(Misc.EOL); } } if (contentType != null) { put("Content-Type: ").put(contentType).put(Misc.EOL); } if (connectionCloseHeader) { put("Connection: close").put(Misc.EOL); } return status; } private void prepareToSend() { if (!chunky) { put(Misc.EOL); } } } public class SimpleResponseImpl { public void sendStatus(int code, CharSequence message) throws PeerDisconnectedException, PeerIsSlowToReadException { buffer.clearAndPrepareToWriteToBuffer(); final String std = headerImpl.status(httpVersion, code, "text/plain; charset=utf-8", -1L); prepareHeaderSink(); flushSingle(); buffer.clearAndPrepareToWriteToBuffer(); sink.put(message == null ? std : message).put(Misc.EOL); buffer.prepareToReadFromBuffer(true, true); resumeSend(); } public void sendStatus(int code) throws PeerDisconnectedException, PeerIsSlowToReadException { buffer.clearAndPrepareToWriteToBuffer(); headerImpl.status(httpVersion, code, "text/html; charset=utf-8", -2L); prepareHeaderSink(); flushSingle(); } public void sendStatusWithDefaultMessage(int code) throws PeerDisconnectedException, PeerIsSlowToReadException { sendStatus(code, null); } } private class ResponseSinkImpl extends AbstractCharSink { @Override public CharSink put(CharSequence seq) { buffer.put(seq); return this; } @Override public CharSink put(CharSequence cs, int lo, int hi) { buffer.put(cs, lo, hi); return this; } @Override public CharSink put(char c) { buffer.put(c); return this; } @Override public CharSink put(char[] chars, int start, int len) { buffer.put(chars, start, len); return this; } @Override public CharSink put(float value, int scale) { if (Float.isNaN(value)) { put("null"); return this; } return super.put(value, scale); } @Override public CharSink put(double value, int scale) { if (Double.isNaN(value) || Double.isInfinite(value)) { put("null"); return this; } return super.put(value, scale); } @Override public void putUtf8Special(char c) { if (c < 32) { escapeSpace(c); } else { switch (c) { case '/': case '\"': case '\\': put('\\'); // intentional fall through default: put(c); break; } } } public void status(int status, CharSequence contentType) { buffer.clearAndPrepareToWriteToBuffer(); headerImpl.status("HTTP/1.1 ", status, contentType, -1); } private void escapeSpace(char c) { switch (c) { case '\0': break; case '\b': put("\\b"); break; case '\f': put("\\f"); break; case '\n': put("\\n"); break; case '\r': put("\\r"); break; case '\t': put("\\t"); break; default: put(c); break; } } } public class HttpRawSocketImpl implements HttpRawSocket { @Override public long getBufferAddress() { return buffer.getWriteAddress(1); } @Override public int getBufferSize() { return (int) buffer.getWriteNAvailable(); } @Override public void send(int size) throws PeerDisconnectedException, PeerIsSlowToReadException { buffer.onWrite(size); buffer.prepareToReadFromBuffer(false, false); flushSingle(); buffer.clearAndPrepareToWriteToBuffer(); } } private class ChunkedResponseImpl extends ResponseSinkImpl implements HttpChunkedResponseSocket { private long bookmark = 0; @Override public void bookmark() { bookmark = buffer._wptr; } @Override public void done() throws PeerDisconnectedException, PeerIsSlowToReadException { if (!chunkedRequestDone) { sendChunk(true); } } @Override public HttpResponseHeader headers() { return headerImpl; } @Override public boolean resetToBookmark() { buffer._wptr = bookmark; return bookmark != buffer.bufStartOfData; } @Override public void sendChunk(boolean done) throws PeerDisconnectedException, PeerIsSlowToReadException { headersSent = true; chunkedRequestDone = done; if (buffer.getReadNAvailable() > 0 || done) { if (!deflateBeforeSend) { buffer.prepareToReadFromBuffer(true, chunkedRequestDone); } resumeSend(); } } @Override public void sendHeader() throws PeerDisconnectedException, PeerIsSlowToReadException { chunkedRequestDone = false; prepareHeaderSink(); flushSingle(); buffer.clearAndPrepareToWriteToBuffer(); } @Override public void status(int status, CharSequence contentType) { super.status(status, contentType); if (deflateBeforeSend) { headerImpl.put("Content-Encoding: gzip").put(Misc.EOL); } } @Override public void shutdownWrite() { nf.shutdown(fd, Net.SHUT_WR); } } private class ChunkBuffer extends AbstractCharSink implements Closeable { private static final int MAX_CHUNK_HEADER_SIZE = 12; private static final String EOF_CHUNK = "\r\n00\r\n\r\n"; private long bufStart; private final long bufStartOfData; private long bufEndOfData; private long _wptr; private long _rptr; private ChunkBuffer(int sz) { bufStart = Unsafe.malloc(sz + MAX_CHUNK_HEADER_SIZE + EOF_CHUNK.length(), MemoryTag.NATIVE_HTTP_CONN); bufStartOfData = bufStart + MAX_CHUNK_HEADER_SIZE; bufEndOfData = bufStartOfData + sz; clear(); } @Override public void close() { if (0 != bufStart) { Unsafe.free(bufStart, bufEndOfData - bufStart + EOF_CHUNK.length(), MemoryTag.NATIVE_HTTP_CONN); bufStart = bufEndOfData = _wptr = _rptr = 0; } } void clear() { _wptr = _rptr = bufStartOfData; } long getReadAddress() { assert _rptr != 0; return _rptr; } long getReadNAvailable() { return _wptr - _rptr; } void onRead(int nRead) { assert nRead >= 0 && nRead <= getReadNAvailable(); _rptr += nRead; } long getWriteAddress(int len) { assert _wptr != 0; if (getWriteNAvailable() >= len) { return _wptr; } throw NoSpaceLeftInResponseBufferException.INSTANCE; } long getWriteNAvailable() { return bufEndOfData - _wptr; } void onWrite(int nWrite) { assert nWrite >= 0 && nWrite <= getWriteNAvailable(); _wptr += nWrite; } void write64BitZeroPadding() { Unsafe.getUnsafe().putLong(bufStartOfData - 8, 0); Unsafe.getUnsafe().putLong(_wptr, 0); } @Override public CharSink put(CharSequence cs) { int len = cs.length(); Chars.asciiStrCpy(cs, len, getWriteAddress(len)); onWrite(len); return this; } @Override public CharSink put(char c) { Unsafe.getUnsafe().putByte(getWriteAddress(1), (byte) c); onWrite(1); return this; } @Override public CharSink put(char[] chars, int start, int len) { Chars.asciiCopyTo(chars, start, len, getWriteAddress(len)); onWrite(len); return this; } @Override public CharSink put(CharSequence cs, int lo, int hi) { int len = hi - lo; Chars.asciiStrCpy(cs, lo, len, getWriteAddress(len)); onWrite(len); return this; } void clearAndPrepareToWriteToBuffer() { _rptr = _wptr = bufStartOfData; } void prepareToReadFromBuffer(boolean addChunkHeader, boolean addEofChunk) { if (addChunkHeader) { int len = (int) (_wptr - bufStartOfData); int padding = len == 0 ? 6 : (Integer.numberOfLeadingZeros(len) >> 3) << 1; long tmp = _wptr; _rptr = _wptr = bufStart + padding; put(Misc.EOL); Numbers.appendHex(this, len); put(Misc.EOL); _wptr = tmp; } if (addEofChunk) { int len = EOF_CHUNK.length(); Chars.asciiStrCpy(EOF_CHUNK, len, _wptr); _wptr += len; LOG.debug().$("end chunk sent [fd=").$(fd).$(']').$(); } } } }
agpl-3.0
asm-products/tiptrace
Manage/Content/Javascript/jquery-ui-1.10.3.js
254448
/*! jQuery UI - v1.10.3 - 2013-11-21 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.datepicker.js, jquery.ui.slider.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.10.3", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use $.widget() extensions instead. plugin: { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var i, set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.10.3", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown."+this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click."+this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("."+this.widgetName); if ( this._mouseMoveDelegate ) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; $(document) .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) .bind("mouseup."+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); })(jQuery); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !$.support.offsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem : elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function () { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); }( jQuery ) ); (function( $, undefined ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._mouseInit(); }, _destroy: function() { this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth+"px", height: this.offsetHeight+"px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if(this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if(this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if(this.dropped) { dropped = this.dropped; this.dropped = false; } //if the original element is no longer in the DOM don't bother to continue (see #8269) if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) { return false; } if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if(that._trigger("stop", event) !== false) { that._clear(); } }); } else { if(this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if(this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if(!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } //This needs to be actually done for all browsers, since pageX/pageY includes this information //Ugly IE fix if((this.offsetParent[0] === document.body) || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.element.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) , ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; } return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod ) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod ) ) }; }, _generatePosition: function(event) { var containment, co, top, left, o = this.options, scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent, pageX = event.pageX, pageY = event.pageY; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( this.originalPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if(event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if(o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call(this, type, [event, ui]); //The absolute position has to be recalculated after plugins if(type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function(event, ui) { var inst = $(this).data("ui-draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, "ui-sortable"); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function(event, ui) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var inst = $(this).data("ui-draggable"), uiSortable = $.extend({}, ui, { item: inst.element }); $.each(inst.sortables, function() { if(this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if(this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if(inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function(event, ui) { var inst = $(this).data("ui-draggable"), that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if(this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function () { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if(innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if(!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if(this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if(this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if(this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function() { var t = $("body"), o = $(this).data("ui-draggable").options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function() { var o = $(this).data("ui-draggable").options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function() { var i = $(this).data("ui-draggable"); if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event ) { var i = $(this).data("ui-draggable"), o = i.options, scrolled = false; if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { if(!o.axis || o.axis !== "x") { if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if(!o.axis || o.axis !== "y") { if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if(!o.axis || o.axis !== "x") { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if(!o.axis || o.axis !== "y") { if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function() { var i = $(this).data("ui-draggable"), o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if(this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function(event, ui) { var ts, bs, ls, rs, l, r, t, b, i, first, inst = $(this).data("ui-draggable"), o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if(inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if(o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if(ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if(o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if(ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function() { var min, o = this.data("ui-draggable").options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); })(jQuery); (function( $, undefined ) { function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } $.widget("ui.droppable", { version: "1.10.3", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, _destroy: function() { var i = 0, drop = $.ui.ddmanager.droppables[this.options.scope]; for ( ; i < drop.length; i++ ) { if ( drop[i] === this ) { drop.splice(i, 1); } } this.element.removeClass("ui-droppable ui-droppable-disabled"); }, _setOption: function(key, value) { if(key === "accept") { this.accept = $.isFunction(value) ? value : function(d) { return d.is(value); }; } $.Widget.prototype._setOption.apply(this, arguments); }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) { this.element.addClass(this.options.activeClass); } if(draggable){ this._trigger("activate", event, this.ui(draggable)); } }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if(draggable){ this._trigger("deactivate", event, this.ui(draggable)); } }, _over: function(event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return; } if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) { this.element.addClass(this.options.hoverClass); } this._trigger("over", event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return; } if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("out", event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { return false; } this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, "ui-droppable"); if( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) ) { childrenIntersection = true; return false; } }); if(childrenIntersection) { return false; } if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if(this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("drop", event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) { return false; } var draggableLeft, draggableTop, x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case "fit": return (l <= x1 && x2 <= r && t <= y1 && y2 <= b); case "intersect": return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half x2 - (draggable.helperProportions.width / 2) < r && // Left Half t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half y2 - (draggable.helperProportions.height / 2) < b ); // Top Half case "pointer": draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left); draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top); return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width ); case "touch": return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); default: return false; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function(t, event) { var i, j, m = $.ui.ddmanager.droppables[t.options.scope] || [], type = event ? event.type : null, // workaround for #2317 list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack(); droppablesLoop: for (i = 0; i < m.length; i++) { //No disabled and non-accepted if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) { continue; } // Filter out elements in the current dragged item for (j=0; j < list.length; j++) { if(list[j] === m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } } m[i].visible = m[i].element.css("display") !== "none"; if(!m[i].visible) { continue; } //Activate the droppable if used directly from draggables if(type === "mousedown") { m[i]._activate.call(m[i], event); } m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; } }, drop: function(draggable, event) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() { if(!this.options) { return; } if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) { dropped = this._drop.call(this, event) || dropped; } if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = true; this.isover = false; this._deactivate.call(this, event); } }); return dropped; }, dragStart: function( draggable, event ) { //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) { $.ui.ddmanager.prepareOffsets(draggable, event); } //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(this.options.disabled || this.greedyChild || !this.visible) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect(draggable, this, this.options.tolerance), c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null); if(!c) { return; } if (this.options.greedy) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents(":data(ui-droppable)").filter(function () { return $.data(this, "ui-droppable").options.scope === scope; }); if (parent.length) { parentInstance = $.data(parent[0], "ui-droppable"); parentInstance.greedyChild = (c === "isover"); } } // we just moved into a greedy child if (parentInstance && c === "isover") { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call(parentInstance, event); } this[c] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c === "isout") { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call(parentInstance, event); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; })(jQuery); (function( $, undefined ) { function num(v) { return parseInt(v, 10) || 0; } function isNumber(value) { return !isNaN(parseInt(value, 10)); } $.widget("ui.resizable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); //Overwrite the original this.element this.element = this.element.parent().data( "ui-resizable", this.element.data("ui-resizable") ); this.elementIsWrapper = true; //Move margins to the wrapper this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); // fix handlers offset this._proportionallyResize(); } this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); if(this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-"+handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); // Apply zIndex to all handles - see #7960 axis.css({ zIndex: o.zIndex }); //TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } //Insert into internal handles object and append to element this.handles[handle] = ".ui-resizable-"+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = $(this.handles[i], this.element).show(); } //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } //Axis, default = se that.axis = axis && axis[1] ? axis[1] : "se"; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; // bugfix for http://dev.jquery.com/ticket/1749 if ( (/absolute/).test( el.css("position") ) ) { el.css({ position: "absolute", top: el.css("top"), left: el.css("left") }); } else if (el.is(".ui-draggable")) { el.css({ position: "absolute", top: iniPos.top, left: iniPos.left }); } this._renderProxy(); curleft = num(this.helper.css("left")); curtop = num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, prevTop = this.position.top, prevLeft = this.position.left, prevWidth = this.size.width, prevHeight = this.size.height, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; if (!trigger) { return false; } // Calculate the attrs that will be change data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); // plugins callbacks need to be called first this._propagate("resize", event); if (this.position.top !== prevTop) { props.top = this.position.top + "px"; } if (this.position.left !== prevLeft) { props.left = this.position.left + "px"; } if (this.size.width !== prevWidth) { props.width = this.size.width + "px"; } if (this.size.height !== prevHeight) { props.height = this.size.height + "px"; } el.css(props); if (!this._helper && this._proportionallyResizeElements.length) { this._proportionallyResize(); } // Call the user callback if the element was resized if ( ! $.isEmptyObject(props) ) { this._trigger("resize", event, this.ui()); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { // We want to create an enclosing box whose aspect ration is the requested one // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (isNumber(data.left)) { this.position.left = data.left; } if (isNumber(data.top)) { this.position.top = data.top; } if (isNumber(data.height)) { this.size.height = data.height; } if (isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left +"px", top: this.elementOffset.top +"px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).data("ui-resizable"), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add("resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $(this).data("ui-resizable"), o = that.options, el = that.element, oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) { return; } that.containerElement = $(ce); if (/document/.test(oc) || oc === document) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else { element = $(ce); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ); height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event ) { var woset, hoset, isParent, isOffsetRelative, that = $(this).data("ui-resizable"), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement; if (ce[0] !== document && (/static/).test(ce.css("position"))) { cop = co; } if (cp.left < (that._helper ? co.left : 0)) { that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left)); if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } that.position.left = o.helper ? co.left : 0; } if (cp.top < (that._helper ? co.top : 0)) { that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top); if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left+that.position.left; that.offset.top = that.parentData.top+that.position.top; woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ); hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); isParent = that.containerElement.get(0) === that.element.parent().get(0); isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position")); if(isParent && isOffsetRelative) { woset -= that.parentData.left; } if (woset + that.size.width >= that.parentData.width) { that.size.width = that.parentData.width - woset; if (pRatio) { that.size.height = that.size.width / that.aspectRatio; } } if (hoset + that.size.height >= that.parentData.height) { that.size.height = that.parentData.height - hoset; if (pRatio) { that.size.width = that.size.height * that.aspectRatio; } } }, stop: function(){ var that = $(this).data("ui-resizable"), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $(that.helper), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if (that._helper && !o.animate && (/static/).test(ce.css("position"))) { $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).data("ui-resizable"), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).data("ui-resizable"), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).data("ui-resizable"), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).data("ui-resizable"); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).data("ui-resizable"); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).data("ui-resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); })(jQuery); (function( $, undefined ) { $.widget("ui.selectable", $.ui.mouse, { version: "1.10.3", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); })(jQuery); (function( $, undefined ) { /*jshint loopfunc: true */ function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } function isFloating(item) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); } $.widget("ui.sortable", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "sort", ready: false, options: { appendTo: "parent", axis: false, connectWith: false, containment: false, cursor: "auto", cursorAt: false, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: "> *", opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000, // callbacks activate: null, beforeStop: null, change: null, deactivate: null, out: null, over: null, receive: null, remove: null, sort: null, start: null, stop: null, update: null }, _create: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); //We're ready to go this.ready = true; }, _destroy: function() { this.element .removeClass("ui-sortable ui-sortable-disabled"); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _setOption: function(key, value){ if ( key === "disabled" ) { this.options[ key ] = value; this.widget().toggleClass( "ui-sortable-disabled", !!value ); } else { // Don't call widget base _setOption for disable as it adds ui-state-disabled class $.Widget.prototype._setOption.apply(this, arguments); } }, _mouseCapture: function(event, overrideHandle) { var currentItem = null, validHandle = false, that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type === "static") { return false; } //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items $(event.target).parents().each(function() { if($.data(this, that.widgetName + "-item") === that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + "-item") === that) { currentItem = $(event.target); } if(!currentItem) { return false; } if(this.options.handle && !overrideHandle) { $(this.options.handle, currentItem).find("*").addBack().each(function() { if(this === event.target) { validHandle = true; } }); if(!validHandle) { return false; } } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var i, body, o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] !== this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) { this._setContainment(); } if( o.cursor && o.cursor !== "auto" ) { // cursor option body = this.document.find( "body" ); // support: IE this.storedCursor = body.css( "cursor" ); body.css( "cursor", o.cursor ); this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) { this._storedOpacity = this.helper.css("opacity"); } this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) { this._storedZIndex = this.helper.css("zIndex"); } this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { this.overflowOffset = this.scrollParent.offset(); } //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) { this._cacheHelperProportions(); } //Post "activate" events to possible containers if( !noActivation ) { for ( i = this.containers.length - 1; i >= 0; i-- ) { this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); } } //Prepare possible droppables if($.ui.ddmanager) { $.ui.ddmanager.current = this; } if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { var i, item, itemElement, intersection, o = this.options, scrolled = false; //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; } if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper position if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } //Rearrange for (i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection item = this.items[i]; itemElement = item.item[0]; intersection = this._intersectsWithPointer(item); if (!intersection) { continue; } // Only put the placeholder inside the current Container, skip all // items form other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this moving items in "sub-sortables" can cause the placeholder to jitter // beetween the outer and inner container. if (item.instance !== this.currentContainer) { continue; } // cannot intersect with itself // no useless actions that have been done before // no action if the item moved is the parent of the item checked if (itemElement !== this.currentItem[0] && this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && !$.contains(this.placeholder[0], itemElement) && (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) ) { this.direction = intersection === 1 ? "down" : "up"; if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } //Call callbacks this._trigger("sort", event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) { return; } //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) { $.ui.ddmanager.drop(this, event); } if(this.options.revert) { var that = this, cur = this.placeholder.offset(), axis = this.options.axis, animation = {}; if ( !axis || axis === "x" ) { animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); } if ( !axis || axis === "y" ) { animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); } this.reverting = true; $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { if(this.dragging) { this._mouseUp({ target: null }); if(this.options.helper === "original") { this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) { this.placeholder[0].parentNode.removeChild(this.placeholder[0]); } if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { this.helper.remove(); } $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected), str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); if (res) { str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); } }); if(!str.length && o.key) { str.push(o.key + "="); } return str.join("&"); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected), ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height, l = item.left, r = l + item.width, t = item.top, b = t + item.height, dyClick = this.offset.click.top, dxClick = this.offset.click.left, isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), isOverElement = isOverElementHeight && isOverElementWidth; if ( this.options.tolerance === "pointer" || this.options.forcePointerForContainers || (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) && // Right Half x2 - (this.helperProportions.width / 2) < r && // Left Half t < y1 + (this.helperProportions.height / 2) && // Bottom Half y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) { return false; } return this.floating ? ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta !== 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta !== 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var i, j, cur, inst, items = [], queries = [], connectWith = this._connectWith(); if(connectWith && connected) { for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for ( j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); } } } } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each(function() { items.push(this); }); } return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] === item.item[0]) { return false; } } return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var i, j, cur, inst, targetData, _queries, item, queriesLength, items = this.items, queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for (j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } } } } for (i = queries.length - 1; i >= 0; i--) { targetData = queries[i][1]; _queries = queries[i][0]; for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { item = $(_queries[j]); item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); } } }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } var i, item, t, p; for (i = this.items.length - 1; i >= 0; i--){ item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { continue; } t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } p = t.offset(); item.left = p.left; item.top = p.top; } if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (i = this.containers.length - 1; i >= 0; i--){ p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); } } return this; }, _createPlaceholder: function(that) { that = that || this; var className, o = that.options; if(!o.placeholder || o.placeholder.constructor === String) { className = o.placeholder; o.placeholder = { element: function() { var nodeName = that.currentItem[0].nodeName.toLowerCase(), element = $( "<" + nodeName + ">", that.document[0] ) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper"); if ( nodeName === "tr" ) { that.currentItem.children().each(function() { $( "<td>&#160;</td>", that.document[0] ) .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) .appendTo( element ); }); } else if ( nodeName === "img" ) { element.attr( "src", that.currentItem.attr( "src" ) ); } if ( !className ) { element.css( "visibility", "hidden" ); } return element; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) { return; } //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating, innermostContainer = null, innermostIndex = null; // get innermost container that intersects with item for (i = this.containers.length - 1; i >= 0; i--) { // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) { continue; } if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { continue; } innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) { return; } // move the item into the container if it's not there already if(this.containers.length === 1) { if (!this.containers[innermostIndex].containerCache.over) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } } else { //When entering a new container, we will find the item with the least distance and append our item near it dist = 10000; itemWithLeastDistance = null; floating = innermostContainer.floating || isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; base = this.positionAbs[posProperty] + this.offset.click[posProperty]; for (j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { continue; } if(this.items[j].item[0] === this.currentItem[0]) { continue; } if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ nearBottom = true; cur += this.items[j][sizeProperty]; } if(Math.abs(cur - base) < dist) { dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; this.direction = nearBottom ? "up": "down"; } } //Check if dropOnEmpty is enabled if(!itemWithLeastDistance && !this.options.dropOnEmpty) { return; } if(this.currentContainer === this.containers[innermostIndex]) { return; } itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); this.currentContainer = this.containers[innermostIndex]; //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); //Add the helper to the DOM if that didn't happen already if(!helper.parents("body").length) { $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); } if(helper[0] === this.currentItem[0]) { this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; } if(!helper[0].style.width || o.forceHelperSize) { helper.width(this.currentItem.width()); } if(!helper[0].style.height || o.forceHelperSize) { helper.height(this.currentItem.height()); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } // This needs to be actually done for all browsers, since pageX/pageY includes this information // with an ugly IE fix if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var ce, co, over, o = this.options; if(o.containment === "parent") { o.containment = this.helper[0].parentNode; } if(o.containment === "document" || o.containment === "window") { this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; } if(!(/^(document|window|parent)$/).test(o.containment)) { ce = $(o.containment)[0]; co = $(o.containment).offset(); over = ($(ce).css("overflow") !== "hidden"); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var top, left, o = this.options, pageX = event.pageX, pageY = event.pageY, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) { pageX = this.containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < this.containment[1]) { pageY = this.containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > this.containment[2]) { pageX = this.containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > this.containment[3]) { pageY = this.containment[3] + this.offset.click.top; } } if(o.grid) { top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter === this.counter) { this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove } }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var i, delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) { this.placeholder.before(this.currentItem); } this._noFinalSort = null; if(this.helper[0] === this.currentItem[0]) { for(i in this._storedCSS) { if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { this._storedCSS[i] = ""; } } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); } if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed } // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers for (i = this.containers.length - 1; i >= 0; i--){ if(!noPropagation) { delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); } if(this.containers[i].containerCache.over) { delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if ( this.storedCursor ) { this.document.find( "body" ).css( "cursor", this.storedCursor ); this.storedStylesheet.remove(); } if(this._storedOpacity) { this.helper.css("opacity", this._storedOpacity); } if(this._storedZIndex) { this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); } this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return false; } if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] !== this.currentItem[0]) { this.helper.remove(); } this.helper = null; if(!noPropagation) { for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); })(jQuery); (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.10.3" } }); var PROP_NAME = "datepicker", instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, PROP_NAME, inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst); } extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], PROP_NAME, inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a").mouseover(); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, PROP_NAME))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), digits = new RegExp("^\\d{1," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate(selector, "mouseover", function(){ if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } }); } /* jQuery extend now ignores nulls! */ function extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.10.3"; })(jQuery); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { this.range = $([]); } }, _setupEvents: function() { var elements = this.handles.add( this.range ).filter( "a" ); this._off( elements ); this._on( elements, this._handleEvents ); this._hoverable( elements ); this._focusable( elements ); }, _destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length-1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { /*jshint maxcomplexity:25*/ var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, click: function( event ) { event.preventDefault(); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); }(jQuery));
agpl-3.0
firstmoversadvantage/sugarcrm
tests/include/JSONTest.php
5417
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ require_once 'include/JSON.php'; class JSONTest extends Sugar_PHPUnit_Framework_TestCase { public function tearDown() { unset($_SESSION['asychronous_key']); } public function testCanEncodeBasicArray() { $array = array('foo' => 'bar', 'bar' => 'foo'); $this->assertEquals( '{"foo":"bar","bar":"foo"}', JSON::encode($array) ); } public function testCanEncodeBasicObjects() { $obj = new stdClass(); $obj->foo = 'bar'; $obj->bar = 'foo'; $this->assertEquals( '{"foo":"bar","bar":"foo"}', JSON::encode($obj) ); } public function testCanEncodeMultibyteData() { $array = array('foo' => '契約', 'bar' => '契約'); $this->assertEquals( '{"foo":"\u5951\u7d04","bar":"\u5951\u7d04"}', JSON::encode($array) ); } public function testCanDecodeObjectIntoArray() { $array = array('foo' => 'bar', 'bar' => 'foo'); $this->assertEquals( JSON::decode('{"foo":"bar","bar":"foo"}'), $array ); } public function testCanDecodeMultibyteData() { $array = array('foo' => '契約', 'bar' => '契約'); $this->assertEquals( JSON::decode('{"foo":"\u5951\u7d04","bar":"\u5951\u7d04"}'), $array ); } public function testEncodeRealWorks() { $array = array('foo' => 'bar', 'bar' => 'foo'); $this->assertEquals( '{"foo":"bar","bar":"foo"}', JSON::encodeReal($array) ); } public function testDecodeRealWorks() { $array = array('foo' => 'bar', 'bar' => 'foo'); $this->assertEquals( JSON::decodeReal('{"foo":"bar","bar":"foo"}'), $array ); } public function testCanDecodeHomefinder(){ $response = '{"data":{"meta":{"currentPage":1,"totalMatched":1,"totalPages":1,"executionTime":0.025315999984741},"affiliates":[{"name":"Los Angeles Times","profileName":"latimes","parentCompany":"Tribune Company","isActive":true,"hasEcommerceEnabled":true,"profileNameLong":"latimes","homePageUrl":"http:\/\/www.latimes.com\/classified\/realestate\/","createDateTime":"2008-07-25T00:00:00-05:00","updateDateTime":"2011-02-16T00:00:00-06:00","id":137}]},"status":{"code":200,"errorStack":null}}'; $json = new JSON(); $decode = $json->decode($response); $this->assertNotEmpty($decode['data']['affiliates'][0]['profileName'], "Did not decode correctly"); } public function testCanDecodeHomefinderAsObject(){ $response = '{"data":{"meta":{"currentPage":1,"totalMatched":1,"totalPages":1,"executionTime":0.025315999984741},"affiliates":[{"name":"Los Angeles Times","profileName":"latimes","parentCompany":"Tribune Company","isActive":true,"hasEcommerceEnabled":true,"profileNameLong":"latimes","homePageUrl":"http:\/\/www.latimes.com\/classified\/realestate\/","createDateTime":"2008-07-25T00:00:00-05:00","updateDateTime":"2011-02-16T00:00:00-06:00","id":137}]},"status":{"code":200,"errorStack":null}}'; $json = new JSON(); $decode = $json->decode($response, false, false); $this->assertNotEmpty($decode->data->affiliates[0]->profileName, "Did not decode correctly"); } }
agpl-3.0
jesramirez/odoo
addons/account/report/account_invoice_report.py
13019
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import tools import openerp.addons.decimal_precision as dp from openerp.osv import fields,osv class account_invoice_report(osv.osv): _name = "account.invoice.report" _description = "Invoices Statistics" _auto = False _rec_name = 'date' def _compute_amounts_in_user_currency(self, cr, uid, ids, field_names, args, context=None): """Compute the amounts in the currency of the user """ if context is None: context={} currency_obj = self.pool.get('res.currency') currency_rate_obj = self.pool.get('res.currency.rate') user_currency_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id currency_rate_id = currency_rate_obj.search(cr, uid, [('rate', '=', 1)], limit=1, context=context)[0] base_currency_id = currency_rate_obj.browse(cr, uid, currency_rate_id, context=context).currency_id.id res = {} ctx = context.copy() for item in self.browse(cr, uid, ids, context=context): ctx['date'] = item.date price_total = currency_obj.compute(cr, uid, base_currency_id, user_currency_id, item.price_total, context=ctx) price_average = currency_obj.compute(cr, uid, base_currency_id, user_currency_id, item.price_average, context=ctx) residual = currency_obj.compute(cr, uid, base_currency_id, user_currency_id, item.residual, context=ctx) res[item.id] = { 'user_currency_price_total': price_total, 'user_currency_price_average': price_average, 'user_currency_residual': residual, } return res _columns = { 'date': fields.date('Date', readonly=True), 'product_id': fields.many2one('product.product', 'Product', readonly=True), 'product_qty':fields.float('Product Quantity', readonly=True), 'uom_name': fields.char('Reference Unit of Measure', size=128, readonly=True), 'payment_term': fields.many2one('account.payment.term', 'Payment Term', readonly=True), 'period_id': fields.many2one('account.period', 'Force Period', domain=[('state','<>','done')], readonly=True), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position', readonly=True), 'currency_id': fields.many2one('res.currency', 'Currency', readonly=True), 'categ_id': fields.many2one('product.category','Category of Product', readonly=True), 'journal_id': fields.many2one('account.journal', 'Journal', readonly=True), 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True), 'commercial_partner_id': fields.many2one('res.partner', 'Partner Company', help="Commercial Entity"), 'company_id': fields.many2one('res.company', 'Company', readonly=True), 'user_id': fields.many2one('res.users', 'Salesperson', readonly=True), 'price_total': fields.float('Total Without Tax', readonly=True), 'user_currency_price_total': fields.function(_compute_amounts_in_user_currency, string="Total Without Tax", type='float', digits_compute=dp.get_precision('Account'), multi="_compute_amounts"), 'price_average': fields.float('Average Price', readonly=True, group_operator="avg"), 'user_currency_price_average': fields.function(_compute_amounts_in_user_currency, string="Average Price", type='float', digits_compute=dp.get_precision('Account'), multi="_compute_amounts"), 'currency_rate': fields.float('Currency Rate', readonly=True), 'nbr': fields.integer('# of Invoices', readonly=True), # TDE FIXME master: rename into nbr_lines 'type': fields.selection([ ('out_invoice','Customer Invoice'), ('in_invoice','Supplier Invoice'), ('out_refund','Customer Refund'), ('in_refund','Supplier Refund'), ],'Type', readonly=True), 'state': fields.selection([ ('draft','Draft'), ('proforma','Pro-forma'), ('proforma2','Pro-forma'), ('open','Open'), ('paid','Done'), ('cancel','Cancelled') ], 'Invoice Status', readonly=True), 'date_due': fields.date('Due Date', readonly=True), 'account_id': fields.many2one('account.account', 'Account',readonly=True), 'account_line_id': fields.many2one('account.account', 'Account Line',readonly=True), 'partner_bank_id': fields.many2one('res.partner.bank', 'Bank Account',readonly=True), 'residual': fields.float('Total Residual', readonly=True), 'user_currency_residual': fields.function(_compute_amounts_in_user_currency, string="Total Residual", type='float', digits_compute=dp.get_precision('Account'), multi="_compute_amounts"), 'country_id': fields.many2one('res.country', 'Country of the Partner Company'), } _order = 'date desc' _depends = { 'account.invoice': [ 'account_id', 'amount_total', 'commercial_partner_id', 'company_id', 'currency_id', 'date_due', 'date_invoice', 'fiscal_position', 'journal_id', 'partner_bank_id', 'partner_id', 'payment_term', 'period_id', 'residual', 'state', 'type', 'user_id', ], 'account.invoice.line': [ 'account_id', 'invoice_id', 'price_subtotal', 'product_id', 'quantity', 'uos_id', ], 'product.product': ['product_tmpl_id'], 'product.template': ['categ_id'], 'product.uom': ['category_id', 'factor', 'name', 'uom_type'], 'res.currency.rate': ['currency_id', 'name'], 'res.partner': ['country_id'], } def _select(self): select_str = """ SELECT sub.id, sub.date, sub.product_id, sub.partner_id, sub.country_id, sub.payment_term, sub.period_id, sub.uom_name, sub.currency_id, sub.journal_id, sub.fiscal_position, sub.user_id, sub.company_id, sub.nbr, sub.type, sub.state, sub.categ_id, sub.date_due, sub.account_id, sub.account_line_id, sub.partner_bank_id, sub.product_qty, sub.price_total / cr.rate as price_total, sub.price_average /cr.rate as price_average, cr.rate as currency_rate, sub.residual / cr.rate as residual, sub.commercial_partner_id as commercial_partner_id """ return select_str def _sub_select(self): select_str = """ SELECT min(ail.id) AS id, ai.date_invoice AS date, ail.product_id, ai.partner_id, ai.payment_term, ai.period_id, CASE WHEN u.uom_type::text <> 'reference'::text THEN ( SELECT product_uom.name FROM product_uom WHERE product_uom.uom_type::text = 'reference'::text AND product_uom.active AND product_uom.category_id = u.category_id LIMIT 1) ELSE u.name END AS uom_name, ai.currency_id, ai.journal_id, ai.fiscal_position, ai.user_id, ai.company_id, count(ail.*) AS nbr, ai.type, ai.state, pt.categ_id, ai.date_due, ai.account_id, ail.account_id AS account_line_id, ai.partner_bank_id, SUM(CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN (- ail.quantity) / u.factor * u2.factor ELSE ail.quantity / u.factor * u2.factor END) AS product_qty, SUM(CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN - ail.price_subtotal ELSE ail.price_subtotal END) AS price_total, CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN SUM(- ail.price_subtotal) ELSE SUM(ail.price_subtotal) END / CASE WHEN SUM(ail.quantity / u.factor) <> 0::numeric THEN CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN SUM((- ail.quantity) / u.factor) ELSE SUM(ail.quantity / u.factor) END ELSE 1::numeric END AS price_average, CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN - ai.residual ELSE ai.residual END / CASE WHEN (( SELECT count(l.id) AS count FROM account_invoice_line l LEFT JOIN account_invoice a ON a.id = l.invoice_id WHERE a.id = ai.id)) <> 0 THEN ( SELECT count(l.id) AS count FROM account_invoice_line l LEFT JOIN account_invoice a ON a.id = l.invoice_id WHERE a.id = ai.id) ELSE 1::bigint END::numeric AS residual, ai.commercial_partner_id as commercial_partner_id, partner.country_id """ return select_str def _from(self): from_str = """ FROM account_invoice_line ail JOIN account_invoice ai ON ai.id = ail.invoice_id JOIN res_partner partner ON ai.commercial_partner_id = partner.id LEFT JOIN product_product pr ON pr.id = ail.product_id left JOIN product_template pt ON pt.id = pr.product_tmpl_id LEFT JOIN product_uom u ON u.id = ail.uos_id LEFT JOIN product_uom u2 ON u.id = pt.uom_id """ return from_str def _group_by(self): group_by_str = """ GROUP BY ail.product_id, ai.date_invoice, ai.id, ai.partner_id, ai.payment_term, ai.period_id, u.name, ai.currency_id, ai.journal_id, ai.fiscal_position, ai.user_id, ai.company_id, ai.type, ai.state, pt.categ_id, ai.date_due, ai.account_id, ail.account_id, ai.partner_bank_id, ai.residual, ai.amount_total, u.uom_type, u.category_id, ai.commercial_partner_id, partner.country_id """ return group_by_str def init(self, cr): # self._table = account_invoice_report tools.drop_view_if_exists(cr, self._table) cr.execute("""CREATE or REPLACE VIEW %s as ( %s FROM ( %s %s %s ) AS sub JOIN res_currency_rate cr ON (cr.currency_id = sub.currency_id) WHERE cr.id IN (SELECT id FROM res_currency_rate cr2 WHERE (cr2.currency_id = sub.currency_id) AND ((sub.date IS NOT NULL AND cr2.name <= sub.date) OR (sub.date IS NULL AND cr2.name <= NOW())) ORDER BY name DESC LIMIT 1) )""" % ( self._table, self._select(), self._sub_select(), self._from(), self._group_by())) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
richhl/kalturaCE
package/app/app/plugins/metadata/lib/KalturaMetadataProfileFieldStatus.php
211
<?php /** * @package plugins.metadata * @subpackage api.enum */ class KalturaMetadataProfileFieldStatus extends KalturaEnum { const ACTIVE = 1; const DEPRECATED = 2; const NONE_SEARCHABLE = 3; }
agpl-3.0
colearn-co/Colearn
app/controllers/api/v1/push_notifications_controller.rb
77
class Api::V1::PushNotificationsController < PushNotificationsController end
agpl-3.0
lepo-project/lepo
app/models/sticky_star.rb
528
# == Schema Information # # Table name: sticky_stars # # id :integer not null, primary key # manager_id :integer # sticky_id :integer # stared :boolean default(TRUE) # created_at :datetime not null # updated_at :datetime not null # class StickyStar < ApplicationRecord belongs_to :manager, class_name: 'User' belongs_to :sticky validates :manager_id, presence: true validates :manager_id, uniqueness: { scope: :sticky_id } validates :sticky_id, presence: true end
agpl-3.0
panterch/future_kids
db/migrate/20180531173049_add_comment_bcc_e_mail_to_site.rb
130
class AddCommentBccEMailToSite < ActiveRecord::Migration[5.2] def change add_column :sites, :comment_bcc, :string end end
agpl-3.0
anneline/Bika-LIMS
bika/lims/browser/js/bika.lims.analysisrequest.js
20790
/** * Controller class for Analysis Request View/s */ function AnalysisRequestView() { var that = this; /** * Entry-point method for AnalysisRequestView */ that.load = function() { $("#workflow-transition-prepublish").click(workflow_transition_prepublish); $("#workflow-transition-publish").click(workflow_transition_publish); $("#workflow-transition-republish").click(workflow_transition_republish); $("#workflow-transition-receive").click(workflow_transition_receive); $("#workflow-transition-retract_ar").click(workflow_transition_retract_ar); } function workflow_transition_receive(event) { event.preventDefault(); var requestdata = {}; requestdata.workflow_action = "receive"; var requeststring = $.param(requestdata); var href = window.location.href.split("?")[0] .replace("/base_view", "") .replace("/manage_results", "") .replace("/workflow_action", "") .replace("/view", "") + "/workflow_action?" + requeststring; window.location.href = href; } function workflow_transition_prepublish(event){ event.preventDefault(); var requestdata = {}; var spec_uid = $("#PublicationSpecification_uid").val(); requestdata.PublicationSpecification = spec_uid; requestdata.workflow_action = "prepublish"; var requeststring = $.param(requestdata); var href = window.location.href.split("?")[0] .replace("/base_view", "") .replace("/manage_results", "") .replace("/workflow_action", "") .replace("/view", "") + "/workflow_action?" + requeststring; window.location.href = href; } function workflow_transition_publish(event){ event.preventDefault(); var requestdata = {}; var spec_uid = $("#PublicationSpecification_uid").val(); requestdata.PublicationSpecification = spec_uid; requestdata.workflow_action = "publish"; var requeststring = $.param(requestdata); var href = window.location.href.split("?")[0] .replace("/base_view", "") .replace("/manage_results", "") .replace("/workflow_action", "") .replace("/view", "") + "/workflow_action?" + requeststring; window.location.href = href; } function workflow_transition_republish(event){ event.preventDefault(); var requestdata = {}; var spec_uid = $("#PublicationSpecification_uid").val(); requestdata.PublicationSpecification = spec_uid; requestdata.workflow_action = "republish"; var requeststring = $.param(requestdata); var href = window.location.href.split("?")[0] .replace("/base_view", "") .replace("/manage_results", "") .replace("/workflow_action", "") .replace("/view", "") + "/workflow_action?" + requeststring; window.location.href = href; } function workflow_transition_retract_ar(event) { event.preventDefault(); var requestdata = {}; requestdata.workflow_action = "retract_ar"; var requeststring = $.param(requestdata); var href = window.location.href.split("?")[0] .replace("/base_view", "") .replace("/manage_results", "") .replace("/workflow_action", "") .replace("/view", "") + "/workflow_action?" + requeststring; window.location.href = href; } } /** * Controller class for Analysis Request View View */ function AnalysisRequestViewView() { var that = this; /** * Entry-point method for AnalysisRequestView */ that.load = function() { if (document.location.href.search('/clients/') >= 0 && $("#archetypes-fieldname-SamplePoint #SamplePoint").length > 0) { var cid = document.location.href.split("clients")[1].split("/")[1]; $.ajax({ url: window.portal_url + "/clients/" + cid + "/getClientInfo", type: 'POST', data: {'_authenticator': $('input[name="_authenticator"]').val()}, dataType: "json", success: function(data, textStatus, $XHR){ if (data['ClientUID'] != '') { var spelement = $("#archetypes-fieldname-SamplePoint #SamplePoint"); var base_query=$.parseJSON($(spelement).attr("base_query")); base_query["getClientUID"] = data['ClientUID']; $(spelement).attr("base_query", $.toJSON(base_query)); var options = $.parseJSON($(spelement).attr("combogrid_options")); options.url = window.location.href.split("/ar")[0] + "/" + options.url; options.url = options.url + "?_authenticator=" + $("input[name='_authenticator']").val(); options.url = options.url + "&catalog_name=" + $(spelement).attr("catalog_name"); options.url = options.url + "&base_query=" + $.toJSON(base_query); options.url = options.url + "&search_query=" + $(spelement).attr("search_query"); options.url = options.url + "&colModel=" + $.toJSON( $.parseJSON($(spelement).attr("combogrid_options")).colModel); options.url = options.url + "&search_fields=" + $.toJSON($.parseJSON($(spelement).attr("combogrid_options")).search_fields); options.url = options.url + "&discard_empty=" + $.toJSON($.parseJSON($(spelement).attr("combogrid_options")).discard_empty); options.force_all="false"; $(spelement).combogrid(options); $(spelement).addClass("has_combogrid_widget"); $(spelement).attr("search_query", "{}"); } } }); } } } /** * Controller class for Analysis Request Manage Results view */ function AnalysisRequestManageResultsView() { var that = this; /** * Entry-point method for AnalysisRequestManageResultsView */ that.load = function() { // Set the analyst automatically when selected in the picklist $('.portaltype-analysisrequest .bika-listing-table td.Analyst select').change(function() { var analyst = $(this).val(); var key = $(this).closest('tr').attr('keyword'); var obj_path = window.location.href.replace(window.portal_url, ''); var obj_path_split = obj_path.split('/'); if (obj_path_split.length > 4) { obj_path_split[obj_path_split.length-1] = key; } else { obj_path_split.push(key); } obj_path = obj_path_split.join('/'); $.ajax({ type: "POST", url: window.portal_url+"/@@API/update", data: {"obj_path": obj_path, "Analyst": analyst} }); }); } } /** * Controller class for Analysis Request Analyses view */ function AnalysisRequestAnalysesView() { var that = this; /** * Entry-point method for AnalysisRequestAnalysesView */ that.load = function() { $("[name^='min\\.'], [name^='max\\.'], [name^='error\\.']").live("change", function(){ validate_spec_field_entry(this); }); //////////////////////////////////////// // disable checkboxes for eg verified analyses. $.each($("[name='uids:list']"), function(x,cb){ var service_uid = $(cb).val(); var row_data = $.parseJSON($("#"+service_uid+"_row_data").val()); if (row_data.disabled === true){ // disabled fields must be shadowed by hidden fields, // or they don't appear in the submitted form. $(cb).prop("disabled", true); var cbname = $(cb).attr("name"); var cbid = $(cb).attr("id"); $(cb).removeAttr("name").removeAttr("id"); $(cb).after("<input type='hidden' name='"+cbname+"' value='"+service_uid+"' id='"+cbid+"'/>"); var el = $("[name='Price."+service_uid+":records']"); var elname = $(el).attr("name"); var elval = $(el).val(); $(el).after("<input type='hidden' name='"+elname+"' value='"+elval+"'/>"); $(el).prop("disabled", true); el = $("[name='Partition."+service_uid+":records']"); elname = $(el).attr("name"); elval = $(el).val(); $(el).after("<input type='hidden' name='"+elname+"' value='"+elval+"'/>"); $(el).prop("disabled", true); var specfields = ["min", "max", "error"]; for(var i in specfields) { var element = $("[name='"+specfields[i]+"."+service_uid+":records']"); var new_element = "" + "<input type='hidden' field='"+specfields[i]+"' value='"+element.val()+"' " + "name='"+specfields[i]+"."+service_uid+":records' uid='"+service_uid+"'>"; $(element).replaceWith(new_element); } } }); //////////////////////////////////////// // checkboxes in services list $("[name='uids:list']").live("click", function(){ calcdependencies([this]); var service_uid = $(this).val(); if ($(this).prop("checked")){ check_service(service_uid); } else { uncheck_service(service_uid); } }); } function validate_spec_field_entry(element) { var uid = $(element).attr("uid"); // no spec selector here yet! // $("[name^='ar\\."+sb_col+"\\.Specification']").val(""); // $("[name^='ar\\."+sb_col+"\\.Specification_uid']").val(""); var min_element = $("[name='min\\."+uid+"\\:records']"); var max_element = $("[name='max\\."+uid+"\\:records']"); var error_element = $("[name='error\\."+uid+"\\:records']"); var min = parseFloat($(min_element).val(), 10); var max = parseFloat($(max_element).val(), 10); var error = parseFloat($(error_element).val(), 10); if($(element).attr("name") == $(min_element).attr("name")){ if(isNaN(min)) { $(min_element).val(""); } else if ((!isNaN(max)) && min > max) { $(max_element).val(""); } } else if($(element).attr("name") == $(max_element).attr("name")){ if(isNaN(max)) { $(max_element).val(""); } else if ((!isNaN(min)) && max < min) { $(min_element).val(""); } } else if($(element).attr("name") == $(error_element).attr("name")){ if(isNaN(error) || error < 0 || error > 100){ $(error_element).val(""); } } } function check_service(service_uid){ var new_element, element; // Add partition dropdown element = $("[name='Partition."+service_uid+":records']"); new_element = "" + "<select class='listing_select_entry' "+ "name='Partition."+service_uid+":records' "+ "field='Partition' uid='"+service_uid+"' "+ "style='font-size: 100%'>"; $.each($("td.PartTitle"), function(i,v){ var partid = $($(v).children()[1]).text(); new_element = new_element + "<option value='"+partid+"'>"+partid+"</option>"; }); new_element = new_element + "</select>"; $(element).replaceWith(new_element); // Add price field var logged_in_client = $("input[name='logged_in_client']").val(); if (logged_in_client != "1") { element = $("[name='Price."+service_uid+":records']"); new_element = "" + "<input class='listing_string_entry numeric' "+ "name='Price."+service_uid+":records' "+ "field='Price' type='text' uid='"+service_uid+"' "+ "autocomplete='off' style='font-size: 100%' size='5' "+ "value='"+$(element).val()+"'>"; $($(element).siblings()[1]).remove(); $(element).replaceWith(new_element); } // spec fields var specfields = ["min", "max", "error"]; for(var i in specfields) { element = $("[name='"+specfields[i]+"."+service_uid+":records']"); new_element = "" + "<input class='listing_string_entry numeric' type='text' size='5' " + "field='"+specfields[i]+"' value='"+$(element).val()+"' " + "name='"+specfields[i]+"."+service_uid+":records' " + "uid='"+service_uid+"' autocomplete='off' style='font-size: 100%'>"; $(element).replaceWith(new_element); } } function uncheck_service(service_uid){ var new_element, element; element = $("[name='Partition."+service_uid+":records']"); new_element = "" + "<input type='hidden' name='Partition."+service_uid+":records' value=''/>"; $(element).replaceWith(new_element); var logged_in_client = $("input[name='logged_in_client']").val(); if (logged_in_client != "1") { element = $("[name='Price."+service_uid+":records']"); $($(element).siblings()[0]) .after("<span class='state-active state-active '>"+$(element).val()+"</span>"); new_element = "" + "<input type='hidden' name='Price."+service_uid+":records' value='"+$(element).val()+"'/>"; $(element).replaceWith(new_element); } var specfields = ["min", "max", "error"]; for(var i in specfields) { element = $("[name='"+specfields[i]+"."+service_uid+":records']"); new_element = "" + "<input type='hidden' field='"+specfields[i]+"' value='"+element.val()+"' " + "name='"+specfields[i]+"."+service_uid+":records' uid='"+service_uid+"'>"; $(element).replaceWith(new_element); } } function add_Yes(dlg, element, dep_services){ for(var i = 0; i<dep_services.length; i++){ var service_uid = dep_services[i].Service_uid; if(! $("#list_cb_"+service_uid).prop("checked") ){ check_service(service_uid); $("#list_cb_"+service_uid).prop("checked",true); } } $(dlg).dialog("close"); $("#messagebox").remove(); } function add_No(dlg, element){ if($(element).prop("checked") ){ uncheck_service($(element).attr("value")); $(element).prop("checked",false); } $(dlg).dialog("close"); $("#messagebox").remove(); } function calcdependencies(elements, auto_yes) { /*jshint validthis:true */ auto_yes = auto_yes || false; jarn.i18n.loadCatalog('bika'); var _ = window.jarn.i18n.MessageFactory("bika"); var dep; var i, cb; var lims = window.bika.lims; for(var elements_i = 0; elements_i < elements.length; elements_i++){ var dep_services = []; // actionable services var dep_titles = []; var element = elements[elements_i]; var service_uid = $(element).attr("value"); // selecting a service; discover dependencies if ($(element).prop("checked")){ var Dependencies = lims.AnalysisService.Dependencies(service_uid); for(i = 0; i<Dependencies.length; i++) { dep = Dependencies[i]; if ($("#list_cb_"+dep.Service_uid).prop("checked") ){ continue; // skip if checked already } dep_services.push(dep); dep_titles.push(dep.Service); } if (dep_services.length > 0) { if (auto_yes) { add_Yes(this, element, dep_services); } else { var html = "<div id='messagebox' style='display:none' title='" + _("Service dependencies") + "'>"; html = html + _("<p>${service} requires the following services to be selected:</p>"+ "<br/><p>${deps}</p><br/><p>Do you want to apply these selections now?</p>", { service: $(element).attr("title"), deps: dep_titles.join("<br/>") }); html = html + "</div>"; $("body").append(html); $("#messagebox").dialog({ width:450, resizable:false, closeOnEscape: false, buttons:{ yes: function(){ add_Yes(this, element, dep_services); }, no: function(){ add_No(this, element); } } }); } } } // unselecting a service; discover back dependencies else { var Dependants = lims.AnalysisService.Dependants(service_uid); for (i=0; i<Dependants.length; i++){ dep = Dependants[i]; cb = $("#list_cb_" + dep.Service_uid); if (cb.prop("checked")){ dep_titles.push(dep.Service); dep_services.push(dep); } } if(dep_services.length > 0){ if (auto_yes) { for(i=0; i<dep_services.length; i+=1) { dep = dep_services[i]; service_uid = dep.Service_uid; cb = $("#list_cb_" + dep.Service_uid); uncheck_service(dep.Service_uid); $(cb).prop("checked", false); } } else { $("body").append( "<div id='messagebox' style='display:none' title='" + _("Service dependencies") + "'>"+ _("<p>The following services depend on ${service}, and will be unselected if you continue:</p><br/><p>${deps}</p><br/><p>Do you want to remove these selections now?</p>", {service:$(element).attr("title"), deps: dep_titles.join("<br/>")})+"</div>"); $("#messagebox").dialog({ width:450, resizable:false, closeOnEscape: false, buttons:{ yes: function(){ for(i=0; i<dep_services.length; i+=1) { dep = dep_services[i]; service_uid = dep.Service_uid; cb = $("#list_cb_" + dep.Service_uid); $(cb).prop("checked", false); uncheck_service(dep.Service_uid); } $(this).dialog("close"); $("#messagebox").remove(); }, no:function(){ service_uid = $(element).attr("value"); check_service(service_uid); $(element).prop("checked", true); $("#messagebox").remove(); $(this).dialog("close"); } } }); } } } } } }
agpl-3.0
rotofly/odoo
addons/account_financial_report_webkit/__openerp__.py
8480
# -*- encoding: utf-8 -*- ############################################################################## # # Authors: Nicolas Bessi, Guewen Baconnier # Copyright Camptocamp SA 2011 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Financial Reports - Webkit', 'description': """ Financial Reports - Webkit ========================== This module adds or replaces the following standard OpenERP financial reports: - General ledger - Trial Balance (simple or comparative view) - Partner ledger - Partner balance - Open invoices report - Aged Partner Balance Main improvements per report: ----------------------------- The General ledger: details of all entries posted in your books sorted by account. * Filter by account is available in the wizard (no need to go to the Chart of Accounts to do this anymore) or by View account (the report will display all regular children accounts) i.e. you can select all P&L accounts. * The report only prints accounts with moves OR with a non null balance. No more endless report with empty accounts (field: display account is hidden) * initial balance computation on the fly if no open entry posted * Thanks to a new checkbox in the account form, you will have the possibility to centralize any account you like. This means you do not want to see all entries posted under the account ‘VAT on sales’; you will only see aggregated amounts by periods. * Counterpart account is displayed for each transaction (3 accounts max.) to ease searching. * Better ergonomy on the wizard: important information is displayed in the top part, filters are in the middle, and options are in the bottom or on a separate tab. There is more specific filtering on separate tabs. No more unique wizard layout for all financial reports (we have removed the journal tab for the GL report) * improved report style The partner ledger: details of entries relative to payable & receivable accounts posted in your books sorted by account and partner. * Filter by partner now available * Now you can see Accounts then Partner with subtotals for each account allowing you to check you data with trial balance and partner balance for instance. Accounts are ordered in the same way as in the Chart of account * Period have been added (date only is not filled in since date can be outside period) * Reconciliation code added * Subtotal by account * Alphabetical sorting (same as in partner balance) Open invoice report : other version of the partner ledger showing unreconciled / partially reconciled entries. * Possibility to print unreconciled transactions only at any date in the past (thanks to the new field: `last_rec_date` which computes the last move line reconciliation date). No more pain to get open invoices at the last closing date. * no initial balance computed because the report shows open invoices from previous years. The Trial balance: list of accounts with balances * You can either see the columns: initial balance, debit, credit, end balance or compare balances over 4 periods of your choice * You can select the "opening" filter to get the opening trial balance only * If you create an extra virtual chart (using consolidated account) of accounts for your P&L and your balance sheet, you can print your statutory accounts (with comparison over years for instance) * If you compare 2 periods, you will get the differences in values and in percent The Partner balance: list of account with balances * Subtotal by account and partner * Alphabetical sorting (same as in partner balance) Aged Partner Balance: Summary of aged open amount per partner This report is an accounting tool helping in various tasks. You can credit control or partner balance provisions computation for instance. The aged balance report allows you to print balances per partner like the trial balance but add an extra information : * It will split balances into due amounts (due date not reached à the end date of the report) and overdue amounts Overdue data are also split by period. * For each partner following columns will be displayed: * Total balance (all figures must match with same date partner balance report). This column equals the sum of all following columns) * Due * Overdue <= 30 days * Overdue <= 60 days * Overdue <= 90 days * Overdue <= 120 days * Older Hypothesis / Contraints of aged partner balance * Overdues columns will be by default be based on 30 days range fix number of days. This can be changed by changes the RANGES constraint * All data will be displayed in company currency * When partial payments, the payment must appear in the same colums than the invoice (Except if multiple payment terms) * Data granularity: partner (will not display figures at invoices level) * The report aggregate data per account with sub-totals * Initial balance must be calculated the same way that the partner balance / Ignoring the opening entry in special period (idem open invoice report) * Only accounts with internal type payable or receivable are considered (idem open invoice report) * If maturity date is null then use move line date Limitations: ------------ In order to run properly this module makes sure you have installed the library `wkhtmltopdf` for the pdf rendering (the library path must be set in a System Parameter `webkit_path`). Initial balances in these reports are based either on opening entry posted in the opening period or computed on the fly. So make sure that your past accounting opening entries are in an opening period. Initials balances are not computed when using the Date filter (since a date can be outside its logical period and the initial balance could be different when computed by data or by initial balance for the period). The opening period is assumed to be the Jan. 1st of the year with an opening flag and the first period of the year must start also on Jan 1st. Totals for amounts in currencies are effective if the partner belongs to an account with a secondary currency. HTML headers and footers are deactivated for these reports because of an issue in wkhtmltopdf (http://code.google.com/p/wkhtmltopdf/issues/detail?id=656) Instead, the header and footer are created as text with arguments passed to wkhtmltopdf. The texts are defined inside the report classes. """, 'version': '1.1.0', 'author': 'Camptocamp', 'license': 'AGPL-3', 'category': 'Finance', 'website': 'http://www.camptocamp.com', 'images': [ 'images/ledger.png',], 'depends': ['account', 'report_webkit'], 'init_xml': [], 'demo_xml' : [], 'update_xml': ['account_view.xml', 'data/financial_webkit_header.xml', 'report/report.xml', 'wizard/wizard.xml', 'wizard/balance_common_view.xml', 'wizard/general_ledger_wizard_view.xml', 'wizard/partners_ledger_wizard_view.xml', 'wizard/trial_balance_wizard_view.xml', 'wizard/partner_balance_wizard_view.xml', 'wizard/open_invoices_wizard_view.xml', 'wizard/aged_partner_balance_wizard.xml', 'wizard/print_journal_view.xml', 'report_menus.xml', ], # tests order matter 'test': ['tests/general_ledger.yml', 'tests/partner_ledger.yml', 'tests/trial_balance.yml', 'tests/partner_balance.yml', 'tests/open_invoices.yml', 'tests/aged_trial_balance.yml'], #'tests/account_move_line.yml' 'active': False, 'installable': True, 'application': True, }
agpl-3.0
inter6/jHears
jhears-servlet-api/src/main/java/org/jhears/web/rs/InsertResource.java
2129
/* * jHears, acoustic fingerprinting framework. * Copyright (C) 2009-2010 Juha Heljoranta. * * This file is part of jHears. * * jHears is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * jHears 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with jHears. If not, see <http://www.gnu.org/licenses/>. */ package org.jhears.web.rs; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.jhears.auth.JHearsRoles; import org.jhears.server.FPCatalogEngine; @Path(ApiPath.INSERT) public class InsertResource extends BaseResource { public InsertResource(BaseResourceParam param) { super(param); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(value = { MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN }) public Response process(InsertRequest insert, @DefaultValue("json") @QueryParam("format") Format format) { if (!isAuthorized(JHearsRoles.USER)) { return unauthorized(); } FPCatalogEngine catalog = getCatalog(); Fingerprint fingerprint = catalog.insertFingerprint( insert.getAudioEntityId(), insert.getFingerprint(), getCtx()); if (fingerprint == null) { return Response.status(Status.FORBIDDEN) .entity("Insert request was not accepted").build(); } if (Format.plain.equals(format)) { return Response.ok(toText(fingerprint), MediaType.TEXT_PLAIN) .build(); } else { return Response.ok(fingerprint, MediaType.APPLICATION_JSON).build(); } } }
agpl-3.0
ketan-ghumatkar/Canvas-LMS
app/models/role.rb
6133
# # Copyright (C) 2012 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # class Role < ActiveRecord::Base belongs_to :account belongs_to :root_account, :class_name => 'Account' attr_accessible :name before_validation :infer_root_account_id validates_presence_of :name validates_inclusion_of :base_role_type, :in => RoleOverride::BASE_ROLE_TYPES, :message => 'is invalid' validates_exclusion_of :name, :in => RoleOverride::KNOWN_ROLE_TYPES + Enrollment::SIS_TYPES.values validates_uniqueness_of :name, :scope => :account_id validate :ensure_no_name_conflict_with_different_base_role_type def infer_root_account_id unless self.account self.errors.add(:account_id) return false end self.root_account_id = self.account.root_account_id || self.account.id end def ensure_no_name_conflict_with_different_base_role_type if self.root_account.all_roles.not_deleted.where("name = ? AND base_role_type <> ?", self.name, self.base_role_type).any? self.errors.add(:name, 'is already taken by a different type of Role in the same root account') end end include Workflow workflow do state :active do event :deactivate, :transitions_to => :inactive end state :inactive do event :activate, :transitions_to => :active end state :deleted end def account_role? base_role_type == AccountUser::BASE_ROLE_NAME end def course_role? !account_role? end def label self.name end alias_method :destroy!, :destroy def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now save! end scope :not_deleted, where("roles.workflow_state<>'deleted'") scope :deleted, where(:workflow_state => 'deleted') scope :active, where(:workflow_state => 'active') scope :inactive, where(:workflow_state => 'inactive') scope :for_courses, where("roles.base_role_type<>?", AccountUser::BASE_ROLE_NAME) scope :for_accounts, where(:base_role_type => AccountUser::BASE_ROLE_NAME) def self.is_base_role?(role_name) RoleOverride.base_role_types.include?(role_name) end # Returns a list of hashes for each base enrollment type, and each will have a # custom_roles key, each will look like: # [{:base_role_name => "StudentEnrollment", # :name => "StudentEnrollment", # :label => "Student", # :plural_label => "Students", # :custom_roles => # [{:base_role_name => "StudentEnrollment", # :name => "weirdstudent", # :asset_string => "role_4" # :label => "weirdstudent"}]}, # ] def self.all_enrollment_roles_for_account(account, include_inactive=false) custom_roles = account.available_course_roles_by_name(include_inactive).values RoleOverride::ENROLLMENT_TYPES.map do |br| new = br.clone new[:label] = br[:label].call new[:plural_label] = br[:plural_label].call new[:custom_roles] = custom_roles.select{|cr|cr.base_role_type == new[:base_role_name]}.map do |cr| {:base_role_name => cr.base_role_type, :name => cr.name, :label => cr.name, :asset_string => cr.asset_string, :workflow_state => cr.workflow_state} end new end end # returns same hash as all_enrollment_roles_for_account but adds enrollment # counts for the given course to each item def self.custom_roles_and_counts_for_course(course, user, include_inactive=false) users_scope = course.users_visible_to(user) base_counts = users_scope.count(:distinct => true, :group => 'enrollments.type', :select => 'users.id', :conditions => 'enrollments.role_name IS NULL') role_counts = users_scope.count(:distinct => true, :group => 'enrollments.role_name', :select => 'users.id', :conditions => 'enrollments.role_name IS NOT NULL') @enrollment_types = Role.all_enrollment_roles_for_account(course.account, include_inactive) @enrollment_types.each do |base_type| base_type[:count] = base_counts[base_type[:name]] || 0 base_type[:custom_roles].each do |custom_role| custom_role[:count] = role_counts[custom_role[:name]] || 0 end end @enrollment_types end def self.built_in_role_names @built_in_role_names ||= %w(AccountAdmin) + Enrollment.valid_types end # this is designed to be used in place of a Role for the purpose # of displaying built-in roles alongside custom ones. # it implements name, base_role_type, and workflow_state class BuiltInRole attr_accessor :name def initialize(name) @name = name if @name == 'AccountAdmin' @label = I18n.t('roles.account_admin', "Account Admin") else er = RoleOverride.enrollment_types.find{|er|er[:name] == @name} @label = er[:label].call end end def self.create(name) return nil unless Role.built_in_role_names.include?(name) BuiltInRole.new(name) end def base_role_type (@name == 'AccountAdmin') ? 'AccountMembership' : @name end def workflow_state 'active' end def label @label end end # returns a BuiltInRole for the role with the given name, or nil # if the role is not a built-in-role def self.built_in_role(role_name) return nil unless self.built_in_role_names.include?(role_name) @built_in_roles ||= {} @built_in_roles[role_name] ||= BuiltInRole.create(role_name) end # returns an array of all built-in Roles def self.built_in_roles @all_built_in_roles ||= self.built_in_role_names.map{ |brt| Role.built_in_role(brt) } end end
agpl-3.0
uniteddiversity/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/service/ibatis/CampaignServiceImpl.java
6855
/** * This file is part of mycollab-services. * * mycollab-services is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.crm.service.ibatis; import com.esofthead.mycollab.common.ModuleNameConstants; import com.esofthead.mycollab.common.interceptor.aspect.*; import com.esofthead.mycollab.core.persistence.ICrudGenericDAO; import com.esofthead.mycollab.core.persistence.ISearchableDAO; import com.esofthead.mycollab.core.persistence.service.DefaultService; import com.esofthead.mycollab.module.crm.CrmTypeConstants; import com.esofthead.mycollab.module.crm.dao.*; import com.esofthead.mycollab.module.crm.domain.*; import com.esofthead.mycollab.module.crm.domain.criteria.CampaignSearchCriteria; import com.esofthead.mycollab.module.crm.service.CampaignService; import com.esofthead.mycollab.schedule.email.crm.CampaignRelayEmailNotificationAction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.GregorianCalendar; import java.util.List; /** * @author MyCollab Ltd. * @since 1.0 */ @Service @Transactional @Traceable(nameField = "campaignname") @Auditable() @Watchable(userFieldName = "assignuser") @NotifyAgent(CampaignRelayEmailNotificationAction.class) public class CampaignServiceImpl extends DefaultService<Integer, CampaignWithBLOBs, CampaignSearchCriteria> implements CampaignService { static { ClassInfoMap.put(CampaignServiceImpl.class, new ClassInfo(ModuleNameConstants.CRM, CrmTypeConstants.CAMPAIGN)); } @Autowired private CampaignMapper campaignMapper; @Autowired private CampaignMapperExt campaignMapperExt; @Autowired private CampaignAccountMapper campaignAccountMapper; @Autowired private CampaignContactMapper campaignContactMapper; @Autowired private CampaignLeadMapper campaignLeadMapper; @Override public ICrudGenericDAO<Integer, CampaignWithBLOBs> getCrudMapper() { return campaignMapper; } @Override public ISearchableDAO<CampaignSearchCriteria> getSearchMapper() { return campaignMapperExt; } @Override public SimpleCampaign findById(Integer campaignId, Integer sAccountUd) { return campaignMapperExt.findById(campaignId); } @Override public Integer saveWithSession(CampaignWithBLOBs campaign, String username) { Integer result = super.saveWithSession(campaign, username); if (campaign.getExtraData() != null && campaign.getExtraData() instanceof SimpleLead) { CampaignLead associateLead = new CampaignLead(); associateLead.setCampaignid(campaign.getId()); associateLead.setLeadid(((SimpleLead) campaign.getExtraData()) .getId()); associateLead.setCreatedtime(new GregorianCalendar().getTime()); this.saveCampaignLeadRelationship(Arrays.asList(associateLead), campaign.getSaccountid()); } return result; } @Override public void saveCampaignAccountRelationship( List<CampaignAccount> associateAccounts, Integer sAccountId) { for (CampaignAccount associateAccount : associateAccounts) { CampaignAccountExample ex = new CampaignAccountExample(); ex.createCriteria() .andAccountidEqualTo(associateAccount.getAccountid()) .andCampaignidEqualTo(associateAccount.getCampaignid()); if (campaignAccountMapper.countByExample(ex) == 0) { campaignAccountMapper.insert(associateAccount); } } } @Override public void removeCampaignAccountRelationship( CampaignAccount associateAccount, Integer sAccountId) { CampaignAccountExample ex = new CampaignAccountExample(); ex.createCriteria() .andAccountidEqualTo(associateAccount.getAccountid()) .andCampaignidEqualTo(associateAccount.getCampaignid()); campaignAccountMapper.deleteByExample(ex); } @Override public void saveCampaignContactRelationship( List<CampaignContact> associateContacts, Integer sAccountId) { for (CampaignContact associateContact : associateContacts) { CampaignContactExample ex = new CampaignContactExample(); ex.createCriteria() .andCampaignidEqualTo(associateContact.getCampaignid()) .andContactidEqualTo(associateContact.getContactid()); if (campaignContactMapper.countByExample(ex) == 0) { campaignContactMapper.insert(associateContact); } } } @Override public void removeCampaignContactRelationship( CampaignContact associateContact, Integer sAccountId) { CampaignContactExample ex = new CampaignContactExample(); ex.createCriteria() .andCampaignidEqualTo(associateContact.getCampaignid()) .andContactidEqualTo(associateContact.getContactid()); campaignContactMapper.deleteByExample(ex); } @Override public void saveCampaignLeadRelationship(List<CampaignLead> associateLeads, Integer sAccountId) { for (CampaignLead associateLead : associateLeads) { CampaignLeadExample ex = new CampaignLeadExample(); ex.createCriteria() .andCampaignidEqualTo(associateLead.getCampaignid()) .andLeadidEqualTo(associateLead.getLeadid()); if (campaignLeadMapper.countByExample(ex) == 0) { campaignLeadMapper.insert(associateLead); } } } @Override public void removeCampaignLeadRelationship(CampaignLead associateLead, Integer sAccountId) { CampaignLeadExample ex = new CampaignLeadExample(); ex.createCriteria().andCampaignidEqualTo(associateLead.getCampaignid()) .andLeadidEqualTo(associateLead.getLeadid()); campaignLeadMapper.deleteByExample(ex); } }
agpl-3.0
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/console/events/ConsoleResetHistoryHandler.java
705
/* * ConsoleResetHistoryHandler.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.console.events; import com.google.gwt.event.shared.EventHandler; public interface ConsoleResetHistoryHandler extends EventHandler { void onConsoleResetHistory(ConsoleResetHistoryEvent event); }
agpl-3.0
MuckRock/muckrock
muckrock/tags/admin.py
482
""" Admin registration for tag models """ # Django from django.contrib import admin # Third Party from taggit.models import Tag as TaggitTag # MuckRock from muckrock.tags.models import Tag class TagAdmin(admin.ModelAdmin): """Model Admin for a tag""" # pylint: disable=too-many-public-methods prepopulated_fields = {"slug": ("name",)} search_fields = ("name",) list_display = ["name"] admin.site.register(Tag, TagAdmin) admin.site.unregister(TaggitTag)
agpl-3.0
devent/sscontrol
sscontrol-dns/src/main/java/com/anrisoftware/sscontrol/dns/zone/AbstractRecord.java
3153
/* * Copyright 2012-2015 Erwin Müller <erwin.mueller@deventm.org> * * This file is part of sscontrol-dns. * * sscontrol-dns is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * sscontrol-dns 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 Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with sscontrol-dns. If not, see <http://www.gnu.org/licenses/>. */ package com.anrisoftware.sscontrol.dns.zone; import java.io.Serializable; import java.text.ParseException; import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang3.builder.ToStringBuilder; import org.joda.time.Duration; import com.anrisoftware.globalpom.format.duration.DurationFormatFactory; import com.anrisoftware.sscontrol.core.api.ServiceException; import com.anrisoftware.sscontrol.dns.time.TimeDuration; import com.anrisoftware.sscontrol.dns.time.TimeDurationFactory; /** * Saves the zone and the time to live time for the record. * * @author Erwin Mueller, erwin.mueller@deventm.org * @since 1.0 */ @SuppressWarnings("serial") public abstract class AbstractRecord implements ZoneRecord, Serializable { private static final String DURATION = "duration"; private static final String TTL = "ttl"; private static final String ZONE = "zone"; private final DnsZone zone; @Inject private DurationFormatFactory durationFormatFactory; @Inject private TimeDurationFactory durationFactory; private AbstractRecordLogger log; private TimeDuration ttl; /** * Sets the DNS zone to which this record belongs to. * * @param zone * the {@link DnsZone}. * */ protected AbstractRecord(DnsZone zone) { this.zone = zone; } /** * Injects the logger for this record. * * @param logger * the {@link AbstractRecordLogger}. */ @Inject void setAbstractRecordLogger(AbstractRecordLogger logger) { this.log = logger; } @Override public void ttl(Map<String, Object> args) throws ParseException { args.put(DURATION, asDuration(args.get(DURATION))); this.ttl = durationFactory.create(this, args); log.ttlSet(this, ttl); } public void ttl(Object args) throws ServiceException { log.invalidOperation(this, "ttl"); } private Duration asDuration(Object object) throws ParseException { log.checkDuration(this, object); if (!(object instanceof Duration)) { return durationFormatFactory.create().parse(object.toString()); } else { return (Duration) object; } } @Override public DnsZone getZone() { return zone; } @Override public Duration getTtl() { return ttl == null ? null : ttl.getDuration(); } @Override public String toString() { return new ToStringBuilder(this).append(ZONE, zone.getName()) .append(TTL, ttl).toString(); } }
agpl-3.0
aptivate/ckanext-mapactionevent
ckanext/mapactionevent/plugin.py
5039
from ckan import logic from ckan.lib.navl.validators import ignore_missing import pylons.config as config import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import ckanext.mapactionevent.logic.action.create import ckanext.mapactionevent.logic.action.get group_type = 'event' def event_description_length(): value = config.get('ckan.mapactionevent.event_description_length', 200) value = toolkit.asint(value) return value class MapactioneventPlugin(plugins.SingletonPlugin, toolkit.DefaultGroupForm): plugins.implements(plugins.IGroupForm, inherit=False) plugins.implements(plugins.IConfigurer) plugins.implements(plugins.IActions) plugins.implements(plugins.IRoutes, inherit=True) plugins.implements(plugins.IFacets, inherit=True) plugins.implements(plugins.ITemplateHelpers) # IFacets def dataset_facets(self, facets_dict, package_type): if 'groups' in facets_dict: facets_dict['groups'] = plugins.toolkit._('Locations or Events') return facets_dict def group_facets(self, facets_dict, group_type, package_type): facets_dict.pop('organization', False) facets_dict.pop('tags', False) facets_dict.pop('groups', False) return facets_dict def organization_facets(self, facets_dict, group_type, package_type): if 'groups' in facets_dict: facets_dict['groups'] = plugins.toolkit._('Events') return facets_dict # IRoutes def before_map(self, map): map.connect( '/', controller='ckanext.mapactionevent.controllers.homecontroller:HomeController', action='index') map.connect( '/%s/new' % group_type, controller='ckanext.mapactionevent.controllers.event_groupcontroller:EventGroupController', action='new') # TODO: IGroupForm register_group_plugins doesn't support delete (in # the <group_type>_action mapping). I'm not sure why this is, but we # implement it here instead: map.connect( '%s_delete' % group_type, '/%s/delete/{id}' % group_type, controller='ckanext.mapactionevent.controllers.event_groupcontroller:EventGroupController', action='delete') map.connect( '%s_about' % group_type, '/%s/about/{id}' % group_type, controller='ckanext.mapactionevent.controllers.event_groupcontroller:EventGroupController', action='about') return map # IActions def get_actions(self): return { 'event_create': ckanext.mapactionevent.logic.action.create.event_create, 'event_list': ckanext.mapactionevent.logic.action.get.event_list, } # IConfigurer def update_config(self, config_): toolkit.add_template_directory(config_, 'templates') toolkit.add_public_directory(config_, 'public') toolkit.add_resource('fanstatic', 'mapactionevent') # IGroupForm def form_to_db_schema_options(self, options): ''' This allows us to select different schemas for different purpose eg via the web interface or via the api or creation vs updating. It is optional and if not available form_to_db_schema should be used. If a context is provided, and it contains a schema, it will be returned. ''' schema = options.get('context', {}).get('schema', None) if schema: return schema if options.get('api'): if options.get('type') == 'create': return self.form_to_db_schema_api_create() else: return logic.schema.default_update_group_schema() else: return self.form_to_db_schema() #ITemplateHelpers def get_helpers(self): return { 'event_description_length': event_description_length } def form_to_db_schema_api_create(self): schema = logic.schema.default_group_schema() # Allow created date to be set explicitly on events schema['created'] = [ignore_missing] return schema def form_to_db_schema(self): schema = logic.schema.group_form_schema() # Allow created date to be set explicitly on events schema['created'] = [ignore_missing] return schema def group_controller(self): return "ckanext.mapactionevent.controllers.event_groupcontroller:EventGroupController" def group_types(self): return (group_type,) def is_fallback(self): False def group_form(self): return 'mapactionevent/group_form.html' def new_template(self): return 'mapactionevent/new.html' def index_template(self): return 'mapactionevent/index.html' def edit_template(self): return 'mapactionevent/edit.html' def read_template(self): return 'mapactionevent/read.html' def about_template(self): return 'mapactionevent/about.html'
agpl-3.0
ow2-proactive/agent-windows
ProActiveAgent/CommonStartInfo.cs
6349
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_INITIAL_DEV$$ */ using System; using System.Collections.Generic; using ConfigParser; using log4net; namespace ProActiveAgent { /// <summary> /// Common information collected at runtime and shared between multiple ProActive Runtime Executors /// </summary> sealed class CommonStartInfo { private static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Initialized by the WindowsService.main(), the directory will contain all logs file (runtime and executors logs) public static string logsDirectory; /// <summary> /// The configuration used to run the process</summary> private readonly AgentType _configuration; /// <summary> /// The selected connection</summary> private readonly ConnectionType _enabledConnection; /// <summary> /// All jvm options (default and user defined)</summary> private readonly string[] _jvmOptions; /// <summary> /// The runtime start delay to avoid concurrent access problems</summary> private readonly int _runtimeStartDelayInMs = 500; /// <summary> /// The runtime start delay is enabled if the PA_AGENT_RUNTIME_START_DELAY system env variable is defined</summary> private readonly bool _runtimeStartDelayEnabled; /// <summary> /// If always available and max cpu usage is 100, no need to use the cpu limiter</summary> private readonly bool _cpuLimiterEnabled; /// <summary> /// The constructor of this class.</summary> public CommonStartInfo(AgentType configuration) { this._configuration = configuration; // Get the selected connection, if no connection is enabled it is an error this._enabledConnection = configuration.getEnabledConnection(); if (this._enabledConnection == null) { LOGGER.Error("No selected connection in the configuration. Exiting ..."); Environment.Exit(0); } else { LOGGER.Info("Selected connection " + this._enabledConnection.GetType().Name); } // The list of jvm options (default + user defined) List<string> mergedJvmOptionsList = new List<string>(); // Add default parameters this._enabledConnection.fillDefaultJvmOptions(mergedJvmOptionsList, this._configuration.config.proactiveHome); // Add user defined if (this._configuration.config.jvmParameters != null) { mergedJvmOptionsList.AddRange(this._configuration.config.jvmParameters); } this._jvmOptions = mergedJvmOptionsList.ToArray(); // The system env variable must not be null otherwise the delay is not enabled string value = System.Environment.GetEnvironmentVariable("PA_AGENT_RUNTIME_START_DELAY", EnvironmentVariableTarget.Machine); if (value != null) { if (!Int32.TryParse(value, out this._runtimeStartDelayInMs)) LOGGER.Warn("Unable to parse the runtime start delay using default value " + this._runtimeStartDelayInMs + " ms"); else { this._runtimeStartDelayEnabled = true; LOGGER.Info("Runtime start delay is set to " + this._runtimeStartDelayInMs + " ms"); } } this._cpuLimiterEnabled = !(configuration.isAlwaysAvailable() && configuration.config.maxCpuUsage == 100); } public AgentType configuration { get { return this._configuration; } } public ConnectionType enabledConnection { get { return this._enabledConnection; } } public string[] jvmOptions { get { return this._jvmOptions; } } public string starterClass { get { return this._enabledConnection.javaStarterClass; } } public int runtimeStartDelayInMs { get { return this._runtimeStartDelayInMs; } } public bool isRuntimeStartDelayEnabled { get { return this._runtimeStartDelayEnabled; } } public bool isCpuLimiterEnabled { get { return this._cpuLimiterEnabled; } } } }
agpl-3.0
cheekahao/lianteam
src/admin/controllers/page-change.controller.js
3162
/** * Page Change Controller */ angular.module('controllers').controller('pageChange', ['$scope', '$state', '$stateParams', '$http', 'account', '$sce', function ($scope, $state, $stateParams, $http, account, $sce) { 'use strict'; /** * 初始化变量 */ $scope.transmitting = true; $scope._id = $stateParams.page; $scope.name = ''; $scope.pageContent = ''; $scope.pageMedia = []; $scope.editAuth = false; $scope.readAuth = false; /** * 读取用户编辑权限以及返回读取当前单页 */ var getAuthAndGetPage = account.auths() .then(function (auths) { $scope.editAuth = auths.pages.edit; $scope.readAuth = auths.pages.read; if (auths.pages.read && !auths.pages.edit) { return $http.get('/api/pages/' + $stateParams.page); } else if (auths.pages.edit) { return $http.get('/api/pages/' + $stateParams.page, { params: { markdown: true } }); } }, function () { $scope.$emit('notification', { type: 'danger', message: '读取权限失败' }); }); /** * 读取当前单页 */ if ($stateParams.page) { getAuthAndGetPage .then(function (res) { var data = res.data; if (data) { if (!_.isEmpty(data.pageMedia)) { _.forEach(data.pageMedia, function (medium) { $scope.pageMedia.push({ file: null, fileName: medium.fileName, description: medium.description, src: medium.src, _id: medium._id, uploadStatus: 'success', active: false, edited: false }); }); } $scope.name = data.name; if ($scope.editAuth) { $scope.pageContent = data.pageContent; } else if ($scope.readAuth) { $scope.pageContent = $sce.trustAsHtml(data.pageContent); } $scope.transmitting = false; } else { $scope.transmitting = true; } }, function () { $scope.$emit('notification', { type: 'danger', message: '获取内容失败' }); }); } /** * 保存当前内容 */ $scope.savePage = function () { $scope.transmitting = true; var data = { pageContent: $scope.pageContent }; if (!_.isEmpty($scope.pageMedia)) { data.pageMedia = _.map($scope.pageMedia, '_id'); } $http.put('/api/pages/' + $stateParams.page, data) .then(function () { $scope.transmitting = false; $scope.$emit('notification', { type: 'success', message: '更新单页成功' }); $state.go('main.pages', { page: $stateParams.page }, { reload: 'main.pages' }); }, function () { $scope.$emit('notification', { type: 'danger', message: '更新单页失败' }); }); }; } ]);
agpl-3.0
itschool/kalolsavam-subdistrict
system/application/views/result/afterresult_report/rpt_grade_wise_participant_details.php
1019
<table width="890" height="62" border="0"> <tr> <td width="884"><h2 align="center"><strong>Grade Wise Participant Details</strong></h2></td> </tr> </table> <table width="889" border="0"> <tr> <td width="85">Rank</td> <td width="10">:</td> <td width="293">&nbsp;</td> <td width="483">&nbsp;</td> </tr> </table> <table width="887" border="0"> <tr> <td width="80"><div align="center">Sl No</div></td> <td width="248"><div align="center">Name of Participant</div></td> <td width="274"><div align="center">Name of the school</div></td> <td width="204"><div align="center">Item</div></td> <td width="59"><div align="center">Point</div></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td><div align="right"> :</div></td> <td>&nbsp;</td> </tr> </table> <p>&nbsp;</p> <p>&nbsp;</p>
agpl-3.0
retorquere/zotero
chrome/content/zotero/xpcom/itemTreeView.js
90164
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ //////////////////////////////////////////////////////////////////////////////// /// /// ItemTreeView /// -- handles the link between an individual tree and the data layer /// -- displays only items (no collections, no hierarchy) /// //////////////////////////////////////////////////////////////////////////////// /* * Constructor for the ItemTreeView object */ Zotero.ItemTreeView = function (collectionTreeRow, sourcesOnly) { Zotero.LibraryTreeView.apply(this); this.wrappedJSObject = this; this.rowCount = 0; this.collectionTreeRow = collectionTreeRow; this._skipKeypress = false; this._sourcesOnly = sourcesOnly; this._ownerDocument = null; this._needsSort = false; this._cellTextCache = {}; this._itemImages = {}; this._refreshPromise = Zotero.Promise.resolve(); this._unregisterID = Zotero.Notifier.registerObserver( this, ['item', 'collection-item', 'item-tag', 'share-items', 'bucket', 'feedItem', 'search'], 'itemTreeView', 50 ); } Zotero.ItemTreeView.prototype = Object.create(Zotero.LibraryTreeView.prototype); Zotero.ItemTreeView.prototype.type = 'item'; /** * Called by the tree itself */ Zotero.ItemTreeView.prototype.setTree = Zotero.Promise.coroutine(function* (treebox) { try { Zotero.debug("Setting tree for " + this.collectionTreeRow.id + " items view " + this.id); var start = Date.now(); // Try to set the window document if not yet set if (treebox && !this._ownerDocument) { try { this._ownerDocument = treebox.treeBody.ownerDocument; } catch (e) {} } if (this._treebox) { if (this._needsSort) { this.sort(); } return; } if (!treebox) { Zotero.debug("Treebox not passed in setTree()", 2); return; } if (!this._ownerDocument) { Zotero.debug("No owner document in setTree()", 2); return; } this._treebox = treebox; this.setSortColumn(); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('pane.items.loading')); } if (Zotero.locked) { Zotero.debug("Zotero is locked -- not loading items tree", 2); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } return; } yield this.refresh(); if (!this._treebox.treeBody) { return; } // Add a keypress listener for expand/collapse var tree = this._treebox.treeBody.parentNode; var self = this; var coloredTagsRE = new RegExp("^[1-" + Zotero.Tags.MAX_COLORED_TAGS + "]{1}$"); var listener = function(event) { if (self._skipKeyPress) { self._skipKeyPress = false; return; } // Handle arrow keys specially on multiple selection, since // otherwise the tree just applies it to the last-selected row if (event.keyCode == 39 || event.keyCode == 37) { if (self._treebox.view.selection.count > 1) { switch (event.keyCode) { case 39: self.expandSelectedRows(); break; case 37: self.collapseSelectedRows(); break; } event.preventDefault(); } return; } var key = String.fromCharCode(event.which); if (key == '+' && !(event.ctrlKey || event.altKey || event.metaKey)) { self.expandAllRows(); event.preventDefault(); return; } else if (key == '-' && !(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) { self.collapseAllRows(); event.preventDefault(); return; } // Ignore other non-character keypresses if (!event.charCode || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) { return; } event.preventDefault(); Zotero.spawn(function* () { if (coloredTagsRE.test(key)) { let libraryID = self.collectionTreeRow.ref.libraryID; let position = parseInt(key) - 1; let colorData = Zotero.Tags.getColorByPosition(libraryID, position); // If a color isn't assigned to this number or any // other numbers, allow key navigation if (!colorData) { return !Zotero.Tags.getColors(libraryID).size; } var items = self.getSelectedItems(); yield Zotero.Tags.toggleItemsListTags(libraryID, items, colorData.name); return; } // We have to disable key navigation on the tree in order to // keep it from acting on the 1-6 keys used for colored tags. // To allow navigation with other keys, we temporarily enable // key navigation and recreate the keyboard event. Since // that will trigger this listener again, we set a flag to // ignore the event, and then clear the flag above when the // event comes in. I see no way this could go wrong... tree.disableKeyNavigation = false; self._skipKeyPress = true; var nsIDWU = Components.interfaces.nsIDOMWindowUtils; var domWindowUtils = event.originalTarget.ownerDocument.defaultView .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(nsIDWU); var modifiers = 0; if (event.altKey) { modifiers |= nsIDWU.MODIFIER_ALT; } if (event.ctrlKey) { modifiers |= nsIDWU.MODIFIER_CONTROL; } if (event.shiftKey) { modifiers |= nsIDWU.MODIFIER_SHIFT; } if (event.metaKey) { modifiers |= nsIDWU.MODIFIER_META; } domWindowUtils.sendKeyEvent( 'keypress', event.keyCode, event.charCode, modifiers ); tree.disableKeyNavigation = true; }) .catch(function (e) { Zotero.logError(e); }) }; // Store listener so we can call removeEventListener() in ItemTreeView.unregister() this.listener = listener; tree.addEventListener('keypress', listener); // This seems to be the only way to prevent Enter/Return // from toggle row open/close. The event is handled by // handleKeyPress() in zoteroPane.js. tree._handleEnter = function () {}; this.sort(); this.expandMatchParents(); if (this._ownerDocument.defaultView.ZoteroPane_Local) { // For My Publications, show intro text in middle pane if no items if (this.collectionTreeRow && this.collectionTreeRow.isPublications() && !this.rowCount) { let doc = this._ownerDocument; let ns = 'http://www.w3.org/1999/xhtml' let div = doc.createElementNS(ns, 'div'); let p = doc.createElementNS(ns, 'p'); p.textContent = Zotero.getString('publications.intro.text1', ZOTERO_CONFIG.DOMAIN_NAME); div.appendChild(p); p = doc.createElementNS(ns, 'p'); p.textContent = Zotero.getString('publications.intro.text2'); div.appendChild(p); p = doc.createElementNS(ns, 'p'); let html = Zotero.getString('publications.intro.text3'); // Convert <b> tags to placeholders html = html.replace('<b>', ':b:').replace('</b>', ':/b:'); // Encode any other special chars, which shouldn't exist html = Zotero.Utilities.htmlSpecialChars(html); // Restore bold text html = html.replace(':b:', '<strong>').replace(':/b:', '</strong>'); p.innerHTML = html; // AMO note: markup from hard-coded strings and filtered above div.appendChild(p); content = div; doc.defaultView.ZoteroPane_Local.setItemsPaneMessage(content); } else { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } } if (this.collectionTreeRow && this.collectionTreeRow.itemToSelect) { var item = this.collectionTreeRow.itemToSelect; yield this.selectItem(item['id'], item['expand']); this.collectionTreeRow.itemToSelect = null; } Zotero.debug("Set tree for items view " + this.id + " in " + (Date.now() - start) + " ms"); this._initialized = true; yield this._runListeners('load'); } catch (e) { Zotero.debug(e, 1); Components.utils.reportError(e); if (this.onError) { this.onError(e); } throw e; } }); Zotero.ItemTreeView.prototype.setSortColumn = function() { var dir, col, currentCol, currentDir; for (let i=0, len=this._treebox.columns.count; i<len; i++) { let column = this._treebox.columns.getColumnAt(i); if (column.element.getAttribute('sortActive')) { currentCol = column; currentDir = column.element.getAttribute('sortDirection'); column.element.removeAttribute('sortActive'); column.element.removeAttribute('sortDirection'); break; } } let colID = Zotero.Prefs.get('itemTree.sortColumnID'); // Restore previous sort setting (feed -> non-feed) if (! this.collectionTreeRow.isFeed() && colID) { col = this._treebox.columns.getNamedColumn(colID); dir = Zotero.Prefs.get('itemTree.sortDirection'); Zotero.Prefs.clear('itemTree.sortColumnID'); Zotero.Prefs.clear('itemTree.sortDirection'); // No previous sort setting stored, so store it (non-feed -> feed) } else if (this.collectionTreeRow.isFeed() && !colID && currentCol) { Zotero.Prefs.set('itemTree.sortColumnID', currentCol.id); Zotero.Prefs.set('itemTree.sortDirection', currentDir); // Retain current sort setting (non-feed -> non-feed) } else { col = currentCol; dir = currentDir; } if (col) { col.element.setAttribute('sortActive', true); col.element.setAttribute('sortDirection', dir); } } /** * Reload the rows from the data access methods * (doesn't call the tree.invalidate methods, etc.) */ Zotero.ItemTreeView.prototype.refresh = Zotero.serial(Zotero.Promise.coroutine(function* () { Zotero.debug('Refreshing items list for ' + this.id); // DEBUG: necessary? try { this._treebox.columns.count } // If treebox isn't ready, skip refresh catch (e) { return false; } var resolve, reject; this._refreshPromise = new Zotero.Promise(function () { resolve = arguments[0]; reject = arguments[1]; }); try { Zotero.CollectionTreeCache.clear(); var newItems = yield this.collectionTreeRow.getItems(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } var savedSelection = this.getSelectedItems(true); var savedOpenState = this._saveOpenState(); var oldCount = this.rowCount; var newSearchItemIDs = {}; var newSearchParentIDs = {}; var newCellTextCache = {}; var newSearchMode = this.collectionTreeRow.isSearchMode(); var newRows = []; var added = 0; for (let i=0, len=newItems.length; i < len; i++) { let item = newItems[i]; // Only add regular items if sourcesOnly is set if (this._sourcesOnly && !item.isRegularItem()) { continue; } // Don't add child items directly (instead mark their parents for // inclusion below) let parentItemID = item.parentItemID; if (parentItemID) { newSearchParentIDs[parentItemID] = true; } // Add top-level items else { this._addRowToArray( newRows, new Zotero.ItemTreeRow(item, 0, false), added++ ); } newSearchItemIDs[item.id] = true; } // Add parents of matches if not matches themselves for (let id in newSearchParentIDs) { if (!newSearchItemIDs[id]) { let item = Zotero.Items.get(id); this._addRowToArray( newRows, new Zotero.ItemTreeRow(item, 0, false), added++ ); } } this._rows = newRows; this.rowCount = this._rows.length; var diff = this.rowCount - oldCount; if (diff != 0) { this._treebox.rowCountChanged(0, diff); } this._refreshItemRowMap(); this._searchMode = newSearchMode; this._searchItemIDs = newSearchItemIDs; // items matching the search this._searchParentIDs = newSearchParentIDs; this._cellTextCache = {}; this.rememberOpenState(savedOpenState); this.rememberSelection(savedSelection); this.expandMatchParents(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } setTimeout(function () { resolve(); }); } catch (e) { setTimeout(function () { reject(e); }); throw e; } })); /* * Called by Zotero.Notifier on any changes to items in the data layer */ Zotero.ItemTreeView.prototype.notify = Zotero.Promise.coroutine(function* (action, type, ids, extraData) { Zotero.debug("Yielding for refresh promise"); // TEMP yield this._refreshPromise; if (!this._treebox || !this._treebox.treeBody) { Zotero.debug("Treebox didn't exist in itemTreeView.notify()"); return; } if (!this._rowMap) { Zotero.debug("Item row map didn't exist in itemTreeView.notify()"); return; } if (type == 'search' && action == 'modify') { // TODO: Only refresh on condition change (not currently available in extraData) yield this.refresh(); this.sort(); this._treebox.invalidate(); return; } // Clear item type icon and tag colors when a tag is added to or removed from an item if (type == 'item-tag') { // TODO: Only update if colored tag changed? ids.map(function (val) val.split("-")[0]).forEach(function (val) { delete this._itemImages[val]; }.bind(this)); return; } var collectionTreeRow = this.collectionTreeRow; if (collectionTreeRow.isFeed() && action == 'modify') { for (let i=0; i<ids.length; i++) { this._treebox.invalidateRow(this._rowMap[ids[i]]); } } var madeChanges = false; var refreshed = false; var sort = false; var savedSelection = this.getSelectedItems(true); var previousFirstSelectedRow = this._rowMap[ids[0]]; // If there's not at least one new item to be selected, get a scroll position to restore later var scrollPosition = false; if (action != 'add' || ids.every(id => extraData[id] && extraData[id].skipSelect)) { scrollPosition = this._saveScrollPosition(); } // Redraw the tree (for tag color and progress changes) if (action == 'redraw') { // Redraw specific rows if (type == 'item' && ids.length) { // Redraw specific cells if (extraData && extraData.column) { var col = this._treebox.columns.getNamedColumn( 'zotero-items-column-' + extraData.column ); for each(var id in ids) { if (extraData.column == 'title') { delete this._itemImages[id]; } this._treebox.invalidateCell(this._rowMap[id], col); } } else { for each(var id in ids) { delete this._itemImages[id]; this._treebox.invalidateRow(this._rowMap[id]); } } } // Redraw the whole tree else { this._itemImages = {}; this._treebox.invalidate(); } return; } if (action == 'refresh') { if (type == 'share-items') { if (collectionTreeRow.isShare()) { yield this.refresh(); refreshed = true; } } else if (type == 'bucket') { if (collectionTreeRow.isBucket()) { yield this.refresh(); refreshed = true; } } else if (type == 'publications') { if (collectionTreeRow.isPublications()) { yield this.refresh(); refreshed = true; } } // If refreshing a single item, clear caches and then unselect and reselect row else if (savedSelection.length == 1 && savedSelection[0] == ids[0]) { let row = this._rowMap[ids[0]]; delete this._cellTextCache[row]; this.selection.clearSelection(); this.rememberSelection(savedSelection); } else { this._cellTextCache = {}; } return; } if (collectionTreeRow.isShare()) { return; } // See if we're in the active window var zp = Zotero.getActiveZoteroPane(); var activeWindow = zp && zp.itemsView == this; var quicksearch = this._ownerDocument.getElementById('zotero-tb-search'); // 'collection-item' ids are in the form collectionID-itemID if (type == 'collection-item') { if (!collectionTreeRow.isCollection()) { return; } var splitIDs = []; for each(var id in ids) { var split = id.split('-'); // Skip if not an item in this collection if (split[0] != collectionTreeRow.ref.id) { continue; } splitIDs.push(split[1]); } ids = splitIDs; // Select the last item even if there are no changes (e.g. if the tag // selector is open and already refreshed the pane) /*if (splitIDs.length > 0 && (action == 'add' || action == 'modify')) { var selectItem = splitIDs[splitIDs.length - 1]; }*/ } this.selection.selectEventsSuppressed = true; //this._treebox.beginUpdateBatch(); if ((action == 'remove' && !collectionTreeRow.isLibrary(true)) || action == 'delete' || action == 'trash' || (action == 'removeDuplicatesMaster' && collectionTreeRow.isDuplicates())) { // Since a remove involves shifting of rows, we have to do it in order, // so sort the ids by row var rows = []; let push = action == 'delete' || action == 'trash' || action == 'removeDuplicatesMaster'; for (var i=0, len=ids.length; i<len; i++) { if (!push) { push = !collectionTreeRow.ref.hasItem(ids[i]); } // Row might already be gone (e.g. if this is a child and // 'modify' was sent to parent) let row = this._rowMap[ids[i]]; if (push && row !== undefined) { // Don't remove child items from collections, because it's handled by 'modify' if (action == 'remove' && this.getParentIndex(row) != -1) { continue; } rows.push(row); // Remove child items of removed parents if (this.isContainer(row) && this.isContainerOpen(row)) { while (++row < this.rowCount && this.getLevel(row) > 0) { rows.push(row); } } } } if (rows.length > 0) { // Child items might have been added more than once rows = Zotero.Utilities.arrayUnique(rows); rows.sort(function(a,b) { return a-b }); for (let i = rows.length - 1; i >= 0; i--) { this._removeRow(rows[i]); } madeChanges = true; sort = true; } } else if (type == 'item' && action == 'modify') { // Clear row caches var items = Zotero.Items.get(ids); for (let i=0; i<items.length; i++) { let id = items[i].id; delete this._itemImages[id]; delete this._cellTextCache[id]; } // If trash or saved search, just re-run search if (collectionTreeRow.isTrash() || collectionTreeRow.isSearch()) { yield this.refresh(); refreshed = true; madeChanges = true; sort = true; } if (collectionTreeRow.isFeed()) { this._ownerDocument.defaultView.ZoteroItemPane.setToggleReadLabel(); } // If no quicksearch, process modifications manually else if (!quicksearch || quicksearch.value == '') { var items = Zotero.Items.get(ids); for (let i = 0; i < items.length; i++) { let item = items[i]; let id = item.id; let row = this._rowMap[id]; // Deleted items get a modify that we have to ignore when // not viewing the trash if (item.deleted) { continue; } // Item already exists in this view if (row !== undefined) { let parentItemID = this.getRow(row).ref.parentItemID; let parentIndex = this.getParentIndex(row); // Top-level item if (this.isContainer(row)) { // If Unfiled Items and itm was added to a collection, remove from view if (collectionTreeRow.isUnfiled() && item.getCollections().length) { this._removeRow(row); } // Otherwise just resort else { sort = id; } } // If item moved from top-level to under another item, remove the old row. else if (parentIndex == -1 && parentItemID) { this._removeRow(row); } // If moved from under another item to top level, remove old row and add new one else if (parentIndex != -1 && !parentItemID) { this._removeRow(row); let beforeRow = this.rowCount; this._addRow(new Zotero.ItemTreeRow(item, 0, false), beforeRow); sort = id; } // If item was moved from one parent to another, remove from old parent else if (parentItemID && parentIndex != -1 && this._rowMap[parentItemID] != parentIndex) { this._removeRow(row); } // If not moved from under one item to another, just resort the row, // which also invalidates it and refreshes it else { sort = id; } madeChanges = true; } // Otherwise, for a top-level item in a library root or a collection // containing the item, the item has to be added else if (item.isTopLevelItem()) { // Root view let add = collectionTreeRow.isLibrary(true) && collectionTreeRow.ref.libraryID == item.libraryID; // Collection containing item if (!add && collectionTreeRow.isCollection()) { add = item.inCollection(collectionTreeRow.ref.id); } if (add) { //most likely, the note or attachment's parent was removed. let beforeRow = this.rowCount; this._addRow(new Zotero.ItemTreeRow(item, 0, false), beforeRow); madeChanges = true; sort = id; } } } if (sort && ids.length != 1) { sort = true; } } // If quicksearch, re-run it, since the results may have changed else { var allDeleted = true; var isTrash = collectionTreeRow.isTrash(); var items = Zotero.Items.get(ids); for each(var item in items) { // If not viewing trash and all items were deleted, ignore modify if (allDeleted && !isTrash && !item.deleted) { allDeleted = false; } } if (!allDeleted) { quicksearch.doCommand(); madeChanges = true; sort = true; } } } else if(type == 'item' && action == 'add') { let items = Zotero.Items.get(ids); // In some modes, just re-run search if (collectionTreeRow.isSearch() || collectionTreeRow.isTrash() || collectionTreeRow.isUnfiled()) { yield this.refresh(); refreshed = true; madeChanges = true; sort = true; } // If not a quicksearch, process new items manually else if (!quicksearch || quicksearch.value == '') { for (let i=0; i<items.length; i++) { let item = items[i]; // if the item belongs in this collection if (((collectionTreeRow.isLibrary(true) && collectionTreeRow.ref.libraryID == item.libraryID) || (collectionTreeRow.isCollection() && item.inCollection(collectionTreeRow.ref.id))) // if we haven't already added it to our hash map && this._rowMap[item.id] == null // Regular item or standalone note/attachment && item.isTopLevelItem()) { let beforeRow = this.rowCount; this._addRow(new Zotero.ItemTreeRow(item, 0, false), beforeRow); madeChanges = true; } } if (madeChanges) { sort = (items.length == 1) ? items[0].id : true; } } // Otherwise re-run the quick search, which refreshes the item list else { // For item adds, clear the quicksearch, unless all the new items have skipSelect or are // child items if (activeWindow && type == 'item') { let clear = false; for (let i=0; i<items.length; i++) { if (!extraData[items[i].id].skipSelect && items[i].isTopLevelItem()) { clear = true; break; } } if (clear) { quicksearch.value = ''; } } quicksearch.doCommand(); madeChanges = true; sort = true; } } if(madeChanges) { // If we made individual changes, we have to clear the cache if (!refreshed) { Zotero.CollectionTreeCache.clear(); } var singleSelect = false; // If adding a single top-level item and this is the active window, select it if (action == 'add' && activeWindow) { if (ids.length == 1) { singleSelect = ids[0]; } // If there's only one parent item in the set of added items, // mark that for selection in the UI // // Only bother checking for single parent item if 1-5 total items, // since a translator is unlikely to save more than 4 child items else if (ids.length <= 5) { var items = Zotero.Items.get(ids); if (items) { var found = false; for each(var item in items) { // Check for note and attachment type, since it's quicker // than checking for parent item if (item.itemTypeID == 1 || item.itemTypeID == 14) { continue; } // We already found a top-level item, so cancel the // single selection if (found) { singleSelect = false; break; } found = true; singleSelect = item.id; } } } } if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshItemRowMap(); } if (singleSelect) { if (!extraData[singleSelect] || !extraData[singleSelect].skipSelect) { // Reset to Info tab this._ownerDocument.getElementById('zotero-view-tabbox').selectedIndex = 0; yield this.selectItem(singleSelect); } } // If single item is selected and was modified else if (action == 'modify' && ids.length == 1 && savedSelection.length == 1 && savedSelection[0] == ids[0]) { // If the item no longer matches the search term, clear the search // DEBUG: Still needed/wanted? (and search is async, so doesn't work anyway, // here or above) if (quicksearch && this._rowMap[ids[0]] == undefined) { Zotero.debug('Selected item no longer matches quicksearch -- clearing'); quicksearch.value = ''; quicksearch.doCommand(); } if (activeWindow) { yield this.selectItem(ids[0]); } else { this.rememberSelection(savedSelection); } } // On removal of a row, select item at previous position else if (savedSelection.length) { if (action == 'remove' || action == 'trash' || action == 'delete') { // In duplicates view, select the next set on delete if (collectionTreeRow.isDuplicates()) { if (this._rows[previousFirstSelectedRow]) { // Mirror ZoteroPane.onTreeMouseDown behavior var itemID = this._rows[previousFirstSelectedRow].ref.id; var setItemIDs = collectionTreeRow.ref.getSetItemsByItemID(itemID); this.selectItems(setItemIDs); } } else { // If this was a child item and the next item at this // position is a top-level item, move selection one row // up to select a sibling or parent if (ids.length == 1 && previousFirstSelectedRow > 0) { let previousItem = Zotero.Items.get(ids[0]); if (previousItem && !previousItem.isTopLevelItem()) { if (this._rows[previousFirstSelectedRow] && this.getLevel(previousFirstSelectedRow) == 0) { previousFirstSelectedRow--; } } } if (previousFirstSelectedRow !== undefined && this._rows[previousFirstSelectedRow]) { this.selection.select(previousFirstSelectedRow); } // If no item at previous position, select last item in list else if (this._rows[this._rows.length - 1]) { this.selection.select(this._rows.length - 1); } } } else { this.rememberSelection(savedSelection); } } this._rememberScrollPosition(scrollPosition); this._treebox.invalidate(); } // For special case in which an item needs to be selected without changes // necessarily having been made // ('collection-item' add with tag selector open) /*else if (selectItem) { yield this.selectItem(selectItem); }*/ //this._treebox.endUpdateBatch(); if (madeChanges) { var deferred = Zotero.Promise.defer(); this.addEventListener('select', () => deferred.resolve()); } this.selection.selectEventsSuppressed = false; if (madeChanges) { Zotero.debug("Yielding for select promise"); // TEMP return deferred.promise; } }); /* * Unregisters view from Zotero.Notifier (called on window close) */ Zotero.ItemTreeView.prototype.unregister = function() { Zotero.Notifier.unregisterObserver(this._unregisterID); if (this.listener) { if (!this._treebox.treeBody) { Zotero.debug("No more tree body in Zotero.ItemTreeView::unregister()"); this.listener = null; return; } let tree = this._treebox.treeBody.parentNode; tree.removeEventListener('keypress', this.listener, false); this.listener = null; } } //////////////////////////////////////////////////////////////////////////////// /// /// nsITreeView functions /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.getCellText = function (row, column) { var obj = this.getRow(row); var itemID = obj.id; // If value is available, retrieve synchronously if (this._cellTextCache[itemID] && this._cellTextCache[itemID][column.id] !== undefined) { return this._cellTextCache[itemID][column.id]; } if (!this._cellTextCache[itemID]) { this._cellTextCache[itemID] = {} } var val; // Image only if (column.id === "zotero-items-column-hasAttachment") { return; } else if(column.id == "zotero-items-column-itemType") { val = Zotero.ItemTypes.getLocalizedString(obj.ref.itemTypeID); } // Year column is just date field truncated else if (column.id == "zotero-items-column-year") { val = obj.getField('date', true).substr(0, 4) } else if (column.id === "zotero-items-column-numNotes") { val = obj.numNotes(); } else { var col = column.id.substring(20); if (col == 'title') { val = obj.ref.getDisplayTitle(); } else { val = obj.getField(col); } } switch (column.id) { // Format dates as short dates in proper locale order and locale time // (e.g. "4/4/07 14:27:23") case 'zotero-items-column-dateAdded': case 'zotero-items-column-dateModified': case 'zotero-items-column-accessDate': case 'zotero-items-column-date': if (column.id == 'zotero-items-column-date' && !this.collectionTreeRow.isFeed()) { break; } if (val) { var order = Zotero.Date.getLocaleDateOrder(); if (order == 'mdy') { order = 'mdy'; var join = '/'; } else if (order == 'dmy') { order = 'dmy'; var join = '/'; } else if (order == 'ymd') { order = 'YMD'; var join = '-'; } var date = Zotero.Date.sqlToDate(val, true); var parts = []; for (var i=0; i<3; i++) { switch (order[i]) { case 'y': parts.push(date.getFullYear().toString().substr(2)); break; case 'Y': parts.push(date.getFullYear()); break; case 'm': parts.push((date.getMonth() + 1)); break; case 'M': parts.push(Zotero.Utilities.lpad((date.getMonth() + 1).toString(), '0', 2)); break; case 'd': parts.push(date.getDate()); break; case 'D': parts.push(Zotero.Utilities.lpad(date.getDate().toString(), '0', 2)); break; } val = parts.join(join); val += ' ' + date.toLocaleTimeString(); } } } return this._cellTextCache[itemID][column.id] = val; } Zotero.ItemTreeView.prototype.getImageSrc = function(row, col) { if(col.id == 'zotero-items-column-title') { // Get item type icon and tag swatches var item = this.getRow(row).ref; var itemID = item.id; if (this._itemImages[itemID]) { return this._itemImages[itemID]; } item.getImageSrcWithTags() .then(function (uriWithTags) { this._itemImages[itemID] = uriWithTags; this._treebox.invalidateCell(row, col); }.bind(this)); return item.getImageSrc(); } else if (col.id == 'zotero-items-column-hasAttachment') { if (this.collectionTreeRow.isTrash()) return false; var treerow = this.getRow(row); var item = treerow.ref; if ((!this.isContainer(row) || !this.isContainerOpen(row)) && Zotero.Sync.Storage.getItemDownloadImageNumber(item)) { return ''; } var itemID = item.id; if (treerow.level === 0) { if (item.isRegularItem()) { let state = item.getBestAttachmentStateCached(); if (state !== null) { switch (state) { case 1: return "chrome://zotero/skin/bullet_blue.png"; case -1: return "chrome://zotero/skin/bullet_blue_empty.png"; default: return ""; } } item.getBestAttachmentState() // Refresh cell when promise is fulfilled .then(function (state) { this._treebox.invalidateCell(row, col); }.bind(this)) .done(); } } if (item.isFileAttachment()) { let exists = item.fileExistsCached(); if (exists !== null) { let suffix = Zotero.hiDPISuffix; return exists ? `chrome://zotero/skin/bullet_blue${suffix}.png` : `chrome://zotero/skin/bullet_blue_empty${suffix}.png`; } item.fileExists() // Refresh cell when promise is fulfilled .then(function (exists) { this._treebox.invalidateCell(row, col); }.bind(this)); } } return ""; } Zotero.ItemTreeView.prototype.isContainer = function(row) { return this.getRow(row).ref.isRegularItem(); } Zotero.ItemTreeView.prototype.isContainerEmpty = function(row) { if (this._sourcesOnly) { return true; } var item = this.getRow(row).ref; if (!item.isRegularItem()) { return false; } var includeTrashed = this.collectionTreeRow.isTrash(); return item.numNotes(includeTrashed) === 0 && item.numAttachments(includeTrashed) == 0; } // Gets the index of the row's container, or -1 if none (top-level) Zotero.ItemTreeView.prototype.getParentIndex = function(row) { if (row==-1) { return -1; } var thisLevel = this.getLevel(row); if(thisLevel == 0) return -1; for(var i = row - 1; i >= 0; i--) if(this.getLevel(i) < thisLevel) return i; return -1; } Zotero.ItemTreeView.prototype.hasNextSibling = function(row,afterIndex) { var thisLevel = this.getLevel(row); for(var i = afterIndex + 1; i < this.rowCount; i++) { var nextLevel = this.getLevel(i); if(nextLevel == thisLevel) return true; else if(nextLevel < thisLevel) return false; } } Zotero.ItemTreeView.prototype.toggleOpenState = function (row, skipRowMapRefresh) { // Shouldn't happen but does if an item is dragged over a closed // container until it opens and then released, since the container // is no longer in the same place when the spring-load closes if (!this.isContainer(row)) { return; } if (this.isContainerOpen(row)) { return this._closeContainer(row, skipRowMapRefresh); } var count = 0; var level = this.getLevel(row); // // Open // var item = this.getRow(row).ref; //Get children var includeTrashed = this.collectionTreeRow.isTrash(); var attachments = item.getAttachments(includeTrashed); var notes = item.getNotes(includeTrashed); var newRows; if (attachments.length && notes.length) { newRows = notes.concat(attachments); } else if (attachments.length) { newRows = attachments; } else if (notes.length) { newRows = notes; } if (newRows) { newRows = Zotero.Items.get(newRows); for (let i = 0; i < newRows.length; i++) { count++; this._addRow( new Zotero.ItemTreeRow(newRows[i], level + 1, false), row + i + 1, true ); } } this._rows[row].isOpen = true; if (count == 0) { return; } this._treebox.invalidateRow(row); if (!skipRowMapRefresh) { Zotero.debug('Refreshing hash map'); this._refreshItemRowMap(); } } Zotero.ItemTreeView.prototype._closeContainer = function (row, skipRowMapRefresh) { // isContainer == false shouldn't happen but does if an item is dragged over a closed // container until it opens and then released, since the container is no longer in the same // place when the spring-load closes if (!this.isContainer(row)) return; if (!this.isContainerOpen(row)) return; var count = 0; var level = this.getLevel(row); // Remove child rows while ((row + 1 < this._rows.length) && (this.getLevel(row + 1) > level)) { // Skip the map update here and just refresh the whole map below, // since we might be removing multiple rows this._removeRow(row + 1, true); count--; } this._rows[row].isOpen = false; if (count == 0) { return; } this._treebox.invalidateRow(row); if (!skipRowMapRefresh) { Zotero.debug('Refreshing hash map'); this._refreshItemRowMap(); } } Zotero.ItemTreeView.prototype.isSorted = function() { // We sort by the first column if none selected, so return true return true; } Zotero.ItemTreeView.prototype.cycleHeader = function (column) { if (this.collectionTreeRow.isFeed()) { return; } for(var i=0, len=this._treebox.columns.count; i<len; i++) { col = this._treebox.columns.getColumnAt(i); if(column != col) { col.element.removeAttribute('sortActive'); col.element.removeAttribute('sortDirection'); } else { // If not yet selected, start with ascending if (!col.element.getAttribute('sortActive')) { col.element.setAttribute('sortDirection', 'ascending'); } else { col.element.setAttribute('sortDirection', col.element.getAttribute('sortDirection') == 'descending' ? 'ascending' : 'descending'); } col.element.setAttribute('sortActive', true); } } this.selection.selectEventsSuppressed = true; var savedSelection = this.getSelectedItems(true); if (savedSelection.length == 1) { var pos = this._rowMap[savedSelection[0]] - this._treebox.getFirstVisibleRow(); } this.sort(); this.rememberSelection(savedSelection); // If single row was selected, try to keep it in the same place if (savedSelection.length == 1) { var newRow = this._rowMap[savedSelection[0]]; // Calculate the last row that would give us a full view var fullTop = Math.max(0, this._rows.length - this._treebox.getPageLength()); // Calculate the row that would give us the same position var consistentTop = Math.max(0, newRow - pos); this._treebox.scrollToRow(Math.min(fullTop, consistentTop)); } this._treebox.invalidate(); this.selection.selectEventsSuppressed = false; } /* * Sort the items by the currently sorted column. */ Zotero.ItemTreeView.prototype.sort = function (itemID) { var t = new Date; // If Zotero pane is hidden, mark tree for sorting later in setTree() if (!this._treebox.columns) { this._needsSort = true; return; } this._needsSort = false; // Single child item sort -- just toggle parent closed and open if (itemID && this._rowMap[itemID] && this.getRow(this._rowMap[itemID]).ref.parentKey) { let parentIndex = this.getParentIndex(this._rowMap[itemID]); this._closeContainer(parentIndex); this.toggleOpenState(parentIndex); return; } var primaryField = this.getSortField(); var sortFields = this.getSortFields(); var dir = this.getSortDirection(); var order = dir == 'descending' ? -1 : 1; var collation = Zotero.getLocaleCollation(); var sortCreatorAsString = Zotero.Prefs.get('sortCreatorAsString'); Zotero.debug("Sorting items list by " + sortFields.join(", ") + " " + dir + (itemID ? " for 1 item" : "")); // Set whether rows with empty values should be displayed last, // which may be different for primary and secondary sorting. var emptyFirst = {}; switch (primaryField) { case 'title': emptyFirst.title = true; break; // When sorting by title we want empty titles at the top, but if not // sorting by title, empty titles should sort to the bottom so that new // empty items don't get sorted to the middle of the items list. default: emptyFirst.title = false; } // Cache primary values while sorting, since base-field-mapped getField() // calls are relatively expensive var cache = {}; sortFields.forEach(function (x) cache[x] = {}) // Get the display field for a row (which might be a placeholder title) function getField(field, row) { var item = row.ref; switch (field) { case 'title': return Zotero.Items.getSortTitle(item.getDisplayTitle()); case 'hasAttachment': if (item.isAttachment()) { var state = item.fileExistsCached() ? 1 : -1; } else if (item.isRegularItem()) { var state = item.getBestAttachmentState(); } else { return 0; } // Make sort order present, missing, empty when ascending if (state === -1) { state = 2; } return state * -1; case 'numNotes': return row.numNotes(false, true) || 0; // Use unformatted part of date strings (YYYY-MM-DD) for sorting case 'date': var val = row.ref.getField('date', true, true); if (val) { val = val.substr(0, 10); if (val.indexOf('0000') == 0) { val = ""; } } return val; case 'year': var val = row.ref.getField('date', true, true); if (val) { val = val.substr(0, 4); if (val == '0000') { val = ""; } } return val; default: return row.ref.getField(field, false, true); } } var includeTrashed = this.collectionTreeRow.isTrash(); function fieldCompare(a, b, sortField) { var aItemID = a.id; var bItemID = b.id; var fieldA = cache[sortField][aItemID]; var fieldB = cache[sortField][bItemID]; switch (sortField) { case 'firstCreator': return creatorSort(a, b); case 'itemType': var typeA = Zotero.ItemTypes.getLocalizedString(a.ref.itemTypeID); var typeB = Zotero.ItemTypes.getLocalizedString(b.ref.itemTypeID); return (typeA > typeB) ? 1 : (typeA < typeB) ? -1 : 0; default: if (fieldA === undefined) { cache[sortField][aItemID] = fieldA = getField(sortField, a); } if (fieldB === undefined) { cache[sortField][bItemID] = fieldB = getField(sortField, b); } // Display rows with empty values last if (!emptyFirst[sortField]) { if(fieldA === '' && fieldB !== '') return 1; if(fieldA !== '' && fieldB === '') return -1; } return collation.compareString(1, fieldA, fieldB); } } var rowSort = function (a, b) { var sortFields = Array.slice(arguments, 2); var sortField; while (sortField = sortFields.shift()) { let cmp = fieldCompare(a, b, sortField); if (cmp !== 0) { return cmp; } } return 0; }; var creatorSortCache = {}; // Regexp to extract the whole string up to an optional "and" or "et al." var andEtAlRegExp = new RegExp( // Extract the beginning of the string in non-greedy mode "^.+?" // up to either the end of the string, "et al." at the end of string + "(?=(?: " + Zotero.getString('general.etAl').replace('.', '\.') + ")?$" // or ' and ' + "| " + Zotero.getString('general.and') + " " + ")" ); function creatorSort(a, b) { var itemA = a.ref; var itemB = b.ref; // // Try sorting by the first name in the firstCreator field, since we already have it // // For sortCreatorAsString mode, just use the whole string // var aItemID = a.id, bItemID = b.id, fieldA = creatorSortCache[aItemID], fieldB = creatorSortCache[bItemID]; var prop = sortCreatorAsString ? 'firstCreator' : 'sortCreator'; var sortStringA = itemA[prop]; var sortStringB = itemB[prop]; if (fieldA === undefined) { let firstCreator = Zotero.Items.getSortTitle(sortStringA); if (sortCreatorAsString) { var fieldA = firstCreator; } else { var matches = andEtAlRegExp.exec(firstCreator); var fieldA = matches ? matches[0] : ''; } creatorSortCache[aItemID] = fieldA; } if (fieldB === undefined) { let firstCreator = Zotero.Items.getSortTitle(sortStringB); if (sortCreatorAsString) { var fieldB = firstCreator; } else { var matches = andEtAlRegExp.exec(firstCreator); var fieldB = matches ? matches[0] : ''; } creatorSortCache[bItemID] = fieldB; } if (fieldA === "" && fieldB === "") { return 0; } // Display rows with empty values last if (fieldA === '' && fieldB !== '') return 1; if (fieldA !== '' && fieldB === '') return -1; return collation.compareString(1, fieldA, fieldB); } // Need to close all containers before sorting if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } var savedSelection = this.getSelectedItems(true); var openItemIDs = this._saveOpenState(true); // Single-row sort if (itemID) { let row = this._rowMap[itemID]; for (let i=0, len=this._rows.length; i<len; i++) { if (i === row) { continue; } let cmp = rowSort.apply(this, [this._rows[i], this._rows[row]].concat(sortFields)) * order; // As soon as we find a value greater (or smaller if reverse sort), // insert row at that position if (cmp > 0) { let rowItem = this._rows.splice(row, 1); this._rows.splice(row < i ? i-1 : i, 0, rowItem[0]); this._treebox.invalidate(); break; } // If greater than last row, move to end if (i == len-1) { let rowItem = this._rows.splice(row, 1); this._rows.splice(i, 0, rowItem[0]); this._treebox.invalidate(); } } } // Full sort else { this._rows.sort(function (a, b) { return rowSort.apply(this, [a, b].concat(sortFields)) * order; }.bind(this)); Zotero.debug("Sorted items list without creators in " + (new Date - t) + " ms"); } this._refreshItemRowMap(); this.rememberOpenState(openItemIDs); this.rememberSelection(savedSelection); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.debug("Sorted items list in " + (new Date - t) + " ms"); }; //////////////////////////////////////////////////////////////////////////////// /// /// Additional functions for managing data in the tree /// //////////////////////////////////////////////////////////////////////////////// /* * Select an item */ Zotero.ItemTreeView.prototype.selectItem = Zotero.Promise.coroutine(function* (id, expand, noRecurse) { // If no row map, we're probably in the process of switching collections, // so store the item to select on the item group for later if (!this._rowMap) { if (this.collectionTreeRow) { this.collectionTreeRow.itemToSelect = { id: id, expand: expand }; Zotero.debug("_rowMap not yet set; not selecting item"); return false; } Zotero.debug('Item group not found and no row map in ItemTreeView.selectItem() -- discarding select', 2); return false; } var selected = this.getSelectedItems(true); if (selected.length == 1 && selected[0] == id) { Zotero.debug("Item " + id + " is already selected"); return true; } var row = this._rowMap[id]; // Get the row of the parent, if there is one var parentRow = null; var item = yield Zotero.Items.getAsync(id); // Can't select a deleted item if we're not in the trash if (item.deleted && !this.collectionTreeRow.isTrash()) { return false; } var parent = item.parentItemID; if (parent && this._rowMap[parent] != undefined) { parentRow = this._rowMap[parent]; } // If row with id not visible, check to see if it's hidden under a parent if(row == undefined) { if (!parent || parentRow === null) { // No parent -- it's not here // Clear the quicksearch and tag selection and try again (once) if (!noRecurse && this._ownerDocument.defaultView.ZoteroPane_Local) { let cleared1 = yield this._ownerDocument.defaultView.ZoteroPane_Local.clearQuicksearch(); let cleared2 = this._ownerDocument.defaultView.ZoteroPane_Local.clearTagSelection(); if (cleared1 || cleared2) { return this.selectItem(id, expand, true); } } Zotero.debug("Could not find row for item; not selecting item"); return false; } // If parent is already open and we haven't found the item, the child // hasn't yet been added to the view, so close parent to allow refresh this._closeContainer(parentRow); // Open the parent this.toggleOpenState(parentRow); row = this._rowMap[id]; } // this.selection.select() triggers the <tree>'s 'onselect' attribute, which calls // ZoteroPane.itemSelected(), which calls ZoteroItemPane.viewItem(), which refreshes the // itembox. But since the 'onselect' doesn't handle promises, itemSelected() isn't waited for // here, which means that 'yield selectItem(itemID)' continues before the itembox has been // refreshed. To get around this, we wait for a select event that's triggered by // itemSelected() when it's done. if (this.selection.selectEventsSuppressed) { this.selection.select(row); } else { var deferred = Zotero.Promise.defer(); this.addEventListener('select', () => deferred.resolve()); this.selection.select(row); } // If |expand|, open row if container if (expand && this.isContainer(row) && !this.isContainerOpen(row)) { this.toggleOpenState(row); } this.selection.select(row); if (deferred) { yield deferred.promise; } // We aim for a row 5 below the target row, since ensureRowIsVisible() does // the bare minimum to get the row in view for (var v = row + 5; v>=row; v--) { if (this._rows[v]) { this._treebox.ensureRowIsVisible(v); if (this._treebox.getFirstVisibleRow() <= row) { break; } } } // If the parent row isn't in view and we have enough room, make parent visible if (parentRow !== null && this._treebox.getFirstVisibleRow() > parentRow) { if ((row - parentRow) < this._treebox.getPageLength()) { this._treebox.ensureRowIsVisible(parentRow); } } return true; }); /** * Select multiple top-level items * * @param {Integer[]} ids An array of itemIDs */ Zotero.ItemTreeView.prototype.selectItems = function(ids) { if (ids.length == 0) { return; } var rows = []; for each(var id in ids) { if(this._rowMap[id] !== undefined) rows.push(this._rowMap[id]); } rows.sort(function (a, b) { return a - b; }); this.selection.clearSelection(); this.selection.selectEventsSuppressed = true; var lastStart = 0; for (var i = 0, len = rows.length; i < len; i++) { if (i == len - 1 || rows[i + 1] != rows[i] + 1) { this.selection.rangedSelect(rows[lastStart], rows[i], true); lastStart = i + 1; } } this.selection.selectEventsSuppressed = false; } /* * Return an array of Item objects for selected items * * If asIDs is true, return an array of itemIDs instead */ Zotero.ItemTreeView.prototype.getSelectedItems = function(asIDs) { var items = [], start = {}, end = {}; for (var i=0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) { if (asIDs) { items.push(this.getRow(j).id); } else { items.push(this.getRow(j).ref); } } } return items; } /** * Delete the selection * * @param {Boolean} [force=false] Delete item even if removing from a collection */ Zotero.ItemTreeView.prototype.deleteSelection = Zotero.Promise.coroutine(function* (force) { if (arguments.length > 1) { throw ("deleteSelection() no longer takes two parameters"); } if (this.selection.count == 0) { return; } //this._treebox.beginUpdateBatch(); // Collapse open items for (var i=0; i<this.rowCount; i++) { if (this.selection.isSelected(i) && this.isContainer(i)) { this._closeContainer(i, true); } } this._refreshItemRowMap(); // Create an array of selected items var ids = []; var start = {}; var end = {}; for (var i=0, len=this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) ids.push(this.getRow(j).id); } var collectionTreeRow = this.collectionTreeRow; if (collectionTreeRow.isBucket()) { collectionTreeRow.ref.deleteItems(ids); } else if (collectionTreeRow.isTrash() || collectionTreeRow.isPublications()) { Zotero.Items.erase(ids); } else if (collectionTreeRow.isLibrary(true) || force) { Zotero.Items.trashTx(ids); } else if (collectionTreeRow.isCollection()) { collectionTreeRow.ref.removeItems(ids); } //this._treebox.endUpdateBatch(); }); /* * Set the search/tags filter on the view */ Zotero.ItemTreeView.prototype.setFilter = Zotero.Promise.coroutine(function* (type, data) { if (!this._treebox || !this._treebox.treeBody) { Components.utils.reportError("Treebox didn't exist in itemTreeView.setFilter()"); return; } this.selection.selectEventsSuppressed = true; //this._treebox.beginUpdateBatch(); switch (type) { case 'search': this.collectionTreeRow.setSearch(data); break; case 'tags': this.collectionTreeRow.setTags(data); break; default: throw ('Invalid filter type in setFilter'); } var oldCount = this.rowCount; yield this.refresh(); this.sort(); //this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; }); /* * Create map of item ids to row indexes */ Zotero.ItemTreeView.prototype._refreshItemRowMap = function() { var rowMap = {}; for (var i=0, len=this.rowCount; i<len; i++) { let row = this.getRow(i); let id = row.ref.id; if (rowMap[id] !== undefined) { Zotero.debug("WARNING: Item row already found", 2); } rowMap[id] = i; } this._rowMap = rowMap; } Zotero.ItemTreeView.prototype.saveSelection = function () { return this.getSelectedItems(true); } /* * Sets the selection based on saved selection ids */ Zotero.ItemTreeView.prototype.rememberSelection = function (selection) { if (!selection.length) { return; } this.selection.clearSelection(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for(var i=0; i < selection.length; i++) { if (this._rowMap[selection[i]] != null) { this.selection.toggleSelect(this._rowMap[selection[i]]); } // Try the parent else { var item = Zotero.Items.get(selection[i]); if (!item) { continue; } var parent = item.parentItemID; if (!parent) { continue; } if (this._rowMap[parent] != null) { this._closeContainer(this._rowMap[parent]); this.toggleOpenState(this._rowMap[parent]); this.selection.toggleSelect(this._rowMap[selection[i]]); } } } if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.selectSearchMatches = function () { if (this._searchMode) { var ids = []; for (var id in this._searchItemIDs) { ids.push(id); } this.rememberSelection(ids); } else { this.selection.clearSelection(); } } Zotero.ItemTreeView.prototype._saveOpenState = function (close) { var itemIDs = []; if (close) { if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } } for (var i=0; i<this._rows.length; i++) { if (this.isContainer(i) && this.isContainerOpen(i)) { itemIDs.push(this.getRow(i).ref.id); if (close) { this._closeContainer(i, true); } } } if (close) { this._refreshItemRowMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } return itemIDs; } Zotero.ItemTreeView.prototype.rememberOpenState = function (itemIDs) { var rowsToOpen = []; for each(var id in itemIDs) { var row = this._rowMap[id]; // Item may not still exist if (row == undefined) { continue; } rowsToOpen.push(row); } rowsToOpen.sort(function (a, b) { return a - b; }); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } // Reopen from bottom up for (var i=rowsToOpen.length-1; i>=0; i--) { this.toggleOpenState(rowsToOpen[i], true); } this._refreshItemRowMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.expandMatchParents = function () { var t = new Date(); var time = 0; // Expand parents of child matches if (!this._searchMode) { return; } var parentIDs = new Set(); for (let id in this._searchParentIDs) { parentIDs.add(parseInt(id)); } if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for (var i=0; i<this.rowCount; i++) { var id = this.getRow(i).ref.id; if (parentIDs.has(id) && this.isContainer(i) && !this.isContainerOpen(i)) { var t2 = new Date(); this.toggleOpenState(i, true); time += (new Date() - t2); } } this._refreshItemRowMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.expandAllRows = function () { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i) && !this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshItemRowMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseAllRows = function () { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i)) { this._closeContainer(i, true); } } this._refreshItemRowMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; }; Zotero.ItemTreeView.prototype.expandSelectedRows = function () { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j) && !this.isContainerOpen(j)) { this.toggleOpenState(j, true); } } } this._refreshItemRowMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseSelectedRows = function () { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j)) { this._closeContainer(j, true); } } } this._refreshItemRowMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.getVisibleFields = function() { var columns = []; for (var i=0, len=this._treebox.columns.count; i<len; i++) { var col = this._treebox.columns.getColumnAt(i); if (col.element.getAttribute('hidden') != 'true') { columns.push(col.id.substring(20)); } } return columns; } /** * Returns an array of items of visible items in current sort order * * @param bool asIDs Return itemIDs * @return array An array of Zotero.Item objects or itemIDs */ Zotero.ItemTreeView.prototype.getSortedItems = function(asIDs) { var items = []; for each(var item in this._rows) { if (asIDs) { items.push(item.ref.id); } else { items.push(item.ref); } } return items; } Zotero.ItemTreeView.prototype.getSortField = function() { if (this.collectionTreeRow.isFeed()) { return 'id'; } var column = this._treebox.columns.getSortedColumn(); if (!column) { column = this._treebox.columns.getFirstColumn(); } // zotero-items-column-_________ return column.id.substring(20); } Zotero.ItemTreeView.prototype.getSortFields = function () { var fields = [this.getSortField()]; var secondaryField = this.getSecondarySortField(); if (secondaryField) { fields.push(secondaryField); } try { var fallbackFields = Zotero.Prefs.get('fallbackSort') .split(',') .map((x) => x.trim()) .filter((x) => x !== ''); } catch (e) { Zotero.debug(e, 1); Components.utils.reportError(e); // This should match the default value for the fallbackSort pref var fallbackFields = ['firstCreator', 'date', 'title', 'dateAdded']; } fields = Zotero.Utilities.arrayUnique(fields.concat(fallbackFields)); // If date appears after year, remove it, unless it's the explicit secondary sort var yearPos = fields.indexOf('year'); if (yearPos != -1) { let datePos = fields.indexOf('date'); if (datePos > yearPos && secondaryField != 'date') { fields.splice(datePos, 1); } } return fields; } /* * Returns 'ascending' or 'descending' */ Zotero.ItemTreeView.prototype.getSortDirection = function() { if (this.collectionTreeRow.isFeed()) { return Zotero.Prefs.get('feeds.sortAscending') ? 'ascending' : 'descending'; } var column = this._treebox.columns.getSortedColumn(); if (!column) { return 'ascending'; } return column.element.getAttribute('sortDirection'); } Zotero.ItemTreeView.prototype.getSecondarySortField = function () { var primaryField = this.getSortField(); var secondaryField = Zotero.Prefs.get('secondarySort.' + primaryField); if (!secondaryField || secondaryField == primaryField) { return false; } return secondaryField; } Zotero.ItemTreeView.prototype.setSecondarySortField = function (secondaryField) { var primaryField = this.getSortField(); var currentSecondaryField = this.getSecondarySortField(); var sortFields = this.getSortFields(); if (primaryField == secondaryField) { return false; } if (currentSecondaryField) { // If same as the current explicit secondary sort, ignore if (currentSecondaryField == secondaryField) { return false; } // If not, but same as first implicit sort, remove current explicit sort if (sortFields[2] && sortFields[2] == secondaryField) { Zotero.Prefs.clear('secondarySort.' + primaryField); return true; } } // If same as current implicit secondary sort, ignore else if (sortFields[1] && sortFields[1] == secondaryField) { return false; } Zotero.Prefs.set('secondarySort.' + primaryField, secondaryField); return true; } /** * Build the More Columns and Secondary Sort submenus while the popup is opening */ Zotero.ItemTreeView.prototype.onColumnPickerShowing = function (event) { var menupopup = event.originalTarget; var ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; var prefix = 'zotero-column-header-'; var doc = menupopup.ownerDocument; var anonid = menupopup.getAttribute('anonid'); if (anonid.indexOf(prefix) == 0) { return; } var lastChild = menupopup.lastChild; try { // More Columns menu let id = prefix + 'more-menu'; let moreMenu = doc.createElementNS(ns, 'menu'); moreMenu.setAttribute('label', Zotero.getString('pane.items.columnChooser.moreColumns')); moreMenu.setAttribute('anonid', id); let moreMenuPopup = doc.createElementNS(ns, 'menupopup'); moreMenuPopup.setAttribute('anonid', id + '-popup'); let treecols = menupopup.parentNode.parentNode; let subs = Array.from(treecols.getElementsByAttribute('submenu', 'true')) .map(x => x.getAttribute('label')); var moreItems = []; for (let i=0; i<menupopup.childNodes.length; i++) { let elem = menupopup.childNodes[i]; if (elem.localName == 'menuseparator') { break; } if (elem.localName == 'menuitem' && subs.indexOf(elem.getAttribute('label')) != -1) { moreItems.push(elem); } } // Sort fields and move to submenu var collation = Zotero.getLocaleCollation(); moreItems.sort(function (a, b) { return collation.compareString(1, a.getAttribute('label'), b.getAttribute('label')); }); moreItems.forEach(function (elem) { moreMenuPopup.appendChild(menupopup.removeChild(elem)); }); moreMenu.appendChild(moreMenuPopup); menupopup.insertBefore(moreMenu, lastChild); // Disable certain entries for feeds let elems = Array.from(treecols.getElementsByAttribute('hidden-in', '*')) let labels = Array.from(elems) .filter(e => e.getAttribute('hidden-in').split(' ').indexOf(this.collectionTreeRow.type) != -1) .map(e => e.getAttribute('label')); for (let i = 0; i < menupopup.childNodes.length; i++) { let elem = menupopup.childNodes[i]; elem.setAttribute('disabled', labels.indexOf(elem.getAttribute('label')) != -1); } } catch (e) { Components.utils.reportError(e); Zotero.debug(e, 1); } // // Secondary Sort menu // if (!this.collectionTreeRow.isFeed()) { try { let id = prefix + 'sort-menu'; let primaryField = this.getSortField(); let sortFields = this.getSortFields(); let secondaryField = false; if (sortFields[1]) { secondaryField = sortFields[1]; } // Get localized names from treecols, since the names are currently done via .dtd let treecols = menupopup.parentNode.parentNode; let primaryFieldLabel = treecols.getElementsByAttribute('id', 'zotero-items-column-' + primaryField)[0].getAttribute('label'); let sortMenu = doc.createElementNS(ns, 'menu'); sortMenu.setAttribute('label', Zotero.getString('pane.items.columnChooser.secondarySort', primaryFieldLabel)); sortMenu.setAttribute('anonid', id); let sortMenuPopup = doc.createElementNS(ns, 'menupopup'); sortMenuPopup.setAttribute('anonid', id + '-popup'); // Generate menuitems let sortOptions = [ 'title', 'firstCreator', 'itemType', 'date', 'year', 'publisher', 'publicationTitle', 'dateAdded', 'dateModified' ]; for (let i=0; i<sortOptions.length; i++) { let field = sortOptions[i]; // Hide current primary field, and don't show Year for Date, since it would be a no-op if (field == primaryField || (primaryField == 'date' && field == 'year')) { continue; } let label = treecols.getElementsByAttribute('id', 'zotero-items-column-' + field)[0].getAttribute('label'); let sortMenuItem = doc.createElementNS(ns, 'menuitem'); sortMenuItem.setAttribute('fieldName', field); sortMenuItem.setAttribute('label', label); sortMenuItem.setAttribute('type', 'checkbox'); if (field == secondaryField) { sortMenuItem.setAttribute('checked', 'true'); } sortMenuItem.setAttribute('oncommand', 'var view = ZoteroPane.itemsView; ' + 'if (view.setSecondarySortField(this.getAttribute("fieldName"))) { view.sort(); }'); sortMenuPopup.appendChild(sortMenuItem); } sortMenu.appendChild(sortMenuPopup); menupopup.insertBefore(sortMenu, lastChild); } catch (e) { Components.utils.reportError(e); Zotero.debug(e, 1); } } sep = doc.createElementNS(ns, 'menuseparator'); sep.setAttribute('anonid', prefix + 'sep'); menupopup.insertBefore(sep, lastChild); } Zotero.ItemTreeView.prototype.onColumnPickerHidden = function (event) { var menupopup = event.originalTarget; var prefix = 'zotero-column-header-'; for (let i=0; i<menupopup.childNodes.length; i++) { let elem = menupopup.childNodes[i]; if (elem.getAttribute('anonid').indexOf(prefix) == 0) { try { menupopup.removeChild(elem); } catch (e) { Zotero.debug(e, 1); } i--; } } } //////////////////////////////////////////////////////////////////////////////// /// /// Command Controller: /// for Select All, etc. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeCommandController = function(tree) { this.tree = tree; } Zotero.ItemTreeCommandController.prototype.supportsCommand = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.isCommandEnabled = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.doCommand = function (cmd) { if (cmd == 'cmd_selectAll') { if (this.tree.view.wrappedJSObject.collectionTreeRow.isSearchMode()) { this.tree.view.wrappedJSObject.selectSearchMatches(); } else { this.tree.view.selection.selectAll(); } } } Zotero.ItemTreeCommandController.prototype.onEvent = function(evt) { } //////////////////////////////////////////////////////////////////////////////// /// /// Drag-and-drop functions /// //////////////////////////////////////////////////////////////////////////////// /** * Start a drag using HTML 5 Drag and Drop */ Zotero.ItemTreeView.prototype.onDragStart = function (event) { // See note in LibraryTreeView::_setDropEffect() if (Zotero.isWin) { event.dataTransfer.effectAllowed = 'copyMove'; } var itemIDs = this.getSelectedItems(true); event.dataTransfer.setData("zotero/item", itemIDs); var items = Zotero.Items.get(itemIDs); // Multi-file drag // - Doesn't work on Windows if (!Zotero.isWin) { // If at least one file is a non-web-link attachment and can be found, // enable dragging to file system for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL && items[i].getFile()) { Zotero.debug("Adding file via x-moz-file-promise"); event.dataTransfer.mozSetDataAt( "application/x-moz-file-promise", new Zotero.ItemTreeView.fileDragDataProvider(), 0 ); break; } } } // Copy first file on Windows else { var index = 0; for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].getAttachmentLinkMode() != Zotero.Attachments.LINK_MODE_LINKED_URL) { var file = items[i].getFile(); if (!file) { continue; } var fph = Components.classes["@mozilla.org/network/protocol;1?name=file"] .createInstance(Components.interfaces.nsIFileProtocolHandler); var uri = fph.getURLSpecFromFile(file); event.dataTransfer.mozSetDataAt("text/x-moz-url", uri + "\n" + file.leafName, index); event.dataTransfer.mozSetDataAt("application/x-moz-file", file, index); event.dataTransfer.mozSetDataAt("application/x-moz-file-promise-url", uri, index); // DEBUG: possible to drag multiple files without x-moz-file-promise? break; index++ } } } // Get Quick Copy format for current URL var url = this._ownerDocument.defaultView.content && this._ownerDocument.defaultView.content.location ? this._ownerDocument.defaultView.content.location.href : null; var format = Zotero.QuickCopy.getFormatFromURL(url); Zotero.debug("Dragging with format " + format); var exportCallback = function(obj, worked) { if (!worked) { Zotero.log(Zotero.getString("fileInterface.exportError"), 'warning'); return; } var text = obj.string.replace(/\r\n/g, "\n"); event.dataTransfer.setData("text/plain", text); } format = Zotero.QuickCopy.unserializeSetting(format); try { if (format.mode == 'export') { Zotero.QuickCopy.getContentFromItems(items, format, exportCallback); } else if (format.mode == 'bibliography') { var content = Zotero.QuickCopy.getContentFromItems(items, format, null, event.shiftKey); if (content) { if (content.html) { event.dataTransfer.setData("text/html", content.html); } event.dataTransfer.setData("text/plain", content.text); } } else { Components.utils.reportError("Invalid Quick Copy mode"); } } catch (e) { Zotero.debug(e); Components.utils.reportError(e + " with '" + format.id + "'"); } }; // Implements nsIFlavorDataProvider for dragging attachment files to OS // // Not used on Windows in Firefox 3 or higher Zotero.ItemTreeView.fileDragDataProvider = function() { }; Zotero.ItemTreeView.fileDragDataProvider.prototype = { QueryInterface : function(iid) { if (iid.equals(Components.interfaces.nsIFlavorDataProvider) || iid.equals(Components.interfaces.nsISupports)) { return this; } throw Components.results.NS_NOINTERFACE; }, getFlavorData : function(transferable, flavor, data, dataLen) { if (flavor == "application/x-moz-file-promise") { // On platforms other than OS X, the only directory we know of here // is the system temp directory, and we pass the nsIFile of the file // copied there in data.value below var useTemp = !Zotero.isMac; // Get the destination directory var dirPrimitive = {}; var dataSize = {}; transferable.getTransferData("application/x-moz-file-promise-dir", dirPrimitive, dataSize); var destDir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile); // Get the items we're dragging var items = {}; transferable.getTransferData("zotero/item", items, dataSize); items.value.QueryInterface(Components.interfaces.nsISupportsString); var draggedItems = Zotero.Items.get(items.value.data.split(',')); var items = []; // Make sure files exist var notFoundNames = []; for (var i=0; i<draggedItems.length; i++) { // TODO create URL? if (!draggedItems[i].isAttachment() || draggedItems[i].getAttachmentLinkMode() == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } if (draggedItems[i].getFile()) { items.push(draggedItems[i]); } else { notFoundNames.push(draggedItems[i].getField('title')); } } // If using the temp directory, create a directory to store multiple // files, since we can (it seems) only pass one nsIFile in data.value if (useTemp && items.length > 1) { var tmpDirName = 'Zotero Dragged Files'; destDir.append(tmpDirName); if (destDir.exists()) { destDir.remove(true); } destDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755); } var copiedFiles = []; var existingItems = []; var existingFileNames = []; for (var i=0; i<items.length; i++) { // TODO create URL? if (!items[i].isAttachment() || items[i].attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } var file = items[i].getFile(); // Determine if we need to copy multiple files for this item // (web page snapshots) if (items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_FILE) { var parentDir = file.parent; var files = parentDir.directoryEntries; var numFiles = 0; while (files.hasMoreElements()) { var f = files.getNext(); f.QueryInterface(Components.interfaces.nsILocalFile); if (f.leafName.indexOf('.') != 0) { numFiles++; } } } // Create folder if multiple files if (numFiles > 1) { var dirName = Zotero.Attachments.getFileBaseNameFromItem(items[i]); try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(dirName); if (copiedFile.exists()) { // If item directory already exists in the temp dir, // delete it if (items.length == 1) { copiedFile.remove(true); } // If item directory exists in the container // directory, it's a duplicate, so give this one // a different name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } parentDir.copyToFollowingLinks(destDir, newName ? newName : dirName); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { // Keep track of items that already existed existingItems.push(items[i].id); existingFileNames.push(dirName); } else { throw (e); } } } // Otherwise just copy else { try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(file.leafName); if (copiedFile.exists()) { // If file exists in the temp directory, // delete it if (items.length == 1) { copiedFile.remove(true); } // If file exists in the container directory, // it's a duplicate, so give this one a different // name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } file.copyToFollowingLinks(destDir, newName ? newName : null); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { existingItems.push(items[i].id); existingFileNames.push(items[i].getFile().leafName); } else { throw (e); } } } } // Files passed via data.value will be automatically moved // from the temp directory to the destination directory if (useTemp && copiedFiles.length) { if (items.length > 1) { data.value = destDir.QueryInterface(Components.interfaces.nsISupports); } else { data.value = copiedFiles[0].QueryInterface(Components.interfaces.nsISupports); } dataLen.value = 4; } if (notFoundNames.length || existingItems.length) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); } // Display alert if files were not found if (notFoundNames.length > 0) { // On platforms that use a temporary directory, an alert here // would interrupt the dragging process, so we just log a // warning to the console if (useTemp) { for (let name of notFoundNames) { var msg = "Attachment file for dragged item '" + name + "' not found"; Zotero.log(msg, 'warning', 'chrome://zotero/content/xpcom/itemTreeView.js'); } } else { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.filesNotFound') + "\n\n" + notFoundNames.join("\n")); } } // Display alert if existing files were skipped if (existingItems.length > 0) { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.existingFiles') + "\n\n" + existingFileNames.join("\n")); } } } } /** * Called by treechildren.onDragOver() before setting the dropEffect, * which is checked in libraryTreeView.canDrop() */ Zotero.ItemTreeView.prototype.canDropCheck = function (row, orient, dataTransfer) { //Zotero.debug("Row is " + row + "; orient is " + orient); var dragData = Zotero.DragDrop.getDataFromDataTransfer(dataTransfer); if (!dragData) { Zotero.debug("No drag data"); return false; } var dataType = dragData.dataType; var data = dragData.data; var collectionTreeRow = this.collectionTreeRow; if (row != -1 && orient == 0) { var rowItem = this.getRow(row).ref; // the item we are dragging over } if (dataType == 'zotero/item') { let items = Zotero.Items.get(data); // Directly on a row if (rowItem) { var canDrop = false; for each(var item in items) { // If any regular items, disallow drop if (item.isRegularItem()) { return false; } // Disallow cross-library child drag if (item.libraryID != collectionTreeRow.ref.libraryID) { return false; } // Only allow dragging of notes and attachments // that aren't already children of the item if (item.parentItemID != rowItem.id) { canDrop = true; } } return canDrop; } // In library, allow children to be dragged out of parent else if (collectionTreeRow.isLibrary(true) || collectionTreeRow.isCollection()) { for each(var item in items) { // Don't allow drag if any top-level items if (item.isTopLevelItem()) { return false; } // Don't allow web attachments to be dragged out of parents, // but do allow PDFs for now so they can be recognized if (item.isWebAttachment() && item.attachmentContentType != 'application/pdf') { return false; } // Don't allow children to be dragged within their own parents var parentItemID = item.parentItemID; var parentIndex = this._rowMap[parentItemID]; if (row != -1 && this.getLevel(row) > 0) { if (this.getRow(this.getParentIndex(row)).ref.id == parentItemID) { return false; } } // Including immediately after the parent if (orient == 1) { if (row == parentIndex) { return false; } } // And immediately before the next parent if (orient == -1) { var nextParentIndex = null; for (var i = parentIndex + 1; i < this.rowCount; i++) { if (this.getLevel(i) == 0) { nextParentIndex = i; break; } } if (row === nextParentIndex) { return false; } } // Disallow cross-library child drag if (item.libraryID != collectionTreeRow.ref.libraryID) { return false; } } return true; } return false; } else if (dataType == "text/x-moz-url" || dataType == 'application/x-moz-file') { // Disallow direct drop on a non-regular item (e.g. note) if (rowItem) { if (!rowItem.isRegularItem()) { return false; } } // Don't allow drop into searches else if (collectionTreeRow.isSearch()) { return false; } return true; } return false; }; /* * Called when something's been dropped on or next to a row */ Zotero.ItemTreeView.prototype.drop = Zotero.Promise.coroutine(function* (row, orient, dataTransfer) { if (!this.canDrop(row, orient, dataTransfer)) { return false; } var dragData = Zotero.DragDrop.getDataFromDataTransfer(dataTransfer); if (!dragData) { Zotero.debug("No drag data"); return false; } var dropEffect = dragData.dropEffect; var dataType = dragData.dataType; var data = dragData.data; var sourceCollectionTreeRow = Zotero.DragDrop.getDragSource(dataTransfer); var collectionTreeRow = this.collectionTreeRow; var targetLibraryID = collectionTreeRow.ref.libraryID; if (dataType == 'zotero/item') { var ids = data; var items = Zotero.Items.get(ids); if (items.length < 1) { return; } // TEMP: This is always false for now, since cross-library drag // is disallowed in canDropCheck() // // TODO: support items coming from different sources? if (items[0].libraryID == targetLibraryID) { var sameLibrary = true; } else { var sameLibrary = false; } var toMove = []; // Dropped directly on a row if (orient == 0) { // Set drop target as the parent item for dragged items // // canDrop() limits this to child items var rowItem = this.getRow(row).ref; // the item we are dragging over yield Zotero.DB.executeTransaction(function* () { for (let i=0; i<items.length; i++) { let item = items[i]; item.parentID = rowItem.id; yield item.save(); } }); } // Dropped outside of a row else { // Remove from parent and make top-level if (collectionTreeRow.isLibrary(true)) { yield Zotero.DB.executeTransaction(function* () { for (let i=0; i<items.length; i++) { let item = items[i]; if (!item.isRegularItem()) { item.parentID = false; yield item.save() } } }); } // Add to collection else { yield Zotero.DB.executeTransaction(function* () { for (let i=0; i<items.length; i++) { let item = items[i]; var source = item.isRegularItem() ? false : item.parentItemID; // Top-level item if (source) { item.parentID = false; item.addToCollection(collectionTreeRow.ref.id); yield item.save(); } else { item.addToCollection(collectionTreeRow.ref.id); yield item.save(); } toMove.push(item.id); } }); } } // If moving, remove items from source collection if (dropEffect == 'move' && toMove.length) { if (!sameLibrary) { throw new Error("Cannot move items between libraries"); } if (!sourceCollectionTreeRow || !sourceCollectionTreeRow.isCollection()) { throw new Error("Drag source must be a collection"); } if (collectionTreeRow.id != sourceCollectionTreeRow.id) { yield collectionTreeRow.ref.removeItems(toMove); } } } else if (dataType == 'text/x-moz-url' || dataType == 'application/x-moz-file') { // Disallow drop into read-only libraries if (!collectionTreeRow.editable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryMessage(); return; } var targetLibraryID = collectionTreeRow.ref.libraryID; var parentItemID = false; var parentCollectionID = false; if (orient == 0) { let treerow = this.getRow(row); parentItemID = treerow.ref.id } else if (collectionTreeRow.isCollection()) { var parentCollectionID = collectionTreeRow.ref.id; } var notifierQueue = new Zotero.Notifier.Queue; try { for (var i=0; i<data.length; i++) { var file = data[i]; if (dataType == 'text/x-moz-url') { var url = data[i]; if (url.indexOf('file:///') == 0) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); // If dragging currently loaded page, only convert to // file if not an HTML document if (win.content.location.href != url || win.content.document.contentType != 'text/html') { var nsIFPH = Components.classes["@mozilla.org/network/protocol;1?name=file"] .getService(Components.interfaces.nsIFileProtocolHandler); try { var file = nsIFPH.getFileFromURLSpec(url); } catch (e) { Zotero.debug(e); } } } // Still string, so remote URL if (typeof file == 'string') { if (parentItemID) { if (!collectionTreeRow.filesEditable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryFilesMessage(); return; } yield Zotero.Attachments.importFromURL({ libraryID: targetLibraryID, url, parentItemID, saveOptions: { notifierQueue } }); } else { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.addItemFromURL(url, 'temporaryPDFHack'); // TODO: don't do this } continue; } // Otherwise file, so fall through } if (dropEffect == 'link') { yield Zotero.Attachments.linkFromFile({ file, parentItemID, collections: parentCollectionID ? [parentCollectionID] : undefined, saveOptions: { notifierQueue } }); } else { if (file.leafName.endsWith(".lnk")) { let wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); let win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotAddShortcutMessage(file.path); continue; } yield Zotero.Attachments.importFromFile({ file, libraryID: targetLibraryID, parentItemID, collections: parentCollectionID ? [parentCollectionID] : undefined, saveOptions: { notifierQueue } }); // If moving, delete original file if (dragData.dropEffect == 'move') { try { file.remove(false); } catch (e) { Components.utils.reportError("Error deleting original file " + file.path + " after drag"); } } } } } finally { yield Zotero.Notifier.commit(notifierQueue); } } }); //////////////////////////////////////////////////////////////////////////////// /// /// Functions for nsITreeView that we have to stub out. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.isSeparator = function(row) { return false; } Zotero.ItemTreeView.prototype.isSelectable = function (row, col) { return true; } Zotero.ItemTreeView.prototype.getRowProperties = function(row, prop) {} Zotero.ItemTreeView.prototype.getColumnProperties = function(col, prop) {} Zotero.ItemTreeView.prototype.getCellProperties = function(row, col, prop) { var treeRow = this.getRow(row); var itemID = treeRow.ref.id; var props = []; // Mark items not matching search as context rows, displayed in gray if (this._searchMode && !this._searchItemIDs[itemID]) { props.push("contextRow"); } // Mark hasAttachment column, which needs special image handling if (col.id == 'zotero-items-column-hasAttachment') { props.push("hasAttachment"); // Don't show pie for open parent items, since we show it for the // child item if (!this.isContainer(row) || !this.isContainerOpen(row)) { var num = Zotero.Sync.Storage.getItemDownloadImageNumber(treeRow.ref); //var num = Math.round(new Date().getTime() % 10000 / 10000 * 64); if (num !== false) props.push("pie", "pie" + num); } } // Style unread items in feeds if (treeRow.ref.isFeedItem && !treeRow.ref.isRead) props.push('unread'); return props.join(" "); } Zotero.ItemTreeRow = function(ref, level, isOpen) { this.ref = ref; //the item associated with this this.level = level; this.isOpen = isOpen; this.id = ref.id; } Zotero.ItemTreeRow.prototype.getField = function(field, unformatted) { return this.ref.getField(field, unformatted, true); } Zotero.ItemTreeRow.prototype.numNotes = function() { if (this.ref.isNote()) { return ''; } return this.ref.numNotes(false, true) || ''; }
agpl-3.0
zvini/website
www/places/fns/sort_panel.php
1274
<?php function sort_panel ($user, $total, $base = '') { if ($total < 2) return; $order_by = $user->places_order_by; $fnsDir = __DIR__.'/../../fns'; include_once "$fnsDir/ItemList/escapedPageQuery.php"; $escapedPageQuery = ItemList\escapedPageQuery(); $title = 'Created time'; if ($order_by === 'insert_time desc') $title .= ' (Current)'; include_once "$fnsDir/Page/imageLink.php"; $insertTimeLink = Page\imageLink($title, "{$base}submit-sort-created.php$escapedPageQuery", 'sort-time'); $title = 'Last modified time'; if ($order_by === 'update_time desc, insert_time desc') { $title .= ' (Current)'; } $updateTimeLink = Page\imageLink($title, "{$base}submit-sort-last-modified.php$escapedPageQuery", 'sort-time'); $title = 'Name'; if ($order_by === 'name, insert_time desc') $title .= ' (Current)'; $nameLink = Page\imageLink($title, "{$base}submit-sort-name.php$escapedPageQuery", 'sort-time'); include_once "$fnsDir/Page/twoColumns.php"; $content = Page\twoColumns($nameLink, $updateTimeLink) .'<div class="hr"></div>' . $insertTimeLink; include_once "$fnsDir/Page/panel.php"; return Page\panel('Sort Places By', $content); }
agpl-3.0
Comunitea/CMNT_004_15
project-addons/sale_product_customize/wizard/__init__.py
157
# © 2019 Comunitea # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import mrp_customization_wizard from . import mrp_product_produce
agpl-3.0
tymiles003/system
application/controllers/Action/Activity.php
1416
<?php /** * @package Billing * @copyright Copyright (C) 2012-2013 S.D.O.C. LTD. All rights reserved. * @license GNU Affero General Public License Version 3; see LICENSE.txt */ require_once APPLICATION_PATH . '/application/controllers/Action/Api.php'; /** * Activity action class * * @package Action * * @since 2.6 */ class ActivityAction extends ApiAction { public function execute() { Billrun_Factory::log()->log("Execute activity call", Zend_Log::INFO); $request = $this->getRequest(); $sid = (int) $request->get('sid', 0); if (empty($sid)) { return $this->setError('Subscriber not exists', $request); } $include_incoming = (int) $request->get('include_incoming', 0); $include_outgoing = (int) $request->get('include_outgoing', 0); $include_sms = (int) $request->get('include_sms', 0); $from_date = $request->get('from_date', time()-30*3600); $to_date = $request->get('to_date', time()); if (!is_numeric($from_date)) { $from_date = strtotime($from_date); } if (!is_numeric($to_date)) { $to_date = strtotime($to_date); } $model = new LinesModel(); $results = $model->getActivity($sid, $from_date, $to_date, $include_outgoing, $include_incoming, $include_sms); $this->getController()->setOutput(array(array( 'status' => 1, 'desc' => 'success', 'details' => $results, 'input' => $request, ))); } }
agpl-3.0
brimstone/cookbook-chef
metadata.rb
17
version "0.0.15"
agpl-3.0
dokterbob/django-shopkit
shopkit/core/forms.py
1726
# Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-shopkit. # # django-shopkit is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero 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. from django import forms from shopkit.core.utils import get_model_from_string from shopkit.core.settings import PRODUCT_MODEL from django.utils.functional import SimpleLazyObject """ Core form classes. """ def get_product_choices(): """ Get available products for shopping cart. This has to be wrapped in a SimpleLazyObject, otherwise Sphinx will complain in the worst ways. """ product_class = get_model_from_string(PRODUCT_MODEL) return product_class.in_shop.all() product_choices = SimpleLazyObject(get_product_choices) """ get_product_choices wrapped up in a SimpleLazyObject. """ class CartItemAddForm(forms.Form): """ Form for adding CartItems to a Cart. """ product = forms.ModelChoiceField(queryset=product_choices, widget=forms.HiddenInput) quantity = forms.IntegerField(min_value=1, initial=1)
agpl-3.0
GTI-Learning/LdShake
views/default/output/pulldown.php
441
<?php /** * Elgg pulldown display * Displays a value that was entered into the system via a pulldown * * @package Elgg * @subpackage Core * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Curverider Ltd * @copyright Curverider Ltd 2008 * @link http://elgg.org/ * * @uses $vars['text'] The text to display * */ echo $vars['value']; ?>
agpl-3.0
castlegateit/cgit-wp-user-guide
classes/Cgit/UserGuide/Guide.php
3182
<?php namespace Cgit\UserGuide; /** * User guide * * Assembles the user guide from all its component sections and renders or * prints it as HTML. */ class Guide { /** * User guide page title * * @var string */ private $title = 'About'; /** * Include a table of contents? * * @var boolean */ private $index = true; /** * Raw section data * * The original, unmodified section data as a multidimensional array which * can be amended using WordPress filters. * * @var array */ private $raws = []; /** * Section instances * * The processed and sanitized section data as an array of Section * instances, with the correct headings, content, and sort orders. * * @var array */ private $sections = []; /** * Constructor * * Apply filters to the default page title and table of contents boolean * value, add and/or edit raw section data using a filter, and generate the * list of sanitized section instances from the raw section data. * * @return void */ public function __construct() { $prefix = 'cgit_user_guide_'; $this->title = 'About ' . get_option('blogname'); // Apply filters to default values $this->title = apply_filters($prefix . 'page_title', $this->title); $this->index = apply_filters($prefix . 'has_index', $this->index); $this->raws = apply_filters($prefix . 'sections', $this->raws); // Generate the sanitized section instances $this->generateSectionInstances(); } /** * Generate and sort sanitized section instances from raw section data * * @return void */ private function generateSectionInstances() { foreach ($this->raws as $key => $args) { $this->sections[$key] = new Section($key, $args); } uasort($this->sections, function ($a, $b) { if ($a->order == $b->order) { return 0; } return $a->order < $b->order ? -1 : 1; }); } /** * Render the user guide as HTML * * @return string */ public function render() { $sections = []; // If it is enabled, the first section in the user guide should be the // table of contents. if ($this->index) { $sections[] = (new Index($this->sections))->render(); } // Render each section as HTML and append them to the array of sections // to be output. foreach ($this->sections as $instance) { $sections[] = $instance->render(); } // Render the complete user guide based on the appropriate template from // the views directory. $template = new Template('guide', [ $this->title, implode(PHP_EOL, $sections), ]); return apply_filters('cgit_user_guide', $template->render()); } /** * Print the user guide as HTML * * @return void */ public function publish() { echo $this->render(); } }
agpl-3.0
gangadharkadam/office_erp
erpnext/selling/doctype/customer/customer.py
6472
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.model.naming import make_autoname from frappe import msgprint, _ import frappe.defaults from erpnext.utilities.transaction_base import TransactionBase from erpnext.accounts.party import create_party_account class Customer(TransactionBase): def autoname(self): cust_master_name = frappe.defaults.get_global_default('cust_master_name') if cust_master_name == 'Customer Name': if frappe.db.exists("Supplier", self.customer_name): msgprint(_("A Supplier exists with same name"), raise_exception=1) self.name = self.customer_name else: self.name = make_autoname(self.naming_series+'.#####') def get_company_abbr(self): return frappe.db.get_value('Company', self.company, 'abbr') def validate_values(self): if frappe.defaults.get_global_default('cust_master_name') == 'Naming Series' and not self.naming_series: frappe.throw(_("Series is mandatory"), frappe.MandatoryError) def validate(self): self.validate_values() def update_lead_status(self): if self.lead_name: frappe.db.sql("update `tabLead` set status='Converted' where name = %s", self.lead_name) def update_address(self): frappe.db.sql("""update `tabAddress` set customer_name=%s, modified=NOW() where customer=%s""", (self.customer_name, self.name)) def update_contact(self): frappe.db.sql("""update `tabContact` set customer_name=%s, modified=NOW() where customer=%s""", (self.customer_name, self.name)) def update_credit_days_limit(self): frappe.db.sql("""update tabAccount set credit_days = %s, credit_limit = %s where master_type='Customer' and master_name = %s""", (self.credit_days or 0, self.credit_limit or 0, self.name)) def create_lead_address_contact(self): if self.lead_name: if not frappe.db.get_value("Address", {"lead": self.lead_name, "customer": self.name}): frappe.db.sql("""update `tabAddress` set customer=%s, customer_name=%s where lead=%s""", (self.name, self.customer_name, self.lead_name)) lead = frappe.db.get_value("Lead", self.lead_name, ["lead_name", "email_id", "phone", "mobile_no"], as_dict=True) c = frappe.new_doc('Contact') c.first_name = lead.lead_name c.email_id = lead.email_id c.phone = lead.phone c.mobile_no = lead.mobile_no c.customer = self.name c.customer_name = self.customer_name c.is_primary_contact = 1 c.ignore_permissions = getattr(self, "ignore_permissions", None) c.autoname() if not frappe.db.exists("Contact", c.name): c.insert() def on_update(self): self.validate_name_with_customer_group() self.update_lead_status() self.update_address() self.update_contact() # create account head create_party_account(self.name, "Customer", self.company) # update credit days and limit in account self.update_credit_days_limit() #create address and contact from lead self.create_lead_address_contact() def validate_name_with_customer_group(self): if frappe.db.exists("Customer Group", self.name): frappe.throw(_("A Customer Group exists with same name please change the Customer name or rename the Customer Group")) def delete_customer_address(self): addresses = frappe.db.sql("""select name, lead from `tabAddress` where customer=%s""", (self.name,)) for name, lead in addresses: if lead: frappe.db.sql("""update `tabAddress` set customer=null, customer_name=null where name=%s""", name) else: frappe.db.sql("""delete from `tabAddress` where name=%s""", name) def delete_customer_contact(self): for contact in frappe.db.sql_list("""select name from `tabContact` where customer=%s""", self.name): frappe.delete_doc("Contact", contact) def delete_customer_account(self): """delete customer's ledger if exist and check balance before deletion""" acc = frappe.db.sql("select name from `tabAccount` where master_type = 'Customer' \ and master_name = %s and docstatus < 2", self.name) if acc: frappe.delete_doc('Account', acc[0][0]) def on_trash(self): self.delete_customer_address() self.delete_customer_contact() self.delete_customer_account() if self.lead_name: frappe.db.sql("update `tabLead` set status='Interested' where name=%s",self.lead_name) def before_rename(self, olddn, newdn, merge=False): from erpnext.accounts.utils import rename_account_for rename_account_for("Customer", olddn, newdn, merge, self.company) def after_rename(self, olddn, newdn, merge=False): set_field = '' if frappe.defaults.get_global_default('cust_master_name') == 'Customer Name': frappe.db.set(self, "customer_name", newdn) self.update_contact() set_field = ", customer_name=%(newdn)s" self.update_customer_address(newdn, set_field) def update_customer_address(self, newdn, set_field): frappe.db.sql("""update `tabAddress` set address_title=%(newdn)s {set_field} where customer=%(newdn)s"""\ .format(set_field=set_field), ({"newdn": newdn})) @frappe.whitelist() def get_dashboard_info(customer): if not frappe.has_permission("Customer", "read", customer): frappe.msgprint(_("Not permitted"), raise_exception=True) out = {} for doctype in ["Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]: out[doctype] = frappe.db.get_value(doctype, {"customer": customer, "docstatus": ["!=", 2] }, "count(*)") billing = frappe.db.sql("""select sum(grand_total), sum(outstanding_amount) from `tabSales Invoice` where customer=%s and docstatus = 1 and fiscal_year = %s""", (customer, frappe.db.get_default("fiscal_year"))) out["total_billing"] = billing[0][0] out["total_unpaid"] = billing[0][1] return out def get_customer_list(doctype, txt, searchfield, start, page_len, filters): if frappe.db.get_default("cust_master_name") == "Customer Name": fields = ["name", "customer_group", "territory"] else: fields = ["name", "customer_name", "customer_group", "territory"] return frappe.db.sql("""select %s from `tabCustomer` where docstatus < 2 and (%s like %s or customer_name like %s) order by case when name like %s then 0 else 1 end, case when customer_name like %s then 0 else 1 end, name, customer_name limit %s, %s""" % (", ".join(fields), searchfield, "%s", "%s", "%s", "%s", "%s", "%s"), ("%%%s%%" % txt, "%%%s%%" % txt, "%%%s%%" % txt, "%%%s%%" % txt, start, page_len))
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc2x3tc1/IfcObjectDefinition.java
9269
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bimserver.models.ifc2x3tc1; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Object Definition</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssignments <em>Has Assignments</em>}</li> * <li>{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getIsDecomposedBy <em>Is Decomposed By</em>}</li> * <li>{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getDecomposes <em>Decomposes</em>}</li> * <li>{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssociations <em>Has Associations</em>}</li> * </ul> * * @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcObjectDefinition() * @model * @generated */ public interface IfcObjectDefinition extends IfcRoot { /** * Returns the value of the '<em><b>Has Assignments</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.ifc2x3tc1.IfcRelAssigns}. * It is bidirectional and its opposite is '{@link org.bimserver.models.ifc2x3tc1.IfcRelAssigns#getRelatedObjects <em>Related Objects</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Has Assignments</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Has Assignments</em>' reference list. * @see #isSetHasAssignments() * @see #unsetHasAssignments() * @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcObjectDefinition_HasAssignments() * @see org.bimserver.models.ifc2x3tc1.IfcRelAssigns#getRelatedObjects * @model opposite="RelatedObjects" unsettable="true" * @generated */ EList<IfcRelAssigns> getHasAssignments(); /** * Unsets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssignments <em>Has Assignments</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetHasAssignments() * @see #getHasAssignments() * @generated */ void unsetHasAssignments(); /** * Returns whether the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssignments <em>Has Assignments</em>}' reference list is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Has Assignments</em>' reference list is set. * @see #unsetHasAssignments() * @see #getHasAssignments() * @generated */ boolean isSetHasAssignments(); /** * Returns the value of the '<em><b>Is Decomposed By</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.ifc2x3tc1.IfcRelDecomposes}. * It is bidirectional and its opposite is '{@link org.bimserver.models.ifc2x3tc1.IfcRelDecomposes#getRelatingObject <em>Relating Object</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Is Decomposed By</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Is Decomposed By</em>' reference list. * @see #isSetIsDecomposedBy() * @see #unsetIsDecomposedBy() * @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcObjectDefinition_IsDecomposedBy() * @see org.bimserver.models.ifc2x3tc1.IfcRelDecomposes#getRelatingObject * @model opposite="RelatingObject" unsettable="true" * @generated */ EList<IfcRelDecomposes> getIsDecomposedBy(); /** * Unsets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getIsDecomposedBy <em>Is Decomposed By</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetIsDecomposedBy() * @see #getIsDecomposedBy() * @generated */ void unsetIsDecomposedBy(); /** * Returns whether the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getIsDecomposedBy <em>Is Decomposed By</em>}' reference list is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Is Decomposed By</em>' reference list is set. * @see #unsetIsDecomposedBy() * @see #getIsDecomposedBy() * @generated */ boolean isSetIsDecomposedBy(); /** * Returns the value of the '<em><b>Decomposes</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.ifc2x3tc1.IfcRelDecomposes}. * It is bidirectional and its opposite is '{@link org.bimserver.models.ifc2x3tc1.IfcRelDecomposes#getRelatedObjects <em>Related Objects</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Decomposes</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Decomposes</em>' reference list. * @see #isSetDecomposes() * @see #unsetDecomposes() * @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcObjectDefinition_Decomposes() * @see org.bimserver.models.ifc2x3tc1.IfcRelDecomposes#getRelatedObjects * @model opposite="RelatedObjects" unsettable="true" upper="2" * @generated */ EList<IfcRelDecomposes> getDecomposes(); /** * Unsets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getDecomposes <em>Decomposes</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetDecomposes() * @see #getDecomposes() * @generated */ void unsetDecomposes(); /** * Returns whether the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getDecomposes <em>Decomposes</em>}' reference list is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Decomposes</em>' reference list is set. * @see #unsetDecomposes() * @see #getDecomposes() * @generated */ boolean isSetDecomposes(); /** * Returns the value of the '<em><b>Has Associations</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.ifc2x3tc1.IfcRelAssociates}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Has Associations</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Has Associations</em>' reference list. * @see #isSetHasAssociations() * @see #unsetHasAssociations() * @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcObjectDefinition_HasAssociations() * @model unsettable="true" * @generated */ EList<IfcRelAssociates> getHasAssociations(); /** * Unsets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssociations <em>Has Associations</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetHasAssociations() * @see #getHasAssociations() * @generated */ void unsetHasAssociations(); /** * Returns whether the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcObjectDefinition#getHasAssociations <em>Has Associations</em>}' reference list is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Has Associations</em>' reference list is set. * @see #unsetHasAssociations() * @see #getHasAssociations() * @generated */ boolean isSetHasAssociations(); } // IfcObjectDefinition
agpl-3.0
Gebesa-Dev/Addons-gebesa
account_payment_transfer/models/account_payment.py
1372
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import _, api, fields, models class AccountPayment(models.Model): _inherit = "account.payment" def _get_dst_liquidity_aml_dict_vals(self): dst_liquidity_aml_dict = { 'name': _('Transfer from %s') % self.journal_id.name, 'account_id': self.destination_journal_id.default_credit_account_id.id, 'currency_id': self.destination_journal_id.currency_id.id, 'payment_id': self.id, 'journal_id': self.destination_journal_id.id, } if self.currency_id != self.company_id.currency_id: dst_liquidity_aml_dict.update({ 'currency_id': self.currency_id.id, # 'amount_currency': -self.amount, }) dst_liquidity_aml_dict.update({ 'operating_unit_id': self.destination_journal_id.operating_unit_id.id or False}) return dst_liquidity_aml_dict @api.multi def cancel(self): for rec in self: if rec.payment_type == 'transfer': for line in rec.move_line_ids: if line.reconciled: line.remove_move_reconcile() return super(AccountPayment, self).cancel()
agpl-3.0
rockneurotiko/wirecloud
src/wirecloud/platform/static/js/wirecloud/ui/UpgradeWindowMenu.js
7522
/* * Copyright (c) 2015 CoNWeT Lab., Universidad Politécnica de Madrid * * This file is part of Wirecloud Platform. * * Wirecloud Platform is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Wirecloud 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 Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Wirecloud Platform. If not, see * <http://www.gnu.org/licenses/>. * */ /* global StyledElements, Wirecloud */ (function (se, utils) { "use strict"; var builder = new se.GUIBuilder(); var request_version = function request_version() { var from_version, to_version, version; if (this.current_request != null) { this.current_request.abort(); } this.changelog.disable(); this.changelog.removeClassName(['downgrade', 'upgrade']); this.acceptButton.removeClassName(['btn-success', 'btn-danger']); version = this.version_selector.getValue(); if (this.component.meta.version.compareTo(version) < 0) { this.acceptButton.setLabel(utils.gettext('Upgrade')); this.acceptButton.addClassName('btn-success'); this.changelog.addClassName('upgrade'); to_version = version; from_version = this.component.meta.version; } else { this.acceptButton.setLabel(utils.gettext('Downgrade')); this.acceptButton.addClassName('btn-danger'); this.changelog.addClassName('downgrade'); to_version = this.component.meta.version; from_version = version; } var resource_info = { 'vendor': this.component.meta.vendor, 'name': this.component.meta.name, 'version': to_version }; var url = Wirecloud.LocalCatalogue.RESOURCE_CHANGELOG_ENTRY.evaluate(resource_info); this.current_request = Wirecloud.io.makeRequest(url, { method: 'GET', parameters: { from: from_version }, on404: function (response) { this.changelog.removeClassName(['upgrade', 'downgrade']); var msg = utils.gettext('There is not change information between versions %(from_version)s and %(to_version)s'); this.changelog.clear().appendChild(utils.interpolate(msg, {from_version: from_version, to_version: to_version})); }.bind(this), onFailure: function (response) { this.changelog.removeClassName(['upgrade', 'downgrade']); var msg = utils.gettext('Unable to retrieve change log information'); this.changelog.clear().appendChild(msg); }.bind(this), onSuccess: function (response) { this.changelog.clear().appendChild(new se.Fragment(response.responseText)); }.bind(this), onComplete: function () { this.current_request = null; this.changelog.enable(); }.bind(this) }); }; var UpgradeWindowMenu = function UpgradeWindowMenu(component) { var title, versions; title = utils.gettext('Upgrading %(component)s'); title = utils.interpolate(title, {component: component.title}); this.component = component; Wirecloud.ui.WindowMenu.call(this, title, 'wc-upgrade-component-modal'); // Get all available versions versions = Wirecloud.LocalCatalogue.resourceVersions[this.component.meta.group_id].map(function (component) {return component.version}); // Remove current version versions = versions.filter(function (version) { return component.meta.version.compareTo(version) !== 0}); // Sort versions versions = versions.sort(function (version1, version2) { return -version1.compareTo(version2); }); this.version_selector = new StyledElements.Select({'name': "version"}); this.version_selector.addEventListener('change', request_version.bind(this)); this.version_selector.addEntries(versions); this.changelog = new StyledElements.Container({'extraClass': 'markdown-body loading', 'tagname': 'article'}); builder.parse(Wirecloud.currentTheme.templates.upgrade_window_menu, { currentversion: this.component.meta.version, versionselect: this.version_selector, changelog: this.changelog }).appendTo(this.windowContent); // Accept button this.acceptButton = new StyledElements.Button({'class': 'btn-accept'}); this.acceptButton.insertInto(this.windowBottom); this.acceptButton.addEventListener("click", function () { this.acceptButton.disable(); var new_version = this.version_selector.getValue(); var old_version = this.component.meta.version; var new_component_id = [this.component.meta.vendor, this.component.meta.name, new_version].join('/'); var new_component = Wirecloud.LocalCatalogue.getResourceId(new_component_id); var _onsuccess_listener = function onsuccess_listener() { component.removeEventListener('upgraded', _onsuccess_listener); component.removeEventListener('upgradeerror', _onfailure_listener); var msg; if (new_version.compareTo(old_version) > 0) { msg = utils.gettext("The %(type)s was upgraded to v%(version)s successfully."); } else { msg = utils.gettext("The %(type)s was downgraded to v%(version)s successfully."); } msg = utils.interpolate(msg, {type: component.meta.type, version: new_version}); component.logManager.log(msg, Wirecloud.constants.LOGGING.INFO_MSG); this._closeListener(); }.bind(this); var _onfailure_listener = function onsuccess_listener() { component.removeEventListener('upgraded', _onsuccess_listener); component.removeEventListener('upgradeerror', _onfailure_listener); this.acceptButton.enable(); }.bind(this); component.addEventListener('upgraded', _onsuccess_listener); component.addEventListener('upgradeerror', _onfailure_listener); component.meta = new_component; }.bind(this)); // Cancel button this.cancelButton = new StyledElements.Button({ text: utils.gettext('Cancel'), 'class': 'btn-primary btn-cancel' }); this.cancelButton.addEventListener("click", this._closeListener); this.cancelButton.insertInto(this.windowBottom); }; UpgradeWindowMenu.prototype = new Wirecloud.ui.WindowMenu(); UpgradeWindowMenu.prototype.show = function show() { Wirecloud.ui.WindowMenu.prototype.show.apply(this, arguments); request_version.call(this); }; Wirecloud.ui.UpgradeWindowMenu = UpgradeWindowMenu; })(StyledElements, StyledElements.Utils);
agpl-3.0
rockneurotiko/wirecloud
src/wirecloud/commons/tests/admin_commands.py
15086
# -*- coding: utf-8 -*- # Copyright (c) 2014-2016 CoNWeT Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Wirecloud 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 Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import io import os import shutil from tempfile import mkdtemp import django from django.core.management.base import CommandError from django.test import TestCase from mock import DEFAULT, Mock, patch from wirecloud.commons.wirecloud_admin import CommandLineUtility from wirecloud.commons.utils.testcases import cleartree import wirecloud.platform # Avoid nose to repeat these tests (they are run through wirecloud/commons/tests/__init__.py) __test__ = False class BaseAdminCommandTestCase(TestCase): tags = ('wirecloud-commands', 'wirecloud-command-base', 'wirecloud-noselenium') @classmethod def setUpClass(cls): from wirecloud.commons.commands.convert import ConvertCommand from wirecloud.commons.commands.startproject import StartprojectCommand from wirecloud.fiware.commands.passintegrationtests import IntegrationTestsCommand cls.command_utility = CommandLineUtility({ "convert": ConvertCommand(), "startproject": StartprojectCommand(), "passintegrationtests": IntegrationTestsCommand(), }, prog_name='wirecloud-admin') cls.test_data_dir = os.path.join(os.path.dirname(__file__), 'test-data') super(BaseAdminCommandTestCase, cls).setUpClass() def test_general_help(self): options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin'], **options) options['stdout'].seek(0) first_output = options['stdout'].read() self.assertIn('Available subcommands', first_output) options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', '-h'], **options) options['stdout'].seek(0) second_output = options['stdout'].read() options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', '--help'], **options) options['stdout'].seek(0) third_output = options['stdout'].read() self.assertEqual(first_output, second_output) self.assertEqual(second_output, third_output) def test_command_help(self): options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', 'help', 'convert'], **options) options['stdout'].seek(0) first_output = options['stdout'].read() options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', 'convert', '-h'], **options) options['stdout'].seek(0) second_output = options['stdout'].read() options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', 'convert', '--help'], **options) options['stdout'].seek(0) third_output = options['stdout'].read() self.assertEqual(first_output, second_output) self.assertEqual(second_output, third_output) def test_version(self): options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', 'version'], **options) options['stdout'].seek(0) self.assertEqual(wirecloud.platform.__version__ + '\n', options['stdout'].read()) def test_version_as_long_flag(self): options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', '--version'], **options) options['stdout'].seek(0) self.assertEqual(wirecloud.platform.__version__ + '\n', options['stdout'].read()) def test_command_list(self): options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(['wirecloud-admin', 'help', '--commands'], **options) options['stdout'].seek(0) first_output = options['stdout'].read() self.assertNotIn('Available subcommands', first_output) def test_basic_command_call(self): args = ['wirecloud-admin', 'convert', '-d', 'xml', os.path.join(self.test_data_dir, 'minimal_endpoint_info.json')] options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(args, **options) options['stdout'].seek(0) self.assertNotEqual(options['stdout'].read(), '') options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') def test_invalid_command(self): # Calling directly to an inexistent command args = ['wirecloud-admin', 'inexistentcommand', 'option1'] options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(args, **options) options['stdout'].seek(0) first_output = options['stdout'].read() self.assertNotEqual(first_output, '') options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') # Requesting help for an inexistent command args = ['wirecloud-admin', 'help', 'inexistentcommand'] options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(args, **options) options['stdout'].seek(0) second_output = options['stdout'].read() options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') # Requesting help for an inexistent command (alternative way) args = ['wirecloud-admin', 'inexistentcommand', '--help'] options = {"stdout": io.StringIO(), "stderr": io.StringIO()} self.command_utility.execute(args, **options) options['stdout'].seek(0) third_output = options['stdout'].read() options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') self.assertEqual(first_output, second_output) self.assertEqual(second_output, third_output) class ConvertCommandTestCase(TestCase): tags = ('wirecloud-commands', 'wirecloud-command-convert', 'wirecloud-noselenium') @classmethod def setUpClass(cls): cls.tmp_dir = mkdtemp() cls.test_data_dir = os.path.join(os.path.dirname(__file__), 'test-data') super(ConvertCommandTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmp_dir, ignore_errors=True) def setUp(self): from wirecloud.commons.commands.convert import ConvertCommand self.command = ConvertCommand() def tearDown(self): cleartree(self.tmp_dir) def test_no_args(self): args = [] options = { "dest_format": "rdf" } self.assertRaises(CommandError, self.command.execute, *args, **options) def test_non_existent_file(self): args = ['/tmp/nonexistent_file.xml'] options = { "dest_format": "rdf" } self.assertRaises(CommandError, self.command.execute, *args, **options) def test_invalid_dest_format(self): args = ['/tmp/nonexistent_file.xml'] options = { "dest_format": "invalid" } self.assertRaises(CommandError, self.command.execute, *args, **options) def test_minimal_info_conversion_stdout(self): for format in ('json', 'xml', 'rdf'): args = [os.path.join(self.test_data_dir, 'minimal_endpoint_info.json')] options = {"dest_format": format, "rdf_format": "n3", "stdout": io.StringIO(), "stderr": io.StringIO()} self.command.execute(*args, **options) options['stdout'].seek(0) self.assertNotEqual(options['stdout'].read(), '') options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') def test_minimal_info_conversion_outputfile(self): dest_file = os.path.join(self.tmp_dir, 'new_file.xml') args = [os.path.join(self.test_data_dir, 'minimal_endpoint_info.json'), dest_file] options = {"dest_format": 'rdf', "rdf_format": "pretty-xml", "stdout": io.StringIO(), "stderr": io.StringIO()} self.command.execute(*args, **options) options['stdout'].seek(0) self.assertEqual(options['stdout'].read(), '') options['stderr'].seek(0) self.assertEqual(options['stderr'].read(), '') with open(dest_file, 'rb') as f: self.assertNotEqual(f.read(), '') class StartprojectCommandTestCase(TestCase): tags = ('wirecloud-commands', 'wirecloud-command-startproject', 'wirecloud-noselenium') @classmethod def setUpClass(cls): cls.tmp_dir = mkdtemp() cls.test_data_dir = os.path.join(os.path.dirname(__file__), 'test-data') super(StartprojectCommandTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmp_dir, ignore_errors=True) def setUp(self): from wirecloud.commons.commands.startproject import StartprojectCommand self.command = StartprojectCommand() def tearDown(self): cleartree(self.tmp_dir) def test_no_args(self): args = [] options = { "type": "platform", "quick_start": False, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT) as mocks: self.assertRaises(CommandError, self.command.execute, *args, **options) self.assertEqual(mocks['Command'].call_count, 0) def test_invalid_project_type(self): args = ['wirecloud_instance'] options = { "type": "invalid", "quick_start": False, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT) as mocks: self.assertRaises(CommandError, self.command.execute, *args, **options) self.assertEqual(mocks['Command'].call_count, 0) def assertHandleCall(self, handle_mock, values={}): call_args, call_kwargs = handle_mock.call_args_list[0] options = { "name": 'wirecloud_instance', "directory": None, "verbosity": 1 } options.update(values) if django.VERSION[1] >= 8: for key in options: self.assertEqual(call_kwargs.get(key), options[key]) else: self.assertEqual(call_args[0], options['name']) self.assertEqual(call_args[1], options['directory']) self.assertEqual(call_kwargs['verbosity'], options['verbosity']) def test_platform_creation(self): args = ['wirecloud_instance'] options = { "type": "platform", "quick_start": False, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT) as mocks: command_instance_mock = Mock() mocks['Command'].return_value = command_instance_mock self.command.execute(*args, **options) self.assertEqual(command_instance_mock.handle.call_count, 1) self.assertHandleCall(command_instance_mock.handle) self.assertEqual(mocks['subprocess'].call.call_count, 0) def test_platform_creation_quick_start(self): args = ['wirecloud_instance'] options = { "type": "platform", "quick_start": True, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT, os=DEFAULT, sys=DEFAULT) as mocks: command_instance_mock = Mock() mocks['Command'].return_value = command_instance_mock mocks['subprocess'].call.return_value = None mocks['sys'].executable = 'python-interpreter' self.command.execute(*args, **options) self.assertEqual(command_instance_mock.handle.call_count, 1) call_args, call_kwargs = command_instance_mock.handle.call_args_list[0] self.assertHandleCall(command_instance_mock.handle) self.assertGreaterEqual(mocks['subprocess'].call.call_count, 1) for (call_args, call_kwargs) in mocks['subprocess'].call.call_args_list: self.assertTrue(call_args[0].startswith('python-interpreter ')) def test_platform_creation_quick_start_no_executable_info(self): args = ['wirecloud_instance'] options = { "type": "platform", "quick_start": True, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT, os=DEFAULT, sys=DEFAULT) as mocks: command_instance_mock = Mock() mocks['Command'].return_value = command_instance_mock mocks['subprocess'].call.return_value = None mocks['sys'].executable = None self.command.execute(*args, **options) self.assertEqual(command_instance_mock.handle.call_count, 1) self.assertHandleCall(command_instance_mock.handle) self.assertGreaterEqual(mocks['subprocess'].call.call_count, 1) for (call_args, call_kwargs) in mocks['subprocess'].call.call_args_list: self.assertTrue(call_args[0].startswith('python ')) def test_platform_creation_quick_start_external_cmd_error(self): args = ['wirecloud_instance'] options = { "type": "platform", "quick_start": True, "verbosity": "1", } with patch.multiple('wirecloud.commons.commands.startproject', Command=DEFAULT, subprocess=DEFAULT, os=DEFAULT, sys=DEFAULT) as mocks: command_instance_mock = Mock() mocks['Command'].return_value = command_instance_mock mocks['subprocess'].call.return_value = 1 mocks['sys'].executable = 'python-interpreter' self.assertRaises(CommandError, self.command.execute, *args, **options) self.assertEqual(command_instance_mock.handle.call_count, 1) self.assertHandleCall(command_instance_mock.handle) self.assertEqual(mocks['subprocess'].call.call_count, 1)
agpl-3.0
digilys/digilys
config/deploy.rb
3481
require "bundler/capistrano" # Digilys is deployed to a single server. The name of the server # can either be supplied as an environment variable +digilys_instance+ # when executing cap: # # > digilys_instance=digilys-production cap deploy # # or it defaults to the server +digilys+. # # A good idea is to have an +~/.ssh/config+ which includes server details # fo set :digilys_server, ENV["digilys_instance"] || "digilys" set :application, "digilys" set :scm, :git set :use_sudo, false # Local deployment set :repository, "." set :local_repository, "." set :deploy_via, :copy set :deploy_to, -> { capture("echo -n $HOME/app") } set :passenger_port, -> { capture("cat #{deploy_to}/shared/config/passenger_port.txt || echo 24500").to_i } role :web, digilys_server # Your HTTP server, Apache/etc role :app, digilys_server # This may be the same as your `Web` server role :db, digilys_server, primary: true # This is where Rails migrations will run # if you want to clean up old releases on each deploy uncomment this: after "deploy:restart", "deploy:cleanup" # If you are using Passenger mod_rails uncomment this: namespace :deploy do task :start, roles: :app do run "cd -- #{deploy_to}/current && bundle exec passenger start #{deploy_to}/current -p #{passenger_port} -e #{rails_env} -d --log-file #{deploy_to}/shared/log/passenger.log --pid-file #{deploy_to}/shared/pids/passenger.pid" end task :stop, roles: :app do run "cd -- #{deploy_to}/current && bundle exec passenger stop #{deploy_to}/current -p #{passenger_port} --pid-file #{deploy_to}/shared/pids/passenger.pid" end task :restart, roles: :app, except: { no_release: true } do run "touch #{File.join(current_path,"tmp","restart.txt")}" end end before "deploy:finalize_update", "deploy:symlink_external_files" before "deploy:finalize_update", "deploy:symlink_relative_public" before "deploy:migrate", "deploy:backup_db" namespace :deploy do desc "Symlinks external files required for the app" task :symlink_external_files, roles: :app do run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml" run "ln -nfs #{deploy_to}/shared/config/app_config.private.yml #{release_path}/config/app/base.private.yml" run "test -d #{deploy_to}/shared/uploads || mkdir -p #{deploy_to}/shared/uploads; mkdir -p #{release_path}/tmp; ln -nfs #{deploy_to}/shared/uploads #{release_path}/tmp/uploads" end desc "Symlinks the relative public directory, if any" task :symlink_relative_public, roles: :app do root_url = capture("echo -n $RAILS_RELATIVE_URL_ROOT") if root_url && !root_url.empty? root_dir = root_url.split("/")[0..-2].join("/") run "mkdir -p #{latest_release}/public#{root_dir}" if root_dir && !root_dir.empty? run "ln -nsf #{latest_release}/public #{latest_release}/public#{root_url}" end end desc "Invoke rake task" task :invoke do run "cd '#{current_path}' && #{rake} #{ENV['task']} RAILS_ENV=#{rails_env}" end task :backup_db, roles: :db do run "test -d #{deploy_to}/shared/backup || mkdir -p #{deploy_to}/shared/backup" db = YAML::load(capture("cat #{deploy_to}/shared/config/database.yml"))["production"] backup_file = "#{deploy_to}/shared/backup/#{db["database"]}.$(date +%Y%m%d%H%M%S).sql.gz" run "pg_dump -U #{db["username"]} #{db["database"]} | gzip > #{backup_file}" end end
agpl-3.0
splicemachine/spliceengine
db-tools-testing/src/main/java/com/splicemachine/dbTesting/junit/SystemPropertyTestSetup.java
5585
/* * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. * * Some parts of this source code are based on Apache Derby, and the following notices apply to * Apache Derby: * * Apache Derby is a subproject of the Apache DB project, and is licensed under * the Apache License, Version 2.0 (the "License"); you may not use these files * 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. * * Splice Machine, Inc. has modified the Apache Derby code in this file. * * All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.dbTesting.junit; import java.security.PrivilegedActionException; import java.util.Enumeration; import java.util.Properties; import junit.extensions.TestSetup; import junit.framework.Test; /** * Test decorator to set a set of system properties on setUp * and restore them to the previous values on tearDown. * */ public class SystemPropertyTestSetup extends TestSetup { protected Properties newValues; private Properties oldValues; private boolean staticProperties; /** * Create a test decorator that sets and restores the passed * in properties. Assumption is that the contents of * properties and values will not change during execution. * @param test test to be decorated * @param newValues properties to be set */ public SystemPropertyTestSetup(Test test, Properties newValues, boolean staticProperties) { super(test); this.newValues = newValues; this.staticProperties = staticProperties; } /** * Create a test decorator that sets and restores * System properties. Do not shutdown engine after * setting properties * @param test * @param newValues */ public SystemPropertyTestSetup(Test test, Properties newValues) { super(test); this.newValues = newValues; this.staticProperties = false; } /** * For each property store the current value and * replace it with the new value, unless there is no change. */ protected void setUp() throws java.lang.Exception { //DERBY-5663 Getting NPE when trying to set // db.language.logStatementText property to true inside a junit // suite. //The same instance of SystemPropertyTestSetup can be used again // and hence we want to make sure that oldValues is not null as set // in the tearDown() method. If we leave it null, we will run into NPE // during the tearDown of SystemPropertyTestSetup during the // decorator's reuse. this.oldValues = new Properties(); // shutdown engine so static properties take effect // shutdown the engine before setting the properties. this // is because the properties may change authentication settings // to NATIVE authentication and we may be missing a credentials DB. if (staticProperties) { TestConfiguration.getCurrent().shutdownEngine(); } setProperties(newValues); } /** * Revert the properties to their values prior to the setUp call. */ protected void tearDown() throws java.lang.Exception { // Clear all the system properties set by the new set // that will not be reset by the old set. for (Enumeration e = newValues.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (oldValues.getProperty(key) == null) BaseTestCase.removeSystemProperty(key); } // and then reset nay old values setProperties(oldValues); // shutdown engine to restore any static properties if (staticProperties) TestConfiguration.getCurrent().shutdownEngine(); oldValues = null; } private void setProperties(Properties values) throws PrivilegedActionException { for (Enumeration e = values.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = values.getProperty(key); String old = BaseTestCase.getSystemProperty(key); boolean change; if (old != null) { // set, might need to be changed. change = !old.equals(value); //Reference equality is ok here. if (values != oldValues) oldValues.setProperty(key, old); } else { // notset, needs to be set change = true; } if (change) { BaseTestCase.setSystemProperty(key, value); } } } }
agpl-3.0
StarshineOnline/Starshine-Online
attaque.php
24595
<?php // -*- tab-width:2; mode: php -*- /** * @file attaque.php * Gestion des combats */ if (file_exists('root.php')) include_once('root.php'); //Inclusion des fichiers indispensables include_once(root.'inc/fp.php'); $perso = &joueur::get_perso(); $interf_princ = $G_interf->creer_jeu(); $interf_princ->verif_mort($perso); $check_pet = array_key_exists('pet', $_GET) && $perso->nb_pet() > 0; $donj = is_donjon($perso->get_x(), $perso->get_y()) && $perso->in_arene('and donj = 0') == false && $perso->get_y()>190; $type = $_GET['type']; // Ivresse $ivresse = $perso->get_buff('ivresse'); if( $ivresse ) { if( comp_sort::test_de(100, $ivresse->get_effet()) ) { $cibles = array(); switch($type) { case 'perso': case 'monstre': case 'batiment': /// @todo passer à l'objet switch($type) { case 'perso': $requete = 'SELECT x, y FROM perso WHERE id = '.$_GET['id_perso']; break; case 'monstre': $requete = 'SELECT x, y FROM map_monstre WHERE id = '.$_GET['id_monstre']; break; case 'batiment': $requete = 'SELECT x, y FROM construction WHERE id = '.$_GET['id_batiment']; } $req = $db->query($requete); $pos = $db->read_assoc($req); $requete = 'SELECT id FROM construction WHERE type != "bourg" AND x = '.$pos['x'].' AND y = '.$pos['y']; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'batiment', 'table'=>'construction', 'id'=>$row[0]); $requete = 'SELECT id FROM placement WHERE x = '.$pos['x'].' AND y = '.$pos['y']; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'batiment', 'table'=>'placement', 'id'=>$row[0]); $requete = 'SELECT id FROM perso WHERE x = '.$pos['x'].' AND y = '.$pos['y']; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'perso', 'id'=>$row[0]); $requete = 'SELECT id FROM map_monstre WHERE x = '.$pos['x'].' AND y = '.$pos['y']; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'monstre', 'id'=>$row[0]); break; case 'siege': case 'ville': $x_min = $perso->get_x() - 1; $x_max = $perso->get_x() + 1; $y_min = $perso->get_y() - 1; $y_max = $perso->get_y() + 1; $requete = 'SELECT id FROM construction WHERE x BETWEEN '.$x_min.' AND '.$x_max.' AND y = '.$y_min.' AND '.$y_max; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'siege', 'table'=>'construction', 'id'=>$row[0]); $requete = 'SELECT id FROM placement WHERE x BETWEEN '.$x_min.' AND '.$x_max.' AND y = '.$y_min.' AND '.$y_max; $req = $db->query($requete); while( $row = $db->read_array($req) ) $cibles[] = array('type'=>'siege', 'table'=>'placement', 'id'=>$row[0]); $requete = 'SELECT map.x as x, map.y as y, nom, race, map.royaume FROM map LEFT JOIN royaume ON map.royaume = royaume.id WHERE map.x BETWEEN '.$x_min.' AND '.$x_max.' AND map.y BETWEEN '.$y_min.' AND '.$y_max.' AND type = 1 AND royaume.fin_raz_capitale = 0'; $req = $db->query($requete); $row = $db->read_assoc($req); if( $row ) $cibles[] = array('type'=>'ville', 'id'=>convert_in_pos($row['x'], $row['y'])); } $ind = rand(0, count($cibles)-1); $type = $cibles[$ind]['type']; switch($type) { case 'perso': $_GET['id_perso'] = $cibles[$ind]['id']; break; case 'monstre': $_GET['id_monstre'] = $cibles[$ind]['id']; break; case 'batiment': case 'siege': $_GET['id_batiment'] = $cibles[$ind]['id']; $_GET['table'] = $cibles[$ind]['table']; break; case 'ville': $_GET['id_ville'] = $cibles[$ind]['id']; } } } switch($type) { case 'perso' : if ($_SESSION['ID'] == $_GET['id_perso']) security_block(URL_MANIPULATION, 'Auto-attaque prohibée'); if(!$check_pet) { $perso = new perso($_SESSION['ID']); $perso->check_perso(); $perso->action_do = $perso->recupaction('attaque'); $attaquant = entite::factory('perso', $perso); } else { $attaquant = entite::factory('pet', $perso->get_pet(), $perso, true); } $def = false; $perso_defenseur = new perso($_GET['id_perso']); $perso_defenseur->check_perso(false); //On vérifie que ya pas un buff qui fait défendre par un pet if($perso_defenseur->is_buff('defense_pet')) { $pet = $perso_defenseur->get_pet(); if (!$pet || $pet->get_hp() < 1) { $check_pet_def = false; interf_debug::enregistre('Le pet est mort…'); } else { $defense = $perso_defenseur->get_buff('defense_pet', 'effet'); $collier = decompose_objet($perso_defenseur->get_inventaire_partie('cou')); if ($collier != '') { $requete = "SELECT * FROM armure WHERE ID = ".$collier['id_objet']; //Récupération des infos de l'objet $req = $db->query($requete); $row = $db->read_array($req); $effet = explode('-', $row['effet']); if ($effet[0] == '20') { $defense = $defense + $effet[1]; } } $rand = rand(0, 100); //Défense par le pet interf_debug::enregistre('Defense par le pet: '.$rand.' VS '.$defense); if($rand < $defense) { interf_debug::enregistre('Defense par le pet OK'); $check_pet_def = true; } } } //Si il est en train de dresser un mob, le dressage est arrêté if($perso_defenseur->is_buff('dressage')) { $buff_def = $perso_defenseur->get_buff('dressage'); $buff_def->supprimer(); } if(!$check_pet_def) { $perso_defenseur->action_do = $perso_defenseur->recupaction('defense'); $defenseur = entite::factory('perso', $perso_defenseur); } else { $defenseur = entite::factory('pet', $perso_defenseur->get_pet(), $perso_defenseur, false); } break; case 'monstre' : if(!$check_pet) { $perso = new perso($_SESSION['ID']); $perso->check_perso(); $perso->action_do = $perso->recupaction('attaque'); $attaquant = entite::factory('perso', $perso); /*if (!$donj) { $perso = new perso($_SESSION['ID']); $perso->check_perso(); $perso->action_do = $perso->recupaction('attaque'); $attaquant = entite::factory('perso', $perso); } else { //On vérifie que ya pas un buff qui fait défendre par un pet if($perso->is_buff('defense_pet')) { $pet = $perso->get_pet(); if (!$pet || $pet->get_hp() < 1) { $check_pet_donj = false; interf_debug::enregistre('Le pet est mort ...'); } else { $attaque_donj = $perso->get_buff('defense_pet', 'effet'); $rand = rand(0, 100); //Défense par le pet interf_debug::enregistre('Defense par le pet: '.$rand.' VS '.$defense); if($rand < $attaque_donj) { interf_debug::enregistre('Defense par le pet OK'); $check_pet_donj = true; } } } if(!$check_pet_donj) { $perso->action_do = $perso->recupaction('defense'); $attaquant = entite::factory('perso', $perso); } else { $attaquant = entite::factory('pet', $perso->get_pet(), $perso); } }*/ } else { $attaquant = entite::factory('pet', $perso->get_pet(), $perso); } $map_monstre = new map_monstre($_GET['id_monstre']); $map_monstre->check_monstre(); if ($map_monstre->nonexistant) { $interf_princ->set_droite( new interf_alerte(interf_alerte::msg_erreur, true, false, 'Ce monstre est déjà au paradis des monstres') ); exit (0); } $perso_defenseur = new monstre($map_monstre->get_type()); $defenseur = entite::factory('monstre', $map_monstre); $diff_lvl = abs($perso->get_level() - $defenseur->get_level()); break; case 'batiment' : if ($perso->is_buff('debuff_rvr')) $no_rvr = true; $perso = new perso($_SESSION['ID']); $perso->check_perso(); if(!$check_pet) { $perso->action_do = $perso->recupaction('attaque'); $attaquant = entite::factory('perso', $perso); } else { $attaquant = entite::factory('pet', $perso->get_pet(), $perso); } if($_GET['table'] == 'construction') $map_batiment = new construction($_GET['id_batiment']); else $map_batiment = new placement($_GET['id_batiment']); $defenseur = entite::factory('batiment', $map_batiment, $perso); break; case 'siege' : if ($perso->is_buff('debuff_rvr')) $no_rvr = true; $map_siege = new arme_siege($_GET['id_arme_de_siege']); if($_GET['table'] == 'construction') { $map_batiment = new construction($_GET['id_batiment']); $id_constr = $_GET['id_batiment']; $id_plac = 0; } else { $map_batiment = new placement($_GET['id_batiment']); $id_constr = 0; $id_plac = $_GET['id_batiment']; } /// debuff empêchant la suppression du bâtiment $buff = new buff_batiment_def( buff_batiment_def::id_assiege ); $buff->lance($id_constr, $id_plac); $perso = new perso($_SESSION['ID']); $perso->check_perso(); $siege = new batiment($map_siege->get_id_batiment()); $defenseur = entite::factory('batiment', $map_batiment); $attaquant = entite::factory('siege', $map_siege, $perso, true, $defenseur); break; case 'ville' : if ($perso->is_buff('debuff_rvr')) $no_rvr = true; $map_siege = new arme_siege($_GET['id_arme_de_siege']); $perso = new perso($_SESSION['ID']); $perso->check_perso(); $map_case = new map_case($_GET['id_ville']); $map_royaume = new royaume($map_case->get_royaume()); $map_royaume->verif_hp(); $siege = new batiment($map_siege->get_id_batiment()); $coord = convert_in_coord($_GET['id_ville']); $map_royaume->x =$coord['x']; $map_royaume->y =$coord['y']; $defenseur = entite::factory('ville', $map_royaume); $attaquant = entite::factory('siege', $map_siege, $perso, true, $defenseur); if ($map_royaume->is_raz()) { $interf_princ->set_droite( new interf_alerte(interf_alerte::msg_erreur, true, false, 'Cette ville est déjà mise à sac') ); exit (0); } break; } //Achievement if(!$check_pet AND ($type == "perso" OR $type == "monstre") AND $attaquant->action == $defenseur->action) $perso->unlock_achiev('same_action'); // round_total sera modifié ensuite au besoin, mais on doit le seter au début $distance = $attaquant->calcule_distance($defenseur); $cadre = $interf_princ->set_droite( $G_interf->creer_droite('Combat VS '.$defenseur->get_nom()) ); interf_debug::aff_enregistres($cadre); /*if( is_donjon($perso->get_x(), $perso->get_y()) && ($perso->in_arene('and donj = 0') == false) && $perso->get_y()>190 ) { $W_case = convertd_in_pos($defenseur->get_x(), $defenseur->get_y()); $distance = detection_distance($W_case, convertd_in_pos($attaquant->get_x(), $attaquant->get_y())); //Un monstre attaque pas de PA pour attaquer if(array_key_exists('attaque_donjon', $_SESSION) AND $_SESSION['attaque_donjon'] == 'ok') { $no_pa_attaque = true; unset($_SESSION['attaque_donjon']); $distance--; if($distance < 0 ) $distance = 0; } }*/ $dist_tir_att = $attaquant->get_distance_tir(); //On vérifie si l'attaquant est sur un batiment offensif /// @todo passer à l'objet $requete = "SELECT id_batiment FROM construction WHERE x = ".$perso->get_x()." AND y = ".$perso->get_y()." AND royaume = ".$Trace[$perso->get_race()]['numrace']; $req = $db->query($requete); if($db->num_rows > 0) { $row = $db->read_row($req); $batiment_off = new batiment($row[0]); //Augmentation de tir à distance if ($batiment_off->has_bonus('batiment_distance')) $attaquant->add_buff('batiment_distance', $batiment_off->get_bonus('batiment_distance')); //Augmentation de la distance de tir if ($batiment_off->has_bonus('batiment_incantation')) $attaquant->add_buff('batiment_incantation', $batiment_off->get_bonus('batiment_incantation')); if( $attaquant->get_arme_type() == 'arc' && $batiment_off->has_bonus('distance_arc') ) $dist_tir_att += $batiment_off->get_bonus('distance_arc'); else if( $attaquant->get_arme_type() == 'baton' && $batiment_off->has_bonus('distance_baton') ) $dist_tir_att += $batiment_off->get_bonus('distance_baton'); } if($perso->is_buff('repos_sage') && !$no_pa_attaque) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous êtes sous repos du sage, vous ne pouvez pas attaquer.') ); elseif($no_rvr) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous ne pouvez pas attaquer pendant la trêve.') ); elseif($perso->is_buff('dressage')) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous dressez un monstre, vous ne pouvez pas attaquer.') ); else if($distance > $dist_tir_att ) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous êtes trop loin pour l\'attaquer !') ); elseif($attaquant->get_hp() <= 0 OR $defenseur->get_hp() <= 0) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Un des protagonistes n\'a plus de points de vie.') ); elseif($perso->is_buff('petrifie')) $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous êtes pétrifié, vous ne pouvez pas attaquer.') ); else { $R = new royaume($Trace[$perso->get_race()]['numrace']); if($type == 'perso') { //Récupération si la case est une ville et diplomatie $defenseur_en_defense = false; /// @todo passer à l'objet $requete = "SELECT type FROM map WHERE x = ".$defenseur->get_x() .' and y = '.$defenseur->get_y()." AND type = 1 AND royaume = ". $Trace[$defenseur->get_race()]['numrace']; $db->query($requete); if($db->num_rows > 0) { $cadre->add( new interf_alerte(interf_alerte::msg_info, true, false, 'Le défenseur est sur sa ville, application des bonus !') ); $defenseur->add_buff('batiment_pp', 30); $defenseur->add_buff('batiment_pm', 16); $defenseur->add_buff('batiment_esquive', 50); $defenseur_en_defense = true; } /// @todo passer à l'objet $constr = construction::create(array('x','y','royaume'), array($defenseur->get_x(), $defenseur->get_y(), $Trace[$defenseur->get_race()]['numrace'])); if( $constr && !$constr[0]->is_buff('sape') ) { $batiment_def = new batiment( $constr[0]->get_id() ); //Augmentation des chances d'esquiver if ($batiment_def->has_bonus('batiment_esquive')) $defenseur->add_buff('batiment_esquive', $batiment_def->get_bonus('batiment_esquive')); //Augmentation de la PP if ($batiment_def->has_bonus('batiment_pp')) $defenseur->add_buff('batiment_pp', $batiment_def->get_bonus('batiment_pp')); //Augmentation de la PM if ($batiment_def->has_bonus('batiment_pm')) $defenseur->add_buff('batiment_pm', $batiment_def->get_bonus('batiment_pm')); //Augmentation de l'incantation if ($batiment_def->has_bonus('batiment_incantation')) $defenseur->add_buff('batiment_incantation', $batiment_def->get_bonus('batiment_incantation')); //Augmentation du tir à distance if ($batiment_def->has_bonus('batiment_distance')) $defenseur->add_buff('batiment_distance', $batiment_def->get_bonus('batiment_distance')); $defenseur_en_defense = true; } } //fin $type = 'perso' $pa_attaque = $attaquant->get_cout_attaque($perso, $defenseur); if (isset($no_pa_attaque) && $no_pa_attaque == true) $pa_attaque = 0; $perso_true = false; $siege_true = false; $perso_true = ($type == 'perso' || $type == 'monstre' || $type == 'batiment') && $perso->get_pa() >= $pa_attaque; $siege_true = ($type == 'siege' || $type == 'ville') && $attaquant->peut_attaquer() && $perso->get_pa() >= $pa_attaque; //Vérifie si l'attaquant a assez de points d'actions pour attaquer ou si l'arme de siege a assez de rechargement if ($perso_true || $siege_true) { //Suppresion de longue portée si besoin if($attaquant->is_buff('longue_portee') && $attaquant->get_arme_type() == 'arc') { /// @todo passer à l'objet $requete = "DELETE FROM buff WHERE id = ".$attaquant->get_buff('longue_portee', 'id'); $db->query($requete); } //Gestion des points de crime if($type == 'perso') { $crime = false; /// @todo passer à l'objet $requete = "SELECT ".$defenseur->get_race()." FROM diplomatie WHERE race = '".$attaquant->get_race()."'"; $req = $db->query($requete); $row = $db->read_row($req); $pascrime = false; //Vérification si crime if(array_key_exists($row[0], $G_crime)) { if($row[0] == 127) { $amende = recup_amende($perso_defenseur->get_id()); if($amende) { if($amende['statut'] != 'normal') $pascrime = true; } } if(!$pascrime) { $crime = true; $points = ($G_crime[$row[0]] / 10); $perso->set_crime($perso->get_crime() + $points); $cadre->add( new interf_alerte(interf_alerte::msg_avertis, true, false, 'Vous attaquez un personnage en '.$Gtrad['diplo'.$row[0]].', vous recevez '.$points.' point(s) de crime') ); } } } /// @todo à améliorer $G_url->add('type', $type); switch($type) { case 'joueur': case 'perso': $G_url->add('id_perso', $defenseur->get_id()); break; case 'monstre': $G_url->add('id_monstre', $map_monstre->get_id()); break; case 'batiment': $G_url->add('id_batiment', $map_batiment->get_id()); $G_url->add('table', $_GET['table']); break; } if ($check_pet) $G_url->add('pet', 1); interf_alerte::aff_enregistres($cadre); $attaque = new attaque($perso, $attaquant, $defenseur); $interf = $cadre->add( $G_interf->creer_combat() ); $attaque->set_interface( $interf ); $attaque->attaque($distance, $type, $pa_attaque, $R, $pet, $defenseur_en_defense); if( interf_debug::doit_aff_bouton() ) { $lien = $interf->add( new interf_bal_smpl('a', '', 'debug_droit', 'icone icone-debug') ); $lien->set_attribut('onclick', 'return debugs();'); } //Suppression des PA si c'est une attaque du perso if ($type == 'perso' OR $type == 'monstre' OR $type == 'batiment') { $perso->set_pa($perso->get_pa() - $pa_attaque); $perso->sauver(); } //Sinon c'est une arme de siège, et il faut modifier son rechargement elseif ($type == 'siege' OR $type == 'ville') { $perso->set_pa($perso->get_pa() - $pa_attaque); $perso->sauver(); } $interf_princ->maj_perso(); $interf_princ->maj_tooltips(); //Mise dans les journaux si attaque pvp if($type == 'perso') { //Insertion de l'attaque dans les journaux des 2 joueurs //Journal de l'attaquant if(!$check_pet) $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'attaque', '".mysql_escape_string(sSQL($perso->get_nom()))."', '".mysql_escape_string(sSQL($defenseur->get_nom()))."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; else $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'attaque', '".mysql_escape_string(sSQL($attaquant->get_nom()))."', '".mysql_escape_string(sSQL($defenseur->get_nom()))."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); // Creation du log du combat $combat = new combat(); $combat->attaquant = $perso->get_id(); $combat->defenseur = $perso_defenseur->get_id(); $combat->combat = $attaque->get_log_combat();//$log_combat; $combat->id_journal = $db->last_insert_id(); $combat->sauver(); //Journal du défenseur if(!$check_pet_def) $requete = "INSERT INTO journal VALUES(NULL, ".$perso_defenseur->get_id().", 'defense', '".mysql_escape_string($perso_defenseur->get_nom())."', '".mysql_escape_string($perso->get_nom())."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; else $requete = "INSERT INTO journal VALUES(NULL, ".$perso_defenseur->get_id().", 'defense', '".mysql_escape_string($defenseur->get_nom())."', '".mysql_escape_string($perso->get_nom())."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); $combat = new combat(); $combat->attaquant = $perso->get_id(); $combat->defenseur = $perso_defenseur->get_id(); $combat->combat = $attaque->get_log_combat();//$log_combat; $combat->id_journal = $db->last_insert_id(); $combat->sauver(); if($defenseur->get_hp() <= 0 && !$check_pet_def) { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'tue', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($perso_defenseur->get_nom())."', NOW(), 0, 0, ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); $requete = "INSERT INTO journal VALUES(NULL, ".$perso_defenseur->get_id().", 'mort', '".mysql_escape_string($perso_defenseur->get_nom())."', '".mysql_escape_string($perso->get_nom())."', NOW(), 0, 0, ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); } if($attaquant->get_hp() <= 0 && !$check_pet) { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'mort', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($perso_defenseur->get_nom())."', NOW(), 0, 0, ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); $requete = "INSERT INTO journal VALUES(NULL, ".$perso_defenseur->get_id().", 'tue', '".mysql_escape_string($perso_defenseur->get_nom())."', '".mysql_escape_string($perso->get_nom())."', NOW(), 0, 0, ".$perso_defenseur->get_x().", ".$perso_defenseur->get_y().")"; $db->query($requete); } } //Mise dans le journal si attaque sur batiment elseif($type == 'batiment') { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'attaque', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($defenseur->get_nom())."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); // Creation du log du combat $combat = new combat(); $combat->attaquant = $perso->get_id(); $combat->defenseur = $defenseur->get_id(); $combat->combat = $attaque->get_log_combat(); $combat->id_journal = $db->last_insert_id(); $combat->sauver(); if($defenseur->get_hp() <= 0) { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'destruction', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($defenseur->get_nom())."', NOW(), 0, 0, ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); } } elseif($type == 'ville') { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'siege', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($map_royaume->get_nom())."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); // Creation du log du combat $combat = new combat(); $combat->attaquant = $perso->get_id(); $combat->defenseur = $defenseur->get_id(); $combat->combat = $attaque->get_log_combat();//$log_combat; $combat->id_journal = $db->last_insert_id(); $combat->sauver(); if($map_royaume->is_raz()) { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'destruction', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($map_royaume->get_nom())."', NOW(), 0, 0, ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); } } elseif($type == 'siege') { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'siege', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($defenseur->get_nom())."', NOW(), ".($defense_hp_avant - $defense_hp_apres).", ".($attaque_hp_avant - $attaque_hp_apres).", ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); // Creation du log du combat $combat = new combat(); $combat->attaquant = $perso->get_id(); $combat->defenseur = $defenseur->get_id(); $combat->combat = $attaque->get_log_combat();//$log_combat; $combat->id_journal = $db->last_insert_id(); $combat->sauver(); if($defenseur->get_hp() <= 0) { $requete = "INSERT INTO journal VALUES(NULL, ".$perso->get_id().", 'destruction', '".mysql_escape_string($perso->get_nom())."', '".mysql_escape_string($defenseur->get_nom())."', NOW(), 0, 0, ".$defenseur->get_x().", ".$defenseur->get_y().")"; $db->query($requete); } } } else $cadre->add( new interf_alerte(interf_alerte::msg_erreur, false, false, 'Vous n\'avez pas assez de points d\'actions.') ); } ?>
agpl-3.0
dmitr25/demobbed-viewer
js/nuEventsData/nuMu/loadEvent10180007950.js
7832
demobbed.resetEvent(); demobbed.event().id(10180007950); demobbed.event().date(1277775832000); demobbed.event().hitsTT()[0] = [ new HitTT(10000, 173.93, 188.39, 38.39), new HitTT(10001, 163.16, 188.39, 8.31), new HitTT(10002, 173.36, 201.79, 70.94), new HitTT(10003, 170.72, 201.79, 135.75), new HitTT(10004, 146.6, 201.79, 14.34), new HitTT(10005, 162.44, 201.79, 15.91), new HitTT(10006, 165.08, 201.79, 8.08), new HitTT(10007, 167.72, 201.79, 78.8), new HitTT(10008, 170.8, 215.19, 19.98), new HitTT(10009, 173.44, 215.19, 8.15), new HitTT(10010, 176.08, 215.19, 28.96), new HitTT(10011, 178.72, 215.19, 3.64), new HitTT(10012, 144.18, 215.19, 1.78), new HitTT(10013, 165.08, 228.59, 110.39), new HitTT(10014, 157.16, 228.59, 67.78), new HitTT(10015, 173.29, 228.59, 19.2), new HitTT(10016, 173.68, 241.99, 21.36), new HitTT(10017, 144.33, 241.99, 3.91), new HitTT(10018, 162.81, 241.99, 6.85), new HitTT(10019, 173.8, 255.39, 24.13), new HitTT(10020, 152.47, 255.39, 69.35), new HitTT(10021, 176.52, 268.79, 9.88), new HitTT(10022, 175.91, 282.19, 19.86), new HitTT(10023, 178.55, 282.19, 20.7), new HitTT(10024, 186.47, 282.19, 10.78), new HitTT(10025, 178.66, 295.59, 19.23), new HitTT(10026, 178.64, 308.99, 30.67), new HitTT(10027, 178.91, 322.39, 27.27), new HitTT(10028, 181.46, 335.79, 32.02), new HitTT(10029, 181.43, 349.19, 24.48), new HitTT(10030, 181.7, 362.59, 19.22), new HitTT(10031, 183.76, 375.99, 25.3), new HitTT(10032, 183.83, 389.39, 7.14), new HitTT(10033, 183.84, 402.79, 18.8), new HitTT(10034, 186.59, 416.19, 7.8), new HitTT(10035, 186.75, 429.59, 10.88), new HitTT(10036, 184.34, 442.99, 13.95), new HitTT(10037, 192.26, 442.99, 4.94), new HitTT(10038, 186.98, 442.99, 5.98), new HitTT(10039, 189.69, 456.39, 11.76), new HitTT(10040, 189.92, 469.79, 21.26), new HitTT(10041, 192.35, 483.19, 17.67), new HitTT(10042, 192.02, 496.59, 31.35), new HitTT(10043, 194.07, 509.99, 6.31), new HitTT(10044, 197.25, 523.39, 18.56), new HitTT(10045, 197.26, 536.79, 4.71), new HitTT(10046, 200.04, 550.19, 24.85), new HitTT(10047, 202.35, 563.59, 31.41) ]; demobbed.event().hitsTT()[1] = [ new HitTT(11000, -224.91, 173.53, 7.48), new HitTT(11001, -232.83, 173.53, 8.9), new HitTT(11002, -222.42, 186.93, 4.89), new HitTT(11003, -256.74, 186.93, 10.89), new HitTT(11004, -225.06, 186.93, 17.37), new HitTT(11005, -251.46, 186.93, 9.4), new HitTT(11006, -246.18, 186.93, 2.88), new HitTT(11007, -254.1, 186.93, 5.73), new HitTT(11008, -236.3, 200.33, 28.52), new HitTT(11009, -238.94, 200.33, 9.96), new HitTT(11010, -241.58, 200.33, 106.53), new HitTT(11011, -244.22, 200.33, 181.99), new HitTT(11012, -265.34, 200.33, 7.94), new HitTT(11013, -254.78, 200.33, 24.08), new HitTT(11014, -246.86, 200.33, 23.37), new HitTT(11015, -238.27, 213.73, 13.68), new HitTT(11016, -243.55, 213.73, 6.31), new HitTT(11017, -248.83, 213.73, 26.72), new HitTT(11018, -246.19, 213.73, 14.12), new HitTT(11019, -270.16, 227.13, 7.66), new HitTT(11020, -267.52, 227.13, 7.75), new HitTT(11021, -251.68, 227.13, 35.58), new HitTT(11022, -249.04, 227.13, 40.36), new HitTT(11023, -246.4, 227.13, 205.87), new HitTT(11024, -243.76, 227.13, 4.94), new HitTT(11025, -235.84, 227.13, 16.3), new HitTT(11026, -225.28, 227.13, 5.88), new HitTT(11027, -232.93, 240.53, 34.39), new HitTT(11028, -261.97, 240.53, 1.63), new HitTT(11029, -230.29, 240.53, 7.98), new HitTT(11030, -230.03, 253.93, 13.98), new HitTT(11031, -227.69, 267.33, 26.73), new HitTT(11032, -224.91, 280.73, 26.85), new HitTT(11033, -222.39, 294.13, 8.84), new HitTT(11034, -219.82, 307.53, 30.98), new HitTT(11035, -217.24, 320.93, 14.12), new HitTT(11036, -215.11, 334.33, 12.22), new HitTT(11037, -211.86, 347.73, 46.73), new HitTT(11038, -209.19, 361.13, 10.74), new HitTT(11039, -206.77, 374.53, 9.49), new HitTT(11040, -203.53, 387.93, 19.66), new HitTT(11041, -201, 401.33, 4.86), new HitTT(11042, -198.48, 414.73, 11.86), new HitTT(11043, -195.79, 428.13, 24.23), new HitTT(11044, -195.79, 441.53, 12.92), new HitTT(11045, -193.15, 441.53, 17.42), new HitTT(11046, -190.5, 454.93, 19.65), new HitTT(11047, -190.36, 468.33, 9.77), new HitTT(11048, -185.38, 481.73, 43.77), new HitTT(11049, -182.74, 481.73, 9.97), new HitTT(11050, -182.62, 495.13, 17.45), new HitTT(11051, -180.41, 508.53, 11.31), new HitTT(11052, -177.74, 521.93, 9.37), new HitTT(11053, -174.84, 535.33, 13.33), new HitTT(11054, -174.3, 548.73, 16.76), new HitTT(11055, -169.27, 562.13, 10.63) ]; demobbed.event().hitsRPC()[0] = [ new HitRPC(20000, 212.7, 672.71, 2.6), new HitRPC(20001, 215.3, 686.71, 2.6), new HitRPC(20002, 216.6, 693.71, 5.2), new HitRPC(20003, 217.9, 700.71, 7.8), new HitRPC(20004, 219.2, 707.71, 5.2), new HitRPC(20005, 220.5, 714.71, 2.6), new HitRPC(20006, 220.5, 721.71, 2.6), new HitRPC(20007, 221.8, 728.71, 5.2), new HitRPC(20008, 223.1, 742.71, 2.6), new HitRPC(20009, 247.8, 888.01, 5.2), new HitRPC(20010, 249.1, 895.01, 2.6), new HitRPC(20011, 247.8, 902.01, 5.2), new HitRPC(20012, 251.7, 909.01, 2.6), new HitRPC(20013, 251.7, 916.01, 2.6), new HitRPC(20014, 253, 923.01, 5.2), new HitRPC(20015, 254.3, 930.01, 2.6), new HitRPC(20016, 254.3, 937.01, 2.6), new HitRPC(20017, 255.6, 944.01, 5.2) ]; demobbed.event().hitsRPC()[1] = [ new HitRPC(21000, -148.7, 672.71, 3.5), new HitRPC(21001, -145.2, 686.71, 3.5), new HitRPC(21002, -145.2, 693.71, 3.5), new HitRPC(21003, -141.7, 700.71, 3.5), new HitRPC(21004, -141.7, 707.71, 3.5), new HitRPC(21005, -141.7, 714.71, 3.5), new HitRPC(21006, -138.2, 721.71, 3.5), new HitRPC(21007, -138.2, 728.71, 3.5), new HitRPC(21008, -134.7, 742.71, 3.5), new HitRPC(21009, -103.7, 888.01, 3.5), new HitRPC(21010, -103.7, 895.01, 3.5), new HitRPC(21011, -100.2, 902.01, 3.5), new HitRPC(21012, -100.2, 909.01, 3.5), new HitRPC(21013, -96.7, 916.01, 3.5), new HitRPC(21014, -96.7, 923.01, 3.5), new HitRPC(21015, -96.7, 930.01, 3.5), new HitRPC(21016, -93.2, 937.01, 3.5), new HitRPC(21017, -93.2, 944.01, 3.5) ]; demobbed.event().hitsDT()[0] = [ new HitDT(30000, 201.01, 574, 1.51), new HitDT(30001, 203.11, 577.64, 0.6), new HitDT(30002, 202.01, 581.7, 1.45), new HitDT(30003, 204.11, 585.34, 0.63), new HitDT(30004, 212.44, 644.16, 1.63), new HitDT(30005, 210.34, 647.8, 1.1), new HitDT(30006, 213.44, 651.86, 1.7), new HitDT(30007, 211.34, 655.5, 1.03), new HitDT(30008, 224.55, 755.32, 1.64), new HitDT(30009, -352.9, 759.26, 1.38), new HitDT(30010, 226.65, 758.96, 0.55), new HitDT(30011, 225.55, 763.02, 1.82), new HitDT(30012, 227.66, 766.66, 0.62), new HitDT(30013, 201.15, 849.28, 1.68), new HitDT(30014, 241.05, 852.89, 0.91), new HitDT(30015, 244.15, 856.94, 1.72), new HitDT(30016, 242.06, 860.59, 1.12), new HitDT(30017, 258.69, 956.67, 1.59), new HitDT(30018, 256.59, 960.31, 0.6), new HitDT(30019, 259.69, 964.37, 1.6), new HitDT(30020, 257.59, 968.01, 1.11), new HitDT(30021, 268.91, 1057.91, 1.26), new HitDT(30022, 271.01, 1061.54, 0.71), new HitDT(30023, 269.91, 1065.6, 1.24), new HitDT(30024, 272.01, 1069.24, 0.72) ]; demobbed.event().verticesECC([new Vertex([23702.1, 29553, 32565], [170.016, -241.576, 193.138])]); demobbed.event().tracksECC([ new TrackECC(0, 6, [23686.4, 29041, 33677], [-0.0259, -0.5255]), new TrackECC(1, 6, [23519.1, 29712.1, 33677], [-0.2106, 0.1133]), new TrackECC(2, 1, [24211.3, 30783.7, 38780], [0.0828, 0.1985]), new TrackECC(3, 7, [23791.8, 29665.3, 32405], [-0.211, -0.3041]), new TrackECC(4, 2, [24104.7, 29183.3, 33677], [0.357, -0.3346]) ]); demobbed.mgrDrawED().onEventChange(); demobbed.mgrDrawECC().onEventChange();
agpl-3.0
Naeka/vosae-app
www/timeline/api/resources/__init__.py
473
# -*- coding:Utf-8 -*- from timeline.api.resources import contacts_entries from timeline.api.resources.contacts_entries import * from timeline.api.resources import invoicing_entries from timeline.api.resources.invoicing_entries import * from timeline.api.resources import timeline_entry_resource from timeline.api.resources.timeline_entry_resource import * __all__ = ( contacts_entries.__all__ + invoicing_entries.__all__ + timeline_entry_resource.__all__ )
agpl-3.0
aydancoskun/fairness
classes/modules/install/InstallSchema_1050A.class.php
1500
<?php /********************************************************************************* * FairnessTNA is a Workforce Management program forked from TimeTrex in 2013, * copyright Aydan Coskun. Original code base is copyright TimeTrex Software Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact Aydan Coskun via issue tracker on github.com/aydancoskun ********************************************************************************/ /** * @package Modules\Install */ class InstallSchema_1050A extends InstallSchema_Base { /** * @return bool */ function preInstall() { Debug::text('preInstall: '. $this->getVersion(), __FILE__, __LINE__, __METHOD__, 9); return TRUE; } /** * @return bool */ function postInstall() { Debug::text('postInstall: '. $this->getVersion(), __FILE__, __LINE__, __METHOD__, 9); return TRUE; } } ?>
agpl-3.0
kaltura/playkit-android
playkit/src/main/java/com/kaltura/playkit/PKAbrFilter.java
114
package com.kaltura.playkit; public enum PKAbrFilter { NONE, BITRATE, HEIGHT, WIDTH, PIXEL }
agpl-3.0
pinfort/mastodon
app/models/area_feed.rb
1224
# frozen_string_literal: true class AreaFeed < PublicFeed # @param [Array<String>] instances # @param [Account] account # @param [Hash] options # @option [Boolean] :with_replies # @option [Boolean] :with_reblogs # @option [Boolean] :local # @option [Boolean] :remote # @option [Boolean] :only_media def initialize(instances, account, options = {}) @instances = instances super(account, options) end # @param [Integer] limit # @param [Integer] max_id # @param [Integer] since_id # @param [Integer] min_id # @return [Array<Status>] def get(limit, max_id = nil, since_id = nil, min_id = nil) scope = public_scope scope.merge!(posted_in_domains) scope.merge!(without_replies_scope) unless with_replies? scope.merge!(without_reblogs_scope) unless with_reblogs? scope.merge!(local_only_scope) if local_only? scope.merge!(remote_only_scope) if remote_only? scope.merge!(account_filters_scope) if account? scope.merge!(media_only_scope) if media_only? scope.cache_ids.to_a_paginated_by_id(limit, max_id: max_id, since_id: since_id, min_id: min_id) end private def posted_in_domains Status.group(:id).posted_in_domains(@instances) end end
agpl-3.0
hamstar0/tml-hamstarhelpers-mod
HamstarHelpers/Helpers/HUD/HUDHelpers.cs
429
using System; using Terraria; namespace HamstarHelpers.Helpers.HUD { /// <summary> /// Assorted static "helper" functions pertaining to general HUD. /// </summary> public partial class HUDHelpers { /// <summary> /// Indicates if `Main.LocalPlayer.mouseInterface` was true at the end of the previous tick. /// </summary> public static bool IsMouseInterfacingWithUI => ModHelpersMod.Instance.MouseInterface; } }
agpl-3.0