code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Fox\Controllers; use \Fox\Core\Exceptions\BadRequest; use \Fox\Core\Exceptions\Forbidden; use \Fox\Core\Exceptions\Error; class EntityManager extends \Fox\Core\Controllers\Base { protected function checkControllerAccess() { if (!$this->getUser()->isAdmin()) { throw new Forbidden(); } } public function actionCreateEntity($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } if (empty($data['name']) || empty($data['type'])) { throw new BadRequest(); } $name = $data['name']; $type = $data['type']; $name = filter_var($name, \FILTER_SANITIZE_STRING); $type = filter_var($type, \FILTER_SANITIZE_STRING); $params = array(); if (!empty($data['labelSingular'])) { $params['labelSingular'] = $data['labelSingular']; } if (!empty($data['labelPlural'])) { $params['labelPlural'] = $data['labelPlural']; } if (!empty($data['stream'])) { $params['stream'] = $data['stream']; } if (!empty($data['sortBy'])) { $params['sortBy'] = $data['sortBy']; } if (!empty($data['sortDirection'])) { $params['asc'] = $data['sortDirection'] === 'asc'; } $result = $this->getContainer()->get('entityManagerUtil')->create($name, $type, $params); if ($result) { $tabList = $this->getConfig()->get('tabList', []); $tabList[] = $name; $this->getConfig()->set('tabList', $tabList); $this->getConfig()->save(); $this->getContainer()->get('dataManager')->rebuild(); } else { throw new Error(); } return true; } public function actionUpdateEntity($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } if (empty($data['name'])) { throw new BadRequest(); } $name = $data['name']; $name = filter_var($name, \FILTER_SANITIZE_STRING); if (!empty($data['sortDirection'])) { $data['asc'] = $data['sortDirection'] === 'asc'; } $result = $this->getContainer()->get('entityManagerUtil')->update($name, $data); if ($result) { $this->getContainer()->get('dataManager')->clearCache(); } else { throw new Error(); } return true; } public function actionRemoveEntity($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } if (empty($data['name'])) { throw new BadRequest(); } $name = $data['name']; $name = filter_var($name, \FILTER_SANITIZE_STRING); $result = $this->getContainer()->get('entityManagerUtil')->delete($name); if ($result) { $tabList = $this->getConfig()->get('tabList', []); if (($key = array_search($name, $tabList)) !== false) { unset($tabList[$key]); $tabList = array_values($tabList); } $this->getConfig()->set('tabList', $tabList); $this->getConfig()->save(); $this->getContainer()->get('dataManager')->clearCache(); } else { throw new Error(); } return true; } public function actionCreateLink($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } $paramList = [ 'entity', 'entityForeign', 'link', 'linkForeign', 'label', 'labelForeign', 'linkType' ]; $d = array(); foreach ($paramList as $item) { if (empty($data[$item])) { throw new BadRequest(); } $d[$item] = filter_var($data[$item], \FILTER_SANITIZE_STRING); } $result = $this->getContainer()->get('entityManagerUtil')->createLink($d); if ($result) { $this->getContainer()->get('dataManager')->rebuild(); } else { throw new Error(); } return true; } public function actionUpdateLink($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } $paramList = [ 'entity', 'entityForeign', 'link', 'linkForeign', 'label', 'labelForeign' ]; $d = array(); foreach ($paramList as $item) { $d[$item] = filter_var($data[$item], \FILTER_SANITIZE_STRING); } $result = $this->getContainer()->get('entityManagerUtil')->updateLink($d); if ($result) { $this->getContainer()->get('dataManager')->clearCache(); } else { throw new Error(); } return true; } public function actionRemoveLink($params, $data, $request) { if (!$request->isPost()) { throw new BadRequest(); } $paramList = [ 'entity', 'link', ]; $d = array(); foreach ($paramList as $item) { $d[$item] = filter_var($data[$item], \FILTER_SANITIZE_STRING); } $result = $this->getContainer()->get('entityManagerUtil')->deleteLink($d); if ($result) { $this->getContainer()->get('dataManager')->clearCache(); } else { throw new Error(); } return true; } }
ilovefox8/zhcrm
application/Fox/Controllers/EntityManager.php
PHP
gpl-3.0
5,645
import logging from django.core.management.base import BaseCommand from catalog.core.visualization.data_access import visualization_cache logger = logging.getLogger(__name__) class Command(BaseCommand): help = '''Build pandas dataframe cache of primary data''' def handle(self, *args, **options): visualization_cache.get_or_create_many()
comses/catalog
catalog/core/management/commands/populate_visualization_cache.py
Python
gpl-3.0
359
/* -*- Mode: c; c-basic-offset: 2 -*- * * Storage.cpp - Redland C++ Storage class interface * * Copyright (C) 2008, David Beckett http://www.dajobe.org/ * * This package is Free Software and part of Redland http://librdf.org/ * * It is licensed under the following three licenses as alternatives: * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version * 2. GNU General Public License (GPL) V2 or any newer version * 3. Apache License, V2.0 or any newer version * * You may not use this file except in compliance with at least one of * the above three licenses. * * See LICENSE.html or LICENSE.txt at the top of this package for the * complete terms and further detail along with the license texts for * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. * * */ #ifndef REDLANDPP_STORAGE_HPP #define REDLANDPP_STORAGE_HPP #ifdef HAVE_CONFIG_H #include <redlandpp_config.h> #endif #include <redland.h> #include "redlandpp/World.hpp" #include "redlandpp/Exception.hpp" #include "redlandpp/Wrapper.hpp" #include "redlandpp/Stream.hpp" #include "redlandpp/Uri.hpp" namespace Redland { class Storage : public Wrapper<librdf_storage> { public: Storage(World* w, const std::string& sn, const std::string& n="", const std::string& opts="") throw(Exception); Storage(World& w, const std::string& sn, const std::string& n="", const std::string& opts="") throw(Exception); ~Storage(); // public methods const std::string name() const; const std::string str() const; protected: World* world_; private: std::string storage_name_; std::string name_; std::string options_; void init() throw(Exception); friend std::ostream& operator<< (std::ostream& os, const Storage& p); friend std::ostream& operator<< (std::ostream& os, const Storage* p); }; class MemoryStorage : public Storage { public: MemoryStorage(World* w, const std::string n="", const std::string opts="") throw(Exception); MemoryStorage(World& w, const std::string n="", const std::string opts="") throw(Exception); ~MemoryStorage(); }; } // namespace Redland #endif
dajobe/redlandpp
redlandpp/Storage.hpp
C++
gpl-3.0
2,188
/* * 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 se.kth.kandy.ejb.restservice; import java.util.Set; import javax.ws.rs.core.Application; /** * * @author Hossein */ @javax.ws.rs.ApplicationPath("api") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); addRestResourceClasses(resources); return resources; } /** * Do not modify addRestResourceClasses() method. It is automatically populated with all resources defined in the * project. If required, comment out calling this method in getClasses(). */ private void addRestResourceClasses( Set<Class<?>> resources) { resources.add(se.kth.kandy.ejb.restservice.ClusterCostFacadeREST.class); resources.add(se.kth.kandy.ejb.restservice.KaramelStatisticsFacadeREST.class); } }
karamelchef/kandy
CloudServiceRecommender/src/main/java/se/kth/kandy/ejb/restservice/ApplicationConfig.java
Java
gpl-3.0
1,020
package com.capgemini.playingwithsqlite; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ShowListAdapter extends ArrayAdapter<Show> { public ShowListAdapter(Context context, int resource) { super(context, resource); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater viewInflater = LayoutInflater.from(getContext()); view = viewInflater.inflate(R.layout.show_list_row, null); } Show show = getItem(position); if (show != null) { TextView title = (TextView) view.findViewById(R.id.show_title); TextView year = (TextView) view.findViewById(R.id.year); if (title != null) { title.setText(show.getTitle()); } if (year != null) { year.setText(show.getYear() + ""); } } return view; } }
larseknu/android_programmering_2014
Lecture 08/src/com/capgemini/playingwithsqlite/ShowListAdapter.java
Java
gpl-3.0
1,116
/* * Copyright (C) 2016-2022 Yaroslav Pronin <proninyaroslav@mail.ru> * * This file is part of LibreTorrent. * * LibreTorrent 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. * * LibreTorrent 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 LibreTorrent. If not, see <http://www.gnu.org/licenses/>. */ package org.proninyaroslav.libretorrent.core.model.session; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; import org.apache.commons.io.FileUtils; import org.libtorrent4j.AlertListener; import org.libtorrent4j.AnnounceEntry; import org.libtorrent4j.ErrorCode; import org.libtorrent4j.Pair; import org.libtorrent4j.SessionHandle; import org.libtorrent4j.SessionManager; import org.libtorrent4j.SessionParams; import org.libtorrent4j.SettingsPack; import org.libtorrent4j.Sha1Hash; import org.libtorrent4j.TcpEndpoint; import org.libtorrent4j.TorrentFlags; import org.libtorrent4j.TorrentHandle; import org.libtorrent4j.TorrentInfo; import org.libtorrent4j.Vectors; import org.libtorrent4j.WebSeedEntry; import org.libtorrent4j.alerts.Alert; import org.libtorrent4j.alerts.AlertType; import org.libtorrent4j.alerts.ListenFailedAlert; import org.libtorrent4j.alerts.MetadataReceivedAlert; import org.libtorrent4j.alerts.PortmapErrorAlert; import org.libtorrent4j.alerts.SessionErrorAlert; import org.libtorrent4j.alerts.TorrentAlert; import org.libtorrent4j.swig.add_torrent_params; import org.libtorrent4j.swig.alert; import org.libtorrent4j.swig.alert_category_t; import org.libtorrent4j.swig.bdecode_node; import org.libtorrent4j.swig.byte_vector; import org.libtorrent4j.swig.create_torrent; import org.libtorrent4j.swig.entry; import org.libtorrent4j.swig.error_code; import org.libtorrent4j.swig.int_vector; import org.libtorrent4j.swig.ip_filter; import org.libtorrent4j.swig.libtorrent; import org.libtorrent4j.swig.session_params; import org.libtorrent4j.swig.settings_pack; import org.libtorrent4j.swig.sha1_hash; import org.libtorrent4j.swig.string_vector; import org.libtorrent4j.swig.tcp_endpoint_vector; import org.libtorrent4j.swig.torrent_flags_t; import org.libtorrent4j.swig.torrent_handle; import org.libtorrent4j.swig.torrent_info; import org.proninyaroslav.libretorrent.core.exception.DecodeException; import org.proninyaroslav.libretorrent.core.exception.TorrentAlreadyExistsException; import org.proninyaroslav.libretorrent.core.exception.UnknownUriException; import org.proninyaroslav.libretorrent.core.model.AddTorrentParams; import org.proninyaroslav.libretorrent.core.model.TorrentEngineListener; import org.proninyaroslav.libretorrent.core.model.data.MagnetInfo; import org.proninyaroslav.libretorrent.core.model.data.Priority; import org.proninyaroslav.libretorrent.core.model.data.SessionStats; import org.proninyaroslav.libretorrent.core.model.data.entity.FastResume; import org.proninyaroslav.libretorrent.core.model.data.entity.Torrent; import org.proninyaroslav.libretorrent.core.model.data.metainfo.TorrentMetaInfo; import org.proninyaroslav.libretorrent.core.settings.SessionSettings; import org.proninyaroslav.libretorrent.core.storage.TorrentRepository; import org.proninyaroslav.libretorrent.core.system.FileDescriptorWrapper; import org.proninyaroslav.libretorrent.core.system.FileSystemFacade; import org.proninyaroslav.libretorrent.core.system.SystemFacade; import org.proninyaroslav.libretorrent.core.utils.Utils; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class TorrentSessionImpl extends SessionManager implements TorrentSession { private static final String TAG = TorrentSession.class.getSimpleName(); private static final int[] INNER_LISTENER_TYPES = new int[] { AlertType.ADD_TORRENT.swig(), AlertType.METADATA_RECEIVED.swig(), AlertType.SESSION_ERROR.swig(), AlertType.PORTMAP_ERROR.swig(), AlertType.LISTEN_FAILED.swig(), AlertType.LOG.swig(), AlertType.DHT_LOG.swig(), AlertType.PEER_LOG.swig(), AlertType.PORTMAP_LOG.swig(), AlertType.TORRENT_LOG.swig(), AlertType.SESSION_STATS.swig() }; /* Base unit in KiB. Used for create torrent */ private static final int[] pieceSize = {0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; private static final String PEER_FINGERPRINT = "Lr"; /* called peer id */ private static final String USER_AGENT = "LibreTorrent %s"; private InnerListener innerListener; private ConcurrentLinkedQueue<TorrentEngineListener> listeners = new ConcurrentLinkedQueue<>(); private SessionSettings settings = new SessionSettings(); private ReentrantLock settingsLock = new ReentrantLock(); private Queue<LoadTorrentTask> restoreTorrentsQueue = new LinkedList<>(); private ExecutorService loadTorrentsExec; private ConcurrentHashMap<String, TorrentDownload> torrentTasks = new ConcurrentHashMap<>(); /* Wait list for non added magnets */ private HashSet<String> magnets = new HashSet<>(); private ConcurrentHashMap<String, byte[]> loadedMagnets = new ConcurrentHashMap<>(); private ArrayList<String> addTorrentsList = new ArrayList<>(); private ReentrantLock syncMagnet = new ReentrantLock(); private CompositeDisposable disposables = new CompositeDisposable(); private TorrentRepository repo; private FileSystemFacade fs; private SystemFacade system; private SessionLogger sessionLogger; private boolean started; private AtomicBoolean stopRequested; private Thread parseIpFilterThread; public TorrentSessionImpl(@NonNull TorrentRepository repo, @NonNull FileSystemFacade fs, @NonNull SystemFacade system) { super(false); this.stopRequested = new AtomicBoolean(false); this.started = false; this.sessionLogger = new SessionLogger(); this.repo = repo; this.fs = fs; this.system = system; innerListener = new InnerListener(); loadTorrentsExec = Executors.newCachedThreadPool(); } @Override public SessionLogger getLogger() { return sessionLogger; } @Override public void addListener(TorrentEngineListener listener) { listeners.add(listener); } @Override public void removeListener(TorrentEngineListener listener) { listeners.remove(listener); } @Override public TorrentDownload getTask(String id) { return torrentTasks.get(id); } public void setSettings(@NonNull SessionSettings settings) { setSettings(settings, true); } @Override public void setSettings(@NonNull SessionSettings settings, boolean keepPort) { settingsLock.lock(); try { this.settings = settings; applySettings(settings, keepPort); } finally { settingsLock.unlock(); } } @Override public SessionSettings getSettings() { settingsLock.lock(); try { return new SessionSettings(settings); } finally { settingsLock.unlock(); } } @Override public byte[] getLoadedMagnet(String hash) { return loadedMagnets.get(hash); } @Override public void removeLoadedMagnet(String hash) { loadedMagnets.remove(hash); } private boolean operationNotAllowed() { return swig() == null || stopRequested.get(); } @Override public Torrent addTorrent( @NonNull AddTorrentParams params, boolean removeFile ) throws IOException, TorrentAlreadyExistsException, DecodeException, UnknownUriException { if (operationNotAllowed()) return null; Torrent torrent = new Torrent( params.sha1hash, params.downloadPath, params.name, params.addPaused, System.currentTimeMillis(), params.sequentialDownload, params.firstLastPiecePriority ); byte[] bencode = null; if (params.fromMagnet) { bencode = getLoadedMagnet(params.sha1hash); removeLoadedMagnet(params.sha1hash); if (bencode == null) torrent.setMagnetUri(params.source); } if (repo.getTorrentById(torrent.id) != null) { mergeTorrent(torrent.id, params, bencode); throw new TorrentAlreadyExistsException(); } repo.addTorrent(torrent); if (!params.tags.isEmpty()) { repo.replaceTags(torrent.id, params.tags); } if (!torrent.isDownloadingMetadata()) { /* * This is possible if the magnet data came after Torrent object * has already been created and nothing is known about the received data */ if (params.filePriorities.length == 0) { try (FileDescriptorWrapper w = fs.getFD(Uri.parse(params.source))) { FileDescriptor outFd = w.open("r"); try (FileInputStream is = new FileInputStream(outFd)) { TorrentMetaInfo info = new TorrentMetaInfo(is); params.filePriorities = new Priority[info.fileCount]; Arrays.fill(params.filePriorities, Priority.DEFAULT); } } catch (FileNotFoundException e) { /* Ignore */ } } } try { download(torrent.id, params, bencode); } catch (Exception e) { repo.deleteTorrent(torrent); throw e; } finally { if (removeFile && !params.fromMagnet) { try { fs.deleteFile(Uri.parse(params.source)); } catch (UnknownUriException e) { // Ignore } } } return torrent; } private void download(String id, AddTorrentParams params, byte[] bencode) throws IOException, UnknownUriException { if (operationNotAllowed()) return; cancelFetchMagnet(id); Torrent torrent = repo.getTorrentById(id); if (torrent == null) throw new IOException("Torrent " + id + " is null"); addTorrentsList.add(params.sha1hash); String path = fs.makeFileSystemPath(params.downloadPath); File saveDir = new File(path); if (torrent.isDownloadingMetadata()) { download(params.source, saveDir, params.addPaused, params.sequentialDownload); return; } TorrentDownload task = torrentTasks.get(torrent.id); if (task != null) task.remove(false); if (params.fromMagnet) { download(bencode, saveDir, params.filePriorities, params.sequentialDownload, params.addPaused, null); } else { try (FileDescriptorWrapper w = fs.getFD(Uri.parse(params.source))) { FileDescriptor fd = w.open("r"); try (FileInputStream fin = new FileInputStream(fd)) { FileChannel chan = fin.getChannel(); download(new TorrentInfo(chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size())), saveDir, params.filePriorities, params.sequentialDownload, params.addPaused, null); } } } } @Override public void deleteTorrent(@NonNull String id, boolean withFiles) { if (operationNotAllowed()) return; TorrentDownload task = getTask(id); if (task == null) { Torrent torrent = repo.getTorrentById(id); if (torrent != null) repo.deleteTorrent(torrent); notifyListeners((listener) -> listener.onTorrentRemoved(id)); } else { task.remove(withFiles); } } @Override public void restoreTorrents() { if (operationNotAllowed()) return; for (Torrent torrent : repo.getAllTorrents()) { if (torrent == null || isTorrentAlreadyRunning(torrent.id)) continue; String path = null; try { path = fs.makeFileSystemPath(torrent.downloadPath); } catch (UnknownUriException e) { Log.e(TAG, "Unable to restore torrent:"); Log.e(TAG, Log.getStackTraceString(e)); } LoadTorrentTask loadTask = new LoadTorrentTask(torrent.id); if (path != null && torrent.isDownloadingMetadata()) { loadTask.putMagnet( torrent.getMagnet(), new File(path), torrent.manuallyPaused, torrent.sequentialDownload ); } restoreTorrentsQueue.add(loadTask); } runNextLoadTorrentTask(); } @Override public MagnetInfo fetchMagnet(@NonNull String uri) throws Exception { if (operationNotAllowed()) return null; org.libtorrent4j.AddTorrentParams params = parseMagnetUri(uri); org.libtorrent4j.AddTorrentParams resParams = fetchMagnet(params); if (resParams == null) return null; List<Priority> priorities = Arrays.asList(PriorityConverter.convert(resParams.filePriorities())); return new MagnetInfo(uri, resParams.getInfoHashes().getBest().toHex(), resParams.getName(), priorities); } @Override public MagnetInfo parseMagnet(@NonNull String uri) { org.libtorrent4j.AddTorrentParams p = org.libtorrent4j.AddTorrentParams.parseMagnetUri(uri); String sha1hash = p.getInfoHashes().getBest().toHex(); String name = (TextUtils.isEmpty(p.getName()) ? sha1hash : p.getName()); return new MagnetInfo(uri, sha1hash, name, Arrays.asList(PriorityConverter.convert(p.filePriorities()))); } private org.libtorrent4j.AddTorrentParams fetchMagnet(org.libtorrent4j.AddTorrentParams params) throws Exception { if (operationNotAllowed()) return null; add_torrent_params p = params.swig(); sha1_hash hash = p.getInfo_hashes().get_best(); if (hash == null) return null; String strHash = hash.to_hex(); torrent_handle th = null; boolean add = false; try { syncMagnet.lock(); try { th = swig().find_torrent(hash); if (th != null && th.is_valid()) { torrent_info ti = th.torrent_file_ptr(); if (ti != null && ti.is_valid()) { byte[] b = createTorrent(p, ti); if (b != null) loadedMagnets.put(hash.to_hex(), b); } notifyListeners((listener) -> listener.onMagnetLoaded(strHash, ti != null ? new TorrentInfo(ti).bencode() : null)); } else { add = true; } if (add) { magnets.add(strHash); if (TextUtils.isEmpty(p.getName())) p.setName(strHash); torrent_flags_t flags = p.getFlags(); flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); flags = flags.or_(TorrentFlags.UPLOAD_MODE); flags = flags.or_(TorrentFlags.STOP_WHEN_READY); p.setFlags(flags); addDefaultTrackers(p); error_code ec = new error_code(); th = swig().add_torrent(p, ec); if (!th.is_valid() || ec.failed()) magnets.remove(strHash); th.resume(); } } finally { syncMagnet.unlock(); } } catch (Exception e) { if (add && th != null && th.is_valid()) swig().remove_torrent(th); throw new Exception(e); } return new org.libtorrent4j.AddTorrentParams(p); } private org.libtorrent4j.AddTorrentParams parseMagnetUri(String uri) { error_code ec = new error_code(); add_torrent_params p = libtorrent.parse_magnet_uri(uri, ec); if (ec.value() != 0) throw new IllegalArgumentException(ec.message()); return new org.libtorrent4j.AddTorrentParams(p); } @Override public void cancelFetchMagnet(@NonNull String infoHash) { if (operationNotAllowed() || !magnets.contains(infoHash)) return; magnets.remove(infoHash); TorrentHandle th = find(Sha1Hash.parseHex(infoHash)); if (th != null && th.isValid()) remove(th, SessionHandle.DELETE_FILES); } private void mergeTorrent(String id, AddTorrentParams params, byte[] bencode) { if (operationNotAllowed()) { return; } var task = torrentTasks.get(id); if (task == null) { return; } task.setSequentialDownload(params.sequentialDownload); if (params.filePriorities != null) { task.prioritizeFiles(params.filePriorities); } task.setFirstLastPiecePriority(params.firstLastPiecePriority); try { var ti = (bencode == null ? new TorrentInfo(new File(Uri.parse(params.source).getPath())) : new TorrentInfo(bencode)); var th = find(Sha1Hash.parseHex(id)); if (th != null) { for (var tracker : ti.trackers()) { th.addTracker(tracker); } for (var webSeed : ti.webSeeds()) { th.addUrlSeed(webSeed.url()); } } task.saveResumeData(true); } catch (Exception e) { /* Ignore */ } if (params.addPaused) { task.pauseManually(); } else { task.resumeManually(); } } @Override public long getDownloadSpeed() { return stats().downloadRate(); } @Override public long getUploadSpeed() { return stats().uploadRate(); } @Override public long getTotalDownload() { return stats().totalDownload(); } @Override public long getTotalUpload() { return stats().totalUpload(); } @Override public int getDownloadSpeedLimit() { SettingsPack settingsPack = settings(); return (settingsPack == null ? -1 : settingsPack.downloadRateLimit()); } @Override public int getUploadSpeedLimit() { SettingsPack settingsPack = settings(); return (settingsPack == null ? -1 : settingsPack.uploadRateLimit()); } @Override public int getListenPort() { return (swig() == null ? -1 : swig().listen_port()); } @Override public long getDhtNodes() { return stats().dhtNodes(); } @Override public void enableIpFilter(@NonNull Uri path) { if (operationNotAllowed()) return; if (parseIpFilterThread != null && !parseIpFilterThread.isInterrupted()) parseIpFilterThread.interrupt(); parseIpFilterThread = new Thread(() -> { if (operationNotAllowed() || Thread.interrupted()) return; IPFilterImpl filter = new IPFilterImpl(); int ruleCount = new IPFilterParser().parseFile(path, fs, filter); if (Thread.interrupted()) return; if (ruleCount != 0 && swig() != null && !operationNotAllowed()) swig().set_ip_filter(filter.getFilter()); notifyListeners((listener) -> listener.onIpFilterParsed(ruleCount)); }); parseIpFilterThread.start(); } @Override public void disableIpFilter() { if (operationNotAllowed()) return; if (parseIpFilterThread != null && !parseIpFilterThread.isInterrupted()) parseIpFilterThread.interrupt(); swig().set_ip_filter(new ip_filter()); } @Override public void pauseAll() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.pause(); } } @Override public void resumeAll() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.resume(); } } @Override public void pauseAllManually() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.pauseManually(); } } @Override public void resumeAllManually() { if (operationNotAllowed()) return; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.resumeManually(); } } @Override public void setMaxConnectionsPerTorrent(int connections) { if (operationNotAllowed()) return; settings.connectionsLimitPerTorrent = connections; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.setMaxConnections(connections); } } @Override public void setMaxUploadsPerTorrent(int uploads) { if (operationNotAllowed()) return; settings.uploadsLimitPerTorrent = uploads; for (TorrentDownload task : torrentTasks.values()) { if (task == null) continue; task.setMaxUploads(uploads); } } @Override public void setAutoManaged(boolean autoManaged) { if (operationNotAllowed()) return; settings.autoManaged = autoManaged; for (TorrentDownload task : torrentTasks.values()) task.setAutoManaged(autoManaged); } @Override public boolean isDHTEnabled() { SettingsPack sp = settings(); return sp != null && sp.isEnableDht(); } @Override public boolean isPeXEnabled() { /* PeX enabled by default in session_handle.session_flags_t::add_default_plugins */ return true; } @Override public void start() { if (isRunning()) return; SessionParams params = loadSettings(); SettingsPack settingsPack = params.getSettings(); settings_pack sp = settingsPack.swig(); sp.set_str(settings_pack.string_types.dht_bootstrap_nodes.swigValue(), dhtBootstrapNodes()); sp.set_bool(settings_pack.bool_types.enable_ip_notifier.swigValue(), false); sp.set_int(settings_pack.int_types.alert_queue_size.swigValue(), 5000); sp.set_bool(settings_pack.bool_types.announce_to_all_trackers.swigValue(), true); sp.set_bool(settings_pack.bool_types.announce_to_all_tiers.swigValue(), true); String versionName = system.getAppVersionName(); if (versionName != null) { int[] version = Utils.getVersionComponents(versionName); String fingerprint = libtorrent.generate_fingerprint(PEER_FINGERPRINT, version[0], version[1], version[2], 0); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), fingerprint); String userAgent = String.format(USER_AGENT, Utils.getAppVersionNumber(versionName)); sp.set_str(settings_pack.string_types.user_agent.swigValue(), userAgent); Log.i(TAG, "Peer fingerprint: " + sp.get_str(settings_pack.string_types.peer_fingerprint.swigValue())); Log.i(TAG, "User agent: " + sp.get_str(settings_pack.string_types.user_agent.swigValue())); } if (settings.useRandomPort) { setRandomPort(settings); } settingsToSettingsPack(settings, params.getSettings()); super.start(params); } @Override public void requestStop() { if (stopRequested.getAndSet(true)) return; saveAllResumeData(); stopTasks(); } private void stopTasks() { disposables.add(Observable.fromIterable(torrentTasks.values()) .filter(Objects::nonNull) .map(TorrentDownload::requestStop) .toList() .flatMapCompletable(Completable::merge) /* Wait for all torrents */ .subscribe( this::handleStoppingTasks, (err) -> { Log.e(TAG, "Error stopping torrents: " + Log.getStackTraceString(err)); handleStoppingTasks(); } )); } private void handleStoppingTasks() { /* Handles must be destructed before the session is destructed */ torrentTasks.clear(); checkStop(); } private void checkStop() { if (stopRequested.get() && torrentTasks.isEmpty() && addTorrentsList.isEmpty()) super.stop(); } private void saveAllResumeData() { for (TorrentDownload task : torrentTasks.values()) { if (task == null || task.hasMissingFiles()) continue; task.saveResumeData(false); } } @Override public boolean isRunning() { return super.isRunning() && started; } @Override public long dhtNodes() { return super.dhtNodes(); } @Override public int[] getPieceSizeList() { return pieceSize; } @Override protected void onBeforeStart() { addListener(torrentTaskListener); addListener(innerListener); } @Override protected void onAfterStart() { /* * Overwrite default behaviour of super.start() * and enable logging in onAfterStart() */ if (settings.logging) { SettingsPack sp = settings(); if (sp == null) return; sp.setInteger(settings_pack.int_types.alert_mask.swigValue(), getAlertMask(settings).to_int()); applySettingsPack(sp); enableSessionLogger(true); } saveSettings(); started = true; disposables.add(Completable.fromRunnable(() -> notifyListeners(TorrentEngineListener::onSessionStarted)) .subscribeOn(Schedulers.io()) .subscribe()); } private void enableSessionLogger(boolean enable) { if (enable) { sessionLogger.resume(); } else { sessionLogger.stopRecording(); sessionLogger.pause(); sessionLogger.clean(); } } @Override protected void onBeforeStop() { disposables.clear(); started = false; enableSessionLogger(false); parseIpFilterThread = null; magnets.clear(); loadedMagnets.clear(); removeListener(torrentTaskListener); removeListener(innerListener); } @Override protected void onAfterStop() { notifyListeners(TorrentEngineListener::onSessionStopped); stopRequested.set(false); } @Override protected void onApplySettings(SettingsPack sp) { saveSettings(); } private final TorrentEngineListener torrentTaskListener = new TorrentEngineListener() { @Override public void onTorrentRemoved(@NonNull String id) { torrentTasks.remove(id); } }; private final class InnerListener implements AlertListener { @Override public int[] types() { return INNER_LISTENER_TYPES; } @Override public void alert(Alert<?> alert) { switch (alert.type()) { case ADD_TORRENT: TorrentAlert<?> torrentAlert = (TorrentAlert<?>)alert; TorrentHandle th = find(torrentAlert.handle().infoHash()); if (th == null) break; String hash = th.infoHash().toHex(); if (magnets.contains(hash)) break; torrentTasks.put(hash, newTask(th, hash)); if (addTorrentsList.contains(hash)) notifyListeners((listener) -> listener.onTorrentAdded(hash)); else notifyListeners((listener) -> listener.onTorrentLoaded(hash)); addTorrentsList.remove(hash); checkStop(); runNextLoadTorrentTask(); break; case METADATA_RECEIVED: handleMetadata(((MetadataReceivedAlert)alert)); break; case SESSION_STATS: handleStats(); break; default: checkError(alert); if (settings.logging) sessionLogger.send(alert); break; } } } private void checkError(Alert<?> alert) { notifyListeners((listener) -> { String msg = null; switch (alert.type()) { case SESSION_ERROR: { SessionErrorAlert sessionErrorAlert = (SessionErrorAlert)alert; ErrorCode error = sessionErrorAlert.error(); msg = SessionErrors.getErrorMsg(error); if (!SessionErrors.isNonCritical(error)) listener.onSessionError(msg); break; } case LISTEN_FAILED: { ListenFailedAlert listenFailedAlert = (ListenFailedAlert)alert; msg = SessionErrors.getErrorMsg(listenFailedAlert.error()); ErrorCode error = listenFailedAlert.error(); if (!SessionErrors.isNonCritical(error)) listener.onSessionError(msg); break; } case PORTMAP_ERROR: { PortmapErrorAlert portmapErrorAlert = (PortmapErrorAlert)alert; ErrorCode error = portmapErrorAlert.error(); msg = SessionErrors.getErrorMsg(error); if (!SessionErrors.isNonCritical(error)) listener.onNatError(msg); break; } } if (msg != null) Log.e(TAG, "Session error: " + msg); }); } private void handleMetadata(MetadataReceivedAlert metadataAlert) { TorrentHandle th = metadataAlert.handle(); String hash = th.infoHash().toHex(); if (!magnets.contains(hash)) return; TorrentInfo ti = th.torrentFile(); if (ti != null) loadedMagnets.put(hash, ti.bencode()); remove(th, SessionHandle.DELETE_FILES); notifyListeners((listener) -> listener.onMagnetLoaded(hash, loadedMagnets.get(hash))); } private void handleStats() { if (operationNotAllowed()) return; notifyListeners((listener) -> listener.onSessionStats( new SessionStats(dhtNodes(), getTotalDownload(), getTotalUpload(), getDownloadSpeed(), getUploadSpeed(), getListenPort())) ); } private static String dhtBootstrapNodes() { return "dht.libtorrent.org:25401" + "," + "router.bittorrent.com:6881" + "," + "dht.transmissionbt.com:6881" + "," + /* For IPv6 DHT */ "outer.silotis.us:6881"; } private SessionParams loadSettings() { try { String sessionPath = repo.getSessionFile(); if (sessionPath == null) return new SessionParams(defaultSettingsPack()); File sessionFile = new File(sessionPath); if (sessionFile.exists()) { byte[] data = FileUtils.readFileToByteArray(sessionFile); byte_vector buffer = Vectors.bytes2byte_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { session_params params = session_params.read_session_params(n); /* Prevents GC */ buffer.clear(); return new SessionParams(params); } else { throw new IllegalArgumentException("Can't decode data: " + ec.message()); } } else { return new SessionParams(defaultSettingsPack()); } } catch (Exception e) { Log.e(TAG, "Error loading session state: "); Log.e(TAG, Log.getStackTraceString(e)); return new SessionParams(defaultSettingsPack()); } } private void saveSettings() { try { session_params params = swig().session_state(); entry e = session_params.write_session_params(params); byte[] b = Vectors.byte_vector2bytes(e.bencode()); repo.saveSession(b); } catch (Exception e) { Log.e(TAG, "Error saving session state: "); Log.e(TAG, Log.getStackTraceString(e)); } } private SettingsPack defaultSettingsPack() { SettingsPack sp = new SettingsPack(); settingsToSettingsPack(settings, sp); return sp; } private void settingsToSettingsPack(SessionSettings settings, SettingsPack sp) { sp.activeDownloads(settings.activeDownloads); sp.activeSeeds(settings.activeSeeds); sp.activeLimit(settings.activeLimit); sp.maxPeerlistSize(settings.maxPeerListSize); sp.tickInterval(settings.tickInterval); sp.inactivityTimeout(settings.inactivityTimeout); sp.connectionsLimit(settings.connectionsLimit); sp.listenInterfaces(getIface(settings.inetAddress, settings.portRangeFirst)); sp.setInteger(settings_pack.int_types.max_retry_port_bind.swigValue(), settings.portRangeSecond - settings.portRangeFirst); sp.setEnableDht(settings.dhtEnabled); sp.setBoolean(settings_pack.bool_types.enable_lsd.swigValue(), settings.lsdEnabled); sp.setBoolean(settings_pack.bool_types.enable_incoming_utp.swigValue(), settings.utpEnabled); sp.setBoolean(settings_pack.bool_types.enable_outgoing_utp.swigValue(), settings.utpEnabled); sp.setBoolean(settings_pack.bool_types.enable_upnp.swigValue(), settings.upnpEnabled); sp.setBoolean(settings_pack.bool_types.enable_natpmp.swigValue(), settings.natPmpEnabled); var encryptMode = convertEncryptMode(settings.encryptMode); var encLevel = getAllowedEncryptLevel(settings.encryptMode); sp.setInteger(settings_pack.int_types.in_enc_policy.swigValue(), encryptMode); sp.setInteger(settings_pack.int_types.out_enc_policy.swigValue(), encryptMode); sp.setInteger(settings_pack.int_types.allowed_enc_level.swigValue(), encLevel); sp.uploadRateLimit(settings.uploadRateLimit); sp.downloadRateLimit(settings.downloadRateLimit); sp.anonymousMode(settings.anonymousMode); sp.seedingOutgoingConnections(settings.seedingOutgoingConnections); sp.setInteger(settings_pack.int_types.alert_mask.swigValue(), getAlertMask(settings).to_int()); sp.setBoolean(settings_pack.bool_types.validate_https_trackers.swigValue(), settings.validateHttpsTrackers); applyProxy(settings, sp); } private void applyProxy(SessionSettings settings, SettingsPack sp) { int proxyType = convertProxyType(settings.proxyType, settings.proxyRequiresAuth); sp.setInteger(settings_pack.int_types.proxy_type.swigValue(), proxyType); if (settings.proxyType != SessionSettings.ProxyType.NONE) { sp.setInteger(settings_pack.int_types.proxy_port.swigValue(), settings.proxyPort); sp.setString(settings_pack.string_types.proxy_hostname.swigValue(), settings.proxyAddress); if (settings.proxyRequiresAuth) { sp.setString(settings_pack.string_types.proxy_username.swigValue(), settings.proxyLogin); sp.setString(settings_pack.string_types.proxy_password.swigValue(), settings.proxyPassword); } sp.setBoolean(settings_pack.bool_types.proxy_peer_connections.swigValue(), settings.proxyPeersToo); sp.setBoolean(settings_pack.bool_types.proxy_tracker_connections.swigValue(), true); sp.setBoolean(settings_pack.bool_types.proxy_hostnames.swigValue(), true); } } private alert_category_t getAlertMask(SessionSettings settings) { alert_category_t mask = alert.all_categories; if (!settings.logging) { alert_category_t log_mask = alert.session_log_notification; log_mask = log_mask.or_(alert.torrent_log_notification); log_mask = log_mask.or_(alert.peer_log_notification); log_mask = log_mask.or_(alert.dht_log_notification); log_mask = log_mask.or_(alert.port_mapping_log_notification); log_mask = log_mask.or_(alert.picker_log_notification); mask = mask.and_(log_mask.inv()); } return mask; } private int convertEncryptMode(SessionSettings.EncryptMode mode) { switch (mode) { case ENABLED: return settings_pack.enc_policy.pe_enabled.swigValue(); case FORCED: return settings_pack.enc_policy.pe_forced.swigValue(); default: return settings_pack.enc_policy.pe_disabled.swigValue(); } } private int getAllowedEncryptLevel(SessionSettings.EncryptMode mode) { if (mode == SessionSettings.EncryptMode.FORCED) { return settings_pack.enc_level.pe_rc4.swigValue(); } else { return settings_pack.enc_level.pe_both.swigValue(); } } private int convertProxyType(SessionSettings.ProxyType mode, boolean authRequired) { switch (mode) { case SOCKS4: return settings_pack.proxy_type_t.socks4.swigValue(); case SOCKS5: return (authRequired ? settings_pack.proxy_type_t.socks5_pw.swigValue() : settings_pack.proxy_type_t.socks5.swigValue()); case HTTP: return (authRequired ? settings_pack.proxy_type_t.http_pw.swigValue() : settings_pack.proxy_type_t.http.swigValue()); default: return settings_pack.proxy_type_t.none.swigValue(); } } private String getIface(String inetAddress, int portRangeFirst) { String iface; if (inetAddress.equals(SessionSettings.DEFAULT_INETADDRESS)) { iface = "0.0.0.0:%1$d,[::]:%1$d"; } else { /* IPv6 test */ if (inetAddress.contains(":")) iface = "[" + inetAddress + "]"; else iface = inetAddress; iface = iface + ":%1$d"; } return String.format(iface, portRangeFirst); } private void applySettingsPack(SettingsPack sp) { applySettings(sp); saveSettings(); } private void applySettings(SessionSettings settings, boolean keepPort) { applyMaxStoredLogs(settings); applySessionLoggerFilters(settings); enableSessionLogger(settings.logging); if (!keepPort && settings.useRandomPort) { setRandomPort(settings); } SettingsPack sp = settings(); if (sp != null) { settingsToSettingsPack(settings, sp); applySettingsPack(sp); } } private void setRandomPort(SessionSettings settings) { Pair<Integer, Integer> range = SessionSettings.getRandomRangePort(); settings.portRangeFirst = range.first; settings.portRangeSecond = range.second; } private void applyMaxStoredLogs(SessionSettings settings) { if (settings.maxLogSize == sessionLogger.getMaxStoredLogs()) return; sessionLogger.setMaxStoredLogs(settings.maxLogSize); } private void applySessionLoggerFilters(SessionSettings settings) { disposables.add(Completable.fromRunnable(() -> sessionLogger.applyFilterParams(new SessionLogger.SessionFilterParams( settings.logSessionFilter, settings.logDhtFilter, settings.logPeerFilter, settings.logPortmapFilter, settings.logTorrentFilter ))) .subscribeOn(Schedulers.computation()) .subscribe()); } private byte[] createTorrent(add_torrent_params params, torrent_info ti) { if (operationNotAllowed()) return null; create_torrent ct = new create_torrent(ti); string_vector v = params.getUrl_seeds(); for (int i = 0; i < v.size(); i++) ct.add_url_seed(v.get(i)); string_vector trackers = params.getTrackers(); int_vector tiers = params.getTracker_tiers(); for (int i = 0; i < trackers.size(); i++) ct.add_tracker(trackers.get(i), tiers.get(i)); entry e = ct.generate(); return Vectors.byte_vector2bytes(e.bencode()); } private TorrentDownload newTask(TorrentHandle th, String id) { TorrentDownload task = new TorrentDownloadImpl(this, repo, fs, listeners, id, th, settings.autoManaged); task.setMaxConnections(settings.connectionsLimitPerTorrent); task.setMaxUploads(settings.uploadsLimitPerTorrent); return task; } private interface CallListener { void apply(TorrentEngineListener listener); } private void notifyListeners(@NonNull CallListener l) { for (TorrentEngineListener listener : listeners) { if (listener != null) l.apply(listener); } } private void runNextLoadTorrentTask() { if (operationNotAllowed()) { restoreTorrentsQueue.clear(); return; } LoadTorrentTask task; try { task = restoreTorrentsQueue.poll(); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); return; } if (task != null) loadTorrentsExec.execute(task); } private boolean isTorrentAlreadyRunning(String torrentId) { return torrentTasks.containsKey(torrentId) || addTorrentsList.contains(torrentId); } private final class LoadTorrentTask implements Runnable { private String torrentId; private File saveDir = null; private String magnetUri = null; private boolean isMagnet = false; private boolean magnetPaused = false; private boolean magnetSequentialDownload = false; LoadTorrentTask(String torrentId) { this.torrentId = torrentId; } public void putMagnet( String magnetUri, File saveDir, boolean magnetPaused, boolean magnetSequentialDownload ) { this.magnetUri = magnetUri; this.saveDir = saveDir; this.magnetPaused = magnetPaused; this.magnetSequentialDownload = magnetSequentialDownload; isMagnet = true; } @Override public void run() { try { if (isTorrentAlreadyRunning(torrentId)) return; if (isMagnet) download(magnetUri, saveDir, magnetPaused, magnetSequentialDownload); else restoreDownload(torrentId); } catch (Exception e) { Log.e(TAG, "Unable to restore torrent from previous session: " + torrentId, e); Torrent torrent = repo.getTorrentById(torrentId); if (torrent != null) { torrent.error = e.toString(); repo.updateTorrent(torrent); } notifyListeners((listener) -> listener.onRestoreSessionError(torrentId)); } } } private void download(byte[] bencode, File saveDir, Priority[] priorities, boolean sequentialDownload, boolean paused, List<TcpEndpoint> peers) { download((bencode == null ? null : new TorrentInfo(bencode)), saveDir, priorities, sequentialDownload, paused, peers); } private void download(TorrentInfo ti, File saveDir, Priority[] priorities, boolean sequentialDownload, boolean paused, List<TcpEndpoint> peers) { if (operationNotAllowed()) return; if (ti == null) throw new IllegalArgumentException("Torrent info is null"); if (!ti.isValid()) throw new IllegalArgumentException("Torrent info not valid"); torrent_handle th = swig().find_torrent(ti.swig().info_hash()); if (th != null && th.is_valid()) { /* Found a download with the same hash */ return; } add_torrent_params p = new add_torrent_params(); p.set_ti(ti.swig()); if (saveDir != null) p.setSave_path(saveDir.getAbsolutePath()); if (priorities != null) { if (ti.files().numFiles() != priorities.length) throw new IllegalArgumentException("Priorities count should be equals to the number of files"); byte_vector v = new byte_vector(); for (Priority priority : priorities) { if (priority == null) v.add(org.libtorrent4j.Priority.IGNORE.swig()); else v.add(PriorityConverter.convert(priority).swig()); } p.set_file_priorities(v); } if (peers != null && !peers.isEmpty()) { tcp_endpoint_vector v = new tcp_endpoint_vector(); for (TcpEndpoint endp : peers) v.add(endp.swig()); p.setPeers(v); } torrent_flags_t flags = p.getFlags(); /* Force saving resume data */ flags = flags.or_(TorrentFlags.NEED_SAVE_RESUME); if (settings.autoManaged) flags = flags.or_(TorrentFlags.AUTO_MANAGED); else flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); if (sequentialDownload) flags = flags.or_(TorrentFlags.SEQUENTIAL_DOWNLOAD); else flags = flags.and_(TorrentFlags.SEQUENTIAL_DOWNLOAD.inv()); if (paused) flags = flags.or_(TorrentFlags.PAUSED); else flags = flags.and_(TorrentFlags.PAUSED.inv()); p.setFlags(flags); addDefaultTrackers(p); swig().async_add_torrent(p); } @Override public void download( @NonNull String magnetUri, File saveDir, boolean paused, boolean sequentialDownload ) { if (operationNotAllowed()) return; error_code ec = new error_code(); add_torrent_params p = libtorrent.parse_magnet_uri(magnetUri, ec); if (ec.value() != 0) throw new IllegalArgumentException(ec.message()); sha1_hash info_hash = p.getInfo_hashes().get_best(); if (info_hash == null) return; torrent_handle th = swig().find_torrent(info_hash); if (th != null && th.is_valid()) { /* Found a download with the same hash */ return; } if (saveDir != null) p.setSave_path(saveDir.getAbsolutePath()); if (TextUtils.isEmpty(p.getName())) p.setName(info_hash.to_hex()); torrent_flags_t flags = p.getFlags(); flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); if (paused) flags = flags.or_(TorrentFlags.PAUSED); else flags = flags.and_(TorrentFlags.PAUSED.inv()); if (sequentialDownload) flags = flags.or_(TorrentFlags.SEQUENTIAL_DOWNLOAD); else flags = flags.and_(TorrentFlags.SEQUENTIAL_DOWNLOAD.inv()); p.setFlags(flags); addDefaultTrackers(p); swig().async_add_torrent(p); } private void addDefaultTrackers(add_torrent_params p) { String[] defaultTrackers = getSettings().defaultTrackersList; if (defaultTrackers != null && defaultTrackers.length > 0) { string_vector v = p.getTrackers(); if (v == null) { v = new string_vector(); } v.addAll(Arrays.asList(defaultTrackers)); p.setTrackers(v); } } @Override public void setDefaultTrackersList(@NonNull String[] trackersList) { settings.defaultTrackersList = trackersList; } private void restoreDownload(String id) throws IOException { if (operationNotAllowed()) return; FastResume fastResume = repo.getFastResumeById(id); if (fastResume == null) throw new IOException("Fast resume data not found"); error_code ec = new error_code(); byte_vector buffer = Vectors.bytes2byte_vector(fastResume.data); bdecode_node n = new bdecode_node(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret != 0) throw new IllegalArgumentException("Can't decode data: " + ec.message()); ec.clear(); add_torrent_params p = libtorrent.read_resume_data(n, ec); if (ec.value() != 0) throw new IllegalArgumentException("Unable to read the resume data: " + ec.message()); torrent_flags_t flags = p.getFlags(); /* Disable force saving resume data, because they already have */ flags = flags.and_(TorrentFlags.NEED_SAVE_RESUME.inv()); if (settings.autoManaged) flags = flags.or_(TorrentFlags.AUTO_MANAGED); else flags = flags.and_(TorrentFlags.AUTO_MANAGED.inv()); p.setFlags(flags); /* After reading the metadata some time may have passed */ if (operationNotAllowed()) return; swig().async_add_torrent(p); } }
proninyaroslav/libretorrent
app/src/main/java/org/proninyaroslav/libretorrent/core/model/session/TorrentSessionImpl.java
Java
gpl-3.0
53,404
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Fri Jul 3 13:38:36 2015 @author: madengr """ from gnuradio import gr import osmosdr from gnuradio import filter as grfilter # Don't redefine Python's filter() from gnuradio import blocks from gnuradio import fft from gnuradio.fft import window from gnuradio import analog from gnuradio import audio import os import time import numpy as np from gnuradio.filter import pfb class BaseTuner(gr.hier_block2): """Some base methods that are the same between the known tuner types. See TunerDemodNBFM and TunerDemodAM for better documentation. """ def set_center_freq(self, center_freq, rf_center_freq): """Sets baseband center frequency and file name Sets baseband center frequency of frequency translating FIR filter Also sets file name of wave file sink If tuner is tuned to zero Hz then set to file name to /dev/null Otherwise set file name to tuned RF frequency in MHz Args: center_freq (float): Baseband center frequency in Hz rf_center_freq (float): RF center in Hz (for file name) """ # Since the frequency (hence file name) changed, then close it self.blocks_wavfile_sink.close() # If we never wrote any data to the wavfile sink, delete the file self._delete_wavfile_if_empty() # Set the frequency self.freq_xlating_fir_filter_ccc.set_center_freq(center_freq) self.center_freq = center_freq # Set the file name if self.center_freq == 0 or not self.record: # If tuner at zero Hz, or record false, then file name to /dev/null file_name = "/dev/null" else: # Otherwise use frequency and time stamp for file name tstamp = "_" + str(int(time.time())) file_freq = (rf_center_freq + self.center_freq)/1E6 file_freq = np.round(file_freq, 3) file_name = 'wav/' + '{:.3f}'.format(file_freq) + tstamp + ".wav" # Make sure the 'wav' directory exists try: os.mkdir('wav') except OSError: # will need to add something here for Win support pass # directory already exists self.file_name = file_name self.blocks_wavfile_sink.open(self.file_name) def _delete_wavfile_if_empty(self): """Delete the current wavfile if it's empty.""" if (not self.record or not self.file_name or self.file_name == '/dev/null'): return # If we never wrote any data to the wavfile sink, delete # the (empty) wavfile if os.stat(self.file_name).st_size in (44, 0): # ugly hack os.unlink(self.file_name) # delete the file def set_squelch(self, squelch_db): """Sets the threshold for both squelches Args: squelch_db (float): Squelch in dB """ self.analog_pwr_squelch_cc.set_threshold(squelch_db) def __del__(self): """Called when the object is destroyed.""" # Make a best effort attempt to clean up our wavfile if it's empty try: self._delete_wavfile_if_empty() except Exception: pass # oh well, we're dying anyway class TunerDemodNBFM(BaseTuner): """Tuner, demodulator, and recorder chain for narrow band FM demodulation Kept as it's own class so multiple can be instantiated in parallel Accepts complex baseband samples at 1 Msps minimum Frequency translating FIR filter tunes from -samp_rate/2 to +samp_rate/2 The following sample rates assume 1 Msps input First two stages of decimation are 5 each for a total of 25 Thus first two stages brings 1 Msps down to 40 ksps The third stage decimates by int(samp_rate/1E6) Thus output rate will vary from 40 ksps to 79.99 ksps The channel is filtered to 12.5 KHz bandwidth followed by squelch The squelch is non-blocking since samples will be added with other demods The quadrature demod is followed by a forth stage of decimation by 5 This brings the sample rate down to 8 ksps to 15.98 ksps The audio is low-pass filtered to 3.5 kHz bandwidth The polyphase resampler resamples by samp_rate/(decims[1] * decims[0]**3) This results in a constant 8 ksps, irrespective of RF sample rate This 8 ksps audio stream may be added to other demos streams The audio is run through an additional blocking squelch at -200 dB This stops the sample flow so squelced audio is not recorded to file The wav file sink stores 8-bit samples (grainy quality but compact) Default demodulator center freqwuency is 0 Hz This is desired since hardware DC removal reduces sensitivity at 0 Hz NBFM demod of LO leakage will just be 0 amplitude Args: samp_rate (float): Input baseband sample rate in sps (1E6 minimum) audio_rate (float): Output audio sample rate in sps (8 kHz minimum) record (bool): Record audio to file if True Attributes: center_freq (float): Baseband center frequency in Hz record (bool): Record audio to file if True """ # pylint: disable=too-many-instance-attributes def __init__(self, samp_rate=4E6, audio_rate=8000, record=True): gr.hier_block2.__init__(self, "TunerDemodNBFM", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Default values self.center_freq = 0 squelch_db = -60 self.quad_demod_gain = 0.050 self.file_name = "/dev/null" self.record = record # Decimation values for four stages of decimation decims = (5, int(samp_rate/1E6)) # Low pass filter taps for decimation by 5 low_pass_filter_taps_0 = \ grfilter.firdes_low_pass(1, 1, 0.090, 0.010, grfilter.firdes.WIN_HAMMING) # Frequency translating FIR filter decimating by 5 self.freq_xlating_fir_filter_ccc = \ grfilter.freq_xlating_fir_filter_ccc(decims[0], low_pass_filter_taps_0, self.center_freq, samp_rate) # FIR filter decimating by 5 fir_filter_ccc_0 = grfilter.fir_filter_ccc(decims[0], low_pass_filter_taps_0) # Low pass filter taps for decimation from samp_rate/25 to 40-79.9 ksps # In other words, decimation by int(samp_rate/1E6) # 12.5 kHz cutoff for NBFM channel bandwidth low_pass_filter_taps_1 = grfilter.firdes_low_pass( 1, samp_rate/decims[0]**2, 12.5E3, 1E3, grfilter.firdes.WIN_HAMMING) # FIR filter decimation by int(samp_rate/1E6) fir_filter_ccc_1 = grfilter.fir_filter_ccc(decims[1], low_pass_filter_taps_1) # Non blocking power squelch self.analog_pwr_squelch_cc = analog.pwr_squelch_cc(squelch_db, 1e-1, 0, False) # Quadrature demod with gain set for decent audio # The gain will be later multiplied by the 0 dB normalized volume self.analog_quadrature_demod_cf = \ analog.quadrature_demod_cf(self.quad_demod_gain) # 3.5 kHz cutoff for audio bandwidth low_pass_filter_taps_2 = grfilter.firdes_low_pass(1,\ samp_rate/(decims[1] * decims[0]**2),\ 3.5E3, 500, grfilter.firdes.WIN_HAMMING) # FIR filter decimating by 5 from 40-79.9 ksps to 8-15.98 ksps fir_filter_fff_0 = grfilter.fir_filter_fff(decims[0], low_pass_filter_taps_2) # Polyphase resampler allows arbitary RF sample rates # Takes 8-15.98 ksps to a constant 8 ksps for audio pfb_resamp = audio_rate/float(samp_rate/(decims[1] * decims[0]**3)) pfb_arb_resampler_fff = pfb.arb_resampler_fff(pfb_resamp, taps=None, flt_size=32) # Connect the blocks for the demod self.connect(self, self.freq_xlating_fir_filter_ccc) self.connect(self.freq_xlating_fir_filter_ccc, fir_filter_ccc_0) self.connect(fir_filter_ccc_0, fir_filter_ccc_1) self.connect(fir_filter_ccc_1, self.analog_pwr_squelch_cc) self.connect(self.analog_pwr_squelch_cc, self.analog_quadrature_demod_cf) self.connect(self.analog_quadrature_demod_cf, fir_filter_fff_0) self.connect(fir_filter_fff_0, pfb_arb_resampler_fff) self.connect(pfb_arb_resampler_fff, self) # Need to set this to a very low value of -200 since it is after demod # Only want it to gate when the previuos squelch has gone to zero analog_pwr_squelch_ff = analog.pwr_squelch_ff(-200, 1e-1, 0, True) # File sink with single channel and 8 bits/sample self.blocks_wavfile_sink = blocks.wavfile_sink(self.file_name, 1, audio_rate, 8) # Connect the blocks for recording self.connect(pfb_arb_resampler_fff, analog_pwr_squelch_ff) self.connect(analog_pwr_squelch_ff, self.blocks_wavfile_sink) def set_volume(self, volume_db): """Sets the volume Args: volume_db (float): Volume in dB """ gain = self.quad_demod_gain * 10**(volume_db/20.0) self.analog_quadrature_demod_cf.set_gain(gain) class TunerDemodAM(BaseTuner): """Tuner, demodulator, and recorder chain for AM demodulation Kept as it's own class so multiple can be instantiated in parallel Accepts complex baseband samples at 1 Msps minimum Frequency translating FIR filter tunes from -samp_rate/2 to +samp_rate/2 The following sample rates assume 1 Msps input First two stages of decimation are 5 each for a total of 25 Thus first two stages brings 1 Msps down to 40 ksps The third stage decimates by int(samp_rate/1E6) Thus output rate will vary from 40 ksps to 79.99 ksps The channel is filtered to 12.5 KHz bandwidth followed by squelch The squelch is non-blocking since samples will be added with other demods The AGC sets level (volume) prior to AM demod The AM demod is followed by a forth stage of decimation by 5 This brings the sample rate down to 8 ksps to 15.98 ksps The audio is low-pass filtered to 3.5 kHz bandwidth The polyphase resampler resamples by samp_rate/(decims[1] * decims[0]**3) This results in a constant 8 ksps, irrespective of RF sample rate This 8 ksps audio stream may be added to other demos streams The audio is run through an additional blocking squelch at -200 dB This stops the sample flow so squelced audio is not recorded to file The wav file sink stores 8-bit samples (grainy quality but compact) Default demodulator center freqwuency is 0 Hz This is desired since hardware DC removal reduces sensitivity at 0 Hz AM demod of LO leakage will just be 0 amplitude Args: samp_rate (float): Input baseband sample rate in sps (1E6 minimum) audio_rate (float): Output audio sample rate in sps (8 kHz minimum) record (bool): Record audio to file if True Attributes: center_freq (float): Baseband center frequency in Hz record (bool): Record audio to file if True """ # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-locals def __init__(self, samp_rate=4E6, audio_rate=8000, record=True): gr.hier_block2.__init__(self, "TunerDemodAM", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_float)) # Default values self.center_freq = 0 squelch_db = -60 self.agc_ref = 0.1 self.file_name = "/dev/null" self.record = record # Decimation values for four stages of decimation decims = (5, int(samp_rate/1E6)) # Low pass filter taps for decimation by 5 low_pass_filter_taps_0 = \ grfilter.firdes_low_pass(1, 1, 0.090, 0.010, grfilter.firdes.WIN_HAMMING) # Frequency translating FIR filter decimating by 5 self.freq_xlating_fir_filter_ccc = \ grfilter.freq_xlating_fir_filter_ccc(decims[0], low_pass_filter_taps_0, self.center_freq, samp_rate) # FIR filter decimating by 5 fir_filter_ccc_0 = grfilter.fir_filter_ccc(decims[0], low_pass_filter_taps_0) # Low pass filter taps for decimation from samp_rate/25 to 40-79.9 ksps # In other words, decimation by int(samp_rate/1E6) # 12.5 kHz cutoff for NBFM channel bandwidth low_pass_filter_taps_1 = grfilter.firdes_low_pass( 1, samp_rate/decims[0]**2, 12.5E3, 1E3, grfilter.firdes.WIN_HAMMING) # FIR filter decimation by int(samp_rate/1E6) fir_filter_ccc_1 = grfilter.fir_filter_ccc(decims[1], low_pass_filter_taps_1) # Non blocking power squelch # Squelch level needs to be lower than NBFM or else choppy AM demod self.analog_pwr_squelch_cc = analog.pwr_squelch_cc(squelch_db, 1e-1, 0, False) # AGC with reference set for nomninal 0 dB volume # Paramaters tweaked to prevent impulse during squelching self.agc3_cc = analog.agc3_cc(1.0, 1E-4, self.agc_ref, 10, 1) self.agc3_cc.set_max_gain(65536) # AM demod with complex_to_mag() # Can't use analog.am_demod_cf() since it won't work with N>2 demods am_demod_cf = blocks.complex_to_mag(1) # 3.5 kHz cutoff for audio bandwidth low_pass_filter_taps_2 = grfilter.firdes_low_pass(1,\ samp_rate/(decims[1] * decims[0]**2),\ 3.5E3, 500, grfilter.firdes.WIN_HAMMING) # FIR filter decimating by 5 from 40-79.9 ksps to 8-15.98 ksps fir_filter_fff_0 = grfilter.fir_filter_fff(decims[0], low_pass_filter_taps_2) # Polyphase resampler allows arbitary RF sample rates # Takes 8-15.98 ksps to a constant 8 ksps for audio pfb_resamp = audio_rate/float(samp_rate/(decims[1] * decims[0]**3)) pfb_arb_resampler_fff = pfb.arb_resampler_fff(pfb_resamp, taps=None, flt_size=32) # Connect the blocks for the demod self.connect(self, self.freq_xlating_fir_filter_ccc) self.connect(self.freq_xlating_fir_filter_ccc, fir_filter_ccc_0) self.connect(fir_filter_ccc_0, fir_filter_ccc_1) self.connect(fir_filter_ccc_1, self.analog_pwr_squelch_cc) self.connect(self.analog_pwr_squelch_cc, self.agc3_cc) self.connect(self.agc3_cc, am_demod_cf) self.connect(am_demod_cf, fir_filter_fff_0) self.connect(fir_filter_fff_0, pfb_arb_resampler_fff) self.connect(pfb_arb_resampler_fff, self) # Need to set this to a very low value of -200 since it is after demod # Only want it to gate when the previuos squelch has gone to zero analog_pwr_squelch_ff = analog.pwr_squelch_ff(-200, 1e-1, 0, True) # File sink with single channel and 8 bits/sample self.blocks_wavfile_sink = blocks.wavfile_sink(self.file_name, 1, audio_rate, 8) # Connect the blocks for recording self.connect(pfb_arb_resampler_fff, analog_pwr_squelch_ff) self.connect(analog_pwr_squelch_ff, self.blocks_wavfile_sink) def set_volume(self, volume_db): """Sets the volume Args: volume_db (float): Volume in dB """ agc_ref = self.agc_ref * 10**(volume_db/20.0) self.agc3_cc.set_reference(agc_ref) class Receiver(gr.top_block): """Receiver for narrow band frequency modulation Controls hardware and instantiates multiple tuner/demodulators Generates FFT power spectrum for channel estimation Args: ask_samp_rate (float): Asking sample rate of hardware in sps (1E6 min) num_demod (int): Number of parallel demodulators type_demod (int): Type of demodulator (0=NBFM, 1=AM) hw_args (string): Argument string to pass to harwdare freq_correction (int): Frequency correction in ppm record (bool): Record audio to file if True Attributes: center_freq (float): Hardware RF center frequency in Hz samp_rate (float): Hardware sample rate in sps (1E6 min) gain_db (int): Hardware RF gain in dB squelch_db (int): Squelch in dB volume_dB (int): Volume in dB """ # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-locals # pylint: disable=too-many-arguments def __init__(self, ask_samp_rate=4E6, num_demod=4, type_demod=0, hw_args="uhd", freq_correction=0, record=True, play=True): # Call the initialization method from the parent class gr.top_block.__init__(self, "Receiver") # Default values self.center_freq = 144E6 self.gain_db = 10 self.squelch_db = -70 self.volume_db = 0 audio_rate = 8000 # Setup the USRP source, or use the USRP sim self.src = osmosdr.source(args="numchan=" + str(1) + " " + hw_args) self.src.set_sample_rate(ask_samp_rate) self.src.set_gain(self.gain_db) self.src.set_center_freq(self.center_freq) self.src.set_freq_corr(freq_correction) # Get the sample rate and center frequency from the hardware self.samp_rate = self.src.get_sample_rate() self.center_freq = self.src.get_center_freq() # Set the I/Q bandwidth to 80 % of sample rate self.src.set_bandwidth(0.8 * self.samp_rate) # NBFM channel is about 10 KHz wide # Want about 3 FFT bins to span a channel # Use length FFT so 4 Msps / 1024 = 3906.25 Hz/bin # This also means 3906.25 vectors/second # Using below formula keeps FFT size a power of two # Also keeps bin size constant for power of two sampling rates # Use of 256 sets 3906.25 Hz/bin; increase to reduce bin size samp_ratio = self.samp_rate / 1E6 fft_length = 256 * int(pow(2, np.ceil(np.log(samp_ratio)/np.log(2)))) # -----------Flow for FFT-------------- # Convert USRP steam to vector stream_to_vector = blocks.stream_to_vector(gr.sizeof_gr_complex*1, fft_length) # Want about 1000 vector/sec amount = int(round(self.samp_rate/fft_length/1000)) keep_one_in_n = blocks.keep_one_in_n(gr.sizeof_gr_complex* fft_length, amount) # Take FFT fft_vcc = fft.fft_vcc(fft_length, True, window.blackmanharris(fft_length), True, 1) # Compute the power complex_to_mag_squared = blocks.complex_to_mag_squared(fft_length) # Video average and decimate from 1000 vector/sec to 10 vector/sec integrate_ff = blocks.integrate_ff(100, fft_length) # Probe vector self.probe_signal_vf = blocks.probe_signal_vf(fft_length) # Connect the blocks self.connect(self.src, stream_to_vector, keep_one_in_n, fft_vcc, complex_to_mag_squared, integrate_ff, self.probe_signal_vf) # -----------Flow for Demod-------------- # Create N parallel demodulators as a list of objects # Default to NBFM demod self.demodulators = [] for idx in range(num_demod): if type_demod == 1: self.demodulators.append(TunerDemodAM(self.samp_rate, audio_rate, record)) else: self.demodulators.append(TunerDemodNBFM(self.samp_rate, audio_rate, record)) if play: # Create an adder add_ff = blocks.add_ff(1) # Connect the demodulators between the source and adder for idx, demodulator in enumerate(self.demodulators): self.connect(self.src, demodulator, (add_ff, idx)) # Audio sink audio_sink = audio.sink(audio_rate) # Connect the summed outputs to the audio sink self.connect(add_ff, audio_sink) else: # Just connect each demodulator to the receiver source for demodulator in self.demodulators: self.connect(self.src, demodulator) def set_center_freq(self, center_freq): """Sets RF center frequency of hardware Args: center_freq (float): Hardware RF center frequency in Hz """ # Tune the hardware self.src.set_center_freq(center_freq) # Update center frequency with hardware center frequency # Do this to account for slight hardware offsets self.center_freq = self.src.get_center_freq() def set_gain(self, gain_db): """Sets gain of RF hardware Args: gain_db (float): Hardware RF gain in dB """ self.src.set_gain(gain_db) self.gain_db = self.src.get_gain() def set_squelch(self, squelch_db): """Sets squelch of all demodulators and clamps range Args: squelch_db (float): Squelch in dB """ self.squelch_db = max(min(0, squelch_db), -100) for demodulator in self.demodulators: demodulator.set_squelch(self.squelch_db) def set_volume(self, volume_db): """Sets volume of all demodulators and clamps range Args: volume_db (float): Volume in dB """ self.volume_db = max(min(20, volume_db), -20) for demodulator in self.demodulators: demodulator.set_volume(self.volume_db) def get_demod_freqs(self): """Gets baseband frequencies of all demodulators Returns: List[float]: List of baseband center frequencies in Hz """ center_freqs = [] for demodulator in self.demodulators: center_freqs.append(demodulator.center_freq) return center_freqs def main(): """Test the receiver Sets up the hadrware Tunes a couple of demodulators Prints the max power spectrum """ # Create receiver object ask_samp_rate = 4E6 num_demod = 4 type_demod = 0 hw_args = "uhd" freq_correction = 0 record = False play = True receiver = Receiver(ask_samp_rate, num_demod, type_demod, hw_args, freq_correction, record, play) # Start the receiver and wait for samples to accumulate receiver.start() time.sleep(1) # Set frequency, gain, squelch, and volume center_freq = 144.5E6 receiver.set_center_freq(center_freq) receiver.set_gain(10) print "\n" print "Started %s at %.3f Msps" % (hw_args, receiver.samp_rate/1E6) print "RX at %.3f MHz with %d dB gain" % (receiver.center_freq/1E6, receiver.gain_db) receiver.set_squelch(-60) receiver.set_volume(0) print "%d demods of type %d at %d dB squelch and %d dB volume" % \ (num_demod, type_demod, receiver.squelch_db, receiver.volume_db) # Create some baseband channels to tune based on 144 MHz center channels = np.zeros(num_demod) channels[0] = 144.39E6 - receiver.center_freq # APRS channels[1] = 144.6E6 - receiver.center_freq # Tune demodulators to baseband channels # If recording on, this creates empty wav file since manually tuning. for idx, demodulator in enumerate(receiver.demodulators): demodulator.set_center_freq(channels[idx], center_freq) # Print demodulator info for idx, channel in enumerate(channels): print "Tuned demod %d to %.3f MHz" % (idx, (channel+receiver.center_freq) /1E6) while 1: # No need to go faster than 10 Hz rate of GNU Radio probe # Just do 1 Hz here time.sleep(1) # Grab the FFT data and print max value spectrum = receiver.probe_signal_vf.level() print "Max spectrum of %.3f" % (np.max(spectrum)) # Stop the receiver receiver.stop() receiver.wait() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
kaback/ham2mon
apps/receiver.py
Python
gpl-3.0
25,151
tinyMCE.addI18n('en.tinycimmimage_dlg',{ title : 'Image Manager', upload:'Upload' });
wuts/xiaodoudian
application/assets/js/tiny_mce/plugins/tinycimm/langs/en_dlg.js
JavaScript
gpl-3.0
95
/* * This file is part of NanoUI * * Copyright (C) 2016-2018 Guerra24 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package net.luxvacuos.nanoui.rendering.shaders.data; public class Attribute { private int id; private String name; public Attribute(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } }
Guerra24/NanoUI
nanoui-core/src/main/java/net/luxvacuos/nanoui/rendering/shaders/data/Attribute.java
Java
gpl-3.0
1,020
/** * Api Controller is the base for all API Rest controllers, it exposes a common * way of defining routes for each controller */ import * as express from "express"; export abstract class ApiController { public abstract getRoutes(): Route[]; } export interface Route { method: "GET"|"PUT"|"POST"|"DELETE"; handler?: (req: express.Request, res: express.Response) => void; path: string; schema?: object; middleware?: express.Handler[] | express.Handler; }
trymnilsen/KingdomArchitect
ts/server/api/apiController.ts
TypeScript
gpl-3.0
488
<?php $usuario=$_SESSION['usuario']; //Indico la ruta de almacenamiento del usuario $directorio='uploads/'.$usuario.'/'; //Compruebo los ficheros que hay en el directorio excluyendo el propio directorio y el directorio padre $ficheros=array_diff(scandir($directorio),array('..','.')); echo " <div class='contenido'>"; if (count($ficheros)>=1) { echo ' <h2 class="titulo">Pulsa sobre el fichero que quieras descargar</h2>'; } echo " <form action='php/form/download.php' method='post'> <table> <tr>"; //Inicializo x para hacer los cambios de línea en la tabla $x=1; //Presento cada fichero cambiando la clase para que cambie el icono en función de la extensión del fichero foreach ($ficheros as $fichero) { $ruta=str_replace(".crypt","",$directorio.$fichero); echo " <td class='scanner'> <div class='content'> <button class='"; if (preg_match('~\.(jpeg.crypt|jpg.crypt|png.crypt|ico.crypt|gif.crypt)$~',$fichero)) { echo "img"; } elseif (preg_match('~\.(txt.crypt|php.crypt|html.crypt|css.crypt|js.crypt)$~',$fichero)) { echo "html"; } elseif (preg_match('~\.(doc.crypt|docx.crypt|pdf.crypt|xls.crypt|xlsx.crypt|cbr.crypt|cbz.crypt)$~',$fichero)) { echo "doc"; } elseif (preg_match('~\.(mp3.crypt|mp4.crypt|mkv.crypt|avi.crypt|flv.crypt|aac.crypt|vob.crypt)$~',$fichero)) { echo "multi"; } elseif (preg_match('~\.(exe.crypt|zip.crypt|rar.crypt|tar.crypt|gz.crypt)$~',$fichero)) { echo "exe"; } else echo "scan"; echo "' type='submit' value='$ruta' name='descargar'>$fichero</button> </div> </td>"; if ($x % 5 ==0) { echo " </tr> <tr>"; } $x=$x+1; } echo " </tr> </table> </form> </div>"; ?>
gavesc7/CryptoShare
cryptoshare/php/scanners/scanner.php
PHP
gpl-3.0
1,749
package net.thevpc.upa.impl.persistence.connection; /** * Created by vpc on 8/7/15. */ public class DefaultConnectionProfileData { private String databaseProductName ; private String databaseProductVersion ; private String connectionDriverName ; private String connectionDriverVersion ; private String server ; private String port ; private String pathAndName ; private String paramsString; @Override public String toString() { return "DefaultConnectionProfileData{" + "databaseProductName='" + databaseProductName + '\'' + ", databaseProductVersion='" + databaseProductVersion + '\'' + ", connectionDriverName='" + connectionDriverName + '\'' + ", connectionDriverVersion='" + connectionDriverVersion + '\'' + ", server='" + server + '\'' + ", port='" + port + '\'' + ", pathAndName='" + pathAndName + '\'' + ", params='" + paramsString + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DefaultConnectionProfileData that = (DefaultConnectionProfileData) o; if (databaseProductName != null ? !databaseProductName.equals(that.databaseProductName) : that.databaseProductName != null) return false; if (databaseProductVersion != null ? !databaseProductVersion.equals(that.databaseProductVersion) : that.databaseProductVersion != null) return false; if (connectionDriverName != null ? !connectionDriverName.equals(that.connectionDriverName) : that.connectionDriverName != null) return false; if (connectionDriverVersion != null ? !connectionDriverVersion.equals(that.connectionDriverVersion) : that.connectionDriverVersion != null) return false; if (server != null ? !server.equals(that.server) : that.server != null) return false; if (port != null ? !port.equals(that.port) : that.port != null) return false; if (pathAndName != null ? !pathAndName.equals(that.pathAndName) : that.pathAndName != null) return false; return paramsString != null ? paramsString.equals(that.paramsString) : that.paramsString == null; } @Override public int hashCode() { int result = databaseProductName != null ? databaseProductName.hashCode() : 0; result = 31 * result + (databaseProductVersion != null ? databaseProductVersion.hashCode() : 0); result = 31 * result + (connectionDriverName != null ? connectionDriverName.hashCode() : 0); result = 31 * result + (connectionDriverVersion != null ? connectionDriverVersion.hashCode() : 0); result = 31 * result + (server != null ? server.hashCode() : 0); result = 31 * result + (port != null ? port.hashCode() : 0); result = 31 * result + (pathAndName != null ? pathAndName.hashCode() : 0); result = 31 * result + (paramsString != null ? paramsString.hashCode() : 0); return result; } public String getDatabaseProductName() { return databaseProductName; } public void setDatabaseProductName(String databaseProductName) { this.databaseProductName = databaseProductName; } public String getDatabaseProductVersion() { return databaseProductVersion; } public void setDatabaseProductVersion(String databaseProductVersion) { this.databaseProductVersion = databaseProductVersion; } public String getConnectionDriverName() { return connectionDriverName; } public void setConnectionDriverName(String connectionDriverName) { this.connectionDriverName = connectionDriverName; } public String getConnectionDriverVersion() { return connectionDriverVersion; } public void setConnectionDriverVersion(String connectionDriverVersion) { this.connectionDriverVersion = connectionDriverVersion; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getPathAndName() { return pathAndName; } public void setPathAndName(String pathAndName) { this.pathAndName = pathAndName; } public String getParamsString() { return paramsString; } public void setParamsString(String paramsString) { this.paramsString = paramsString; } }
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/persistence/connection/DefaultConnectionProfileData.java
Java
gpl-3.0
4,695
// TestApp.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <iostream> #include <algorithm> #include "sqlite3.h" #include <time.h> #include <sstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { sqlite3* db; sqlite3_open("testdb.db", &db); const char* evaluated; std::string sql = "CREATE TABLE IF NOT EXISTS Files (FileName varchar(256) NOT NULL PRIMARY KEY, FileContents varbinary(1048576))"; sqlite3_stmt* command; sqlite3_prepare_v2(db,sql.data(),sql.size(),&command,&evaluated); int val; while ((val = sqlite3_step(command)) != SQLITE_DONE) { } sqlite3_reset(command); sql = "INSERT INTO Files VALUES (?, ?)"; sqlite3_prepare_v2(db, sql.data(), sql.size(), &command, &evaluated); for (int i = 200; i < 300; i++) { unsigned char* data = new unsigned char[1024 * 1024]; //Insert 30 files std::stringstream mval; mval << i; std::string mstr = mval.str(); sqlite3_bind_text(command, 1, mstr.data(), mstr.size(),0); sqlite3_bind_blob(command, 2, data, 1024 * 1024, 0); while ((val = sqlite3_step(command)) != SQLITE_DONE) { } sqlite3_reset(command); sqlite3_clear_bindings(command); } return 0; }
IDWMaster/OpenNet
fs/Windows/TestApp/TestApp.cpp
C++
gpl-3.0
1,222
package org.isatools.macros.utils; import org.apache.commons.collections15.map.ListOrderedMap; import org.isatools.macros.motiffinder.Motif; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by the ISA team * * @author Eamonn Maguire (eamonnmag@gmail.com) * <p/> * Date: 31/10/2012 * Time: 07:57 */ public class MotifProcessingUtils { private static final String SINGLE_MOTIF_PATTERN = "((:|\\*)*\\{*[\\w\\s]*#[\\w\\s]*(:|,|>)*[\\w\\s]*:*[\\w\\s]*\\}*)"; private static final String WORD_PATTERN = "[ref]*_*(\\w+\\s*)+_*(\\d+)*"; private static final String ALT_SINGLE_MOTIF_PATTERN = "((:|\\*|,)*\\{*[\\w\\s]*#[\\w\\s]*(:|,|>)*(\\w+:*)*\\d*(\\(\\w+\\))*(_)*:*\\}*)"; private static final String NODE_PATTERN = "([\\w\\s_]+:\\d+)"; private static Pattern motifGroupPattern = Pattern.compile(SINGLE_MOTIF_PATTERN + "+"); private static Pattern singleMotifPattern = Pattern.compile(ALT_SINGLE_MOTIF_PATTERN); private static Pattern mergePattern = Pattern.compile(NODE_PATTERN); private static Pattern singleWordPattern = Pattern.compile(WORD_PATTERN); private static Pattern number = Pattern.compile(":\\d+"); public static String findAndCollapseMergeEvents(String representation) { Matcher m = mergePattern.matcher(representation); Map<String, List<Integer>> idToStartIndex = new ListOrderedMap<String, List<Integer>>(); while (m.find()) { String group = representation.substring(m.start(), m.end()); if (!idToStartIndex.containsKey(group)) { idToStartIndex.put(group, new ArrayList<Integer>()); } idToStartIndex.get(group).add(m.start()); } for (String key : idToStartIndex.keySet()) { if (idToStartIndex.get(key).size() > 1) { String reference = "ref_" + key.substring(0, key.lastIndexOf(":")) + "_" + key.substring(key.lastIndexOf(":") + 1); representation = representation.replace(key, reference); representation = representation.replaceFirst(reference, key.substring(0, key.lastIndexOf(":")) + ">" + reference); } } representation = representation.replaceAll("\\(\\d+\\)", ""); representation = representation.replaceAll(":\\d+", ""); return representation; } public static int getNumberOfGroupsInMotifString(Motif motif) { return getNumberOfGroupsInMotifString(motif.getStringRepresentation()); } public static int getNumberOfGroupsInMotifString(String representation) { List<String> branches = getBranchesInMotif(representation); int maxSize = 0; for (String branch : branches) { List<String> nodesInBranch = getNodesInBranch(branch); if (nodesInBranch.size() > maxSize) { maxSize = nodesInBranch.size(); } } return maxSize; } /** * Returns an ordered set of Branches found in the motif. * * @param representation - Motif String representation * @return OrderedSet of branches as found in the String representation. */ public static List<String> getBranchesInMotif(String representation) { List<String> branches = new ArrayList<String>(); Matcher motifGroupMatcher = motifGroupPattern.matcher(representation); while (motifGroupMatcher.find()) { String targetGroup = representation.substring(motifGroupMatcher.start(), motifGroupMatcher.end()); branches.add(targetGroup); } return branches; } /** * Returns an ordered set of nodes found in a branch. * * @param branch - String representation of branch to be processed * @return - OrderedSet of nodes within the branch. */ public static List<String> getNodesInBranch(String branch) { Matcher singleBracketMatcher = singleMotifPattern.matcher(branch); List<String> nodes = new ArrayList<String>(); while (singleBracketMatcher.find()) { nodes.add(branch.substring(singleBracketMatcher.start(), singleBracketMatcher.end())); } return nodes; } /** * Returns the parts of the node, usually of size 3 where 1:Relationship Type 2: Node Type 3:Count */ public static List<String> getPartsOfNode(String node) { Matcher wordMatcher = singleWordPattern.matcher(node); // we want the 2nd word. This is always the node type in our motif representation. List<String> nodeParts = new ArrayList<String>(); while (wordMatcher.find()) { nodeParts.add(node.substring(wordMatcher.start(), wordMatcher.end())); } return nodeParts; } /** * Returns all node ids contained in a motif's String representation. * * @param representation - Motif String representation * @return - Set of node ids as Longs. */ public static Set<Long> getNodeIdsInString(String representation) { Matcher m = number.matcher(representation); Set<Long> nodeIds = new HashSet<Long>(); while (m.find()) { nodeIds.add(Long.valueOf(representation.substring(m.start() + 1, m.end()))); } return nodeIds; } /** * isMotifGood(String representation) * A good motif is one with the same start and end nodes. The code will be similar to that of the code * used to detect the group counts, except for each group, we process the last motif and determine * whether or not the node type is the same. * * @param representation - String representation of motif to be processed * @return true if the end nodes match, false otherwise. */ public static boolean isMotifGood(String representation) { List<String> branches = getBranchesInMotif(representation); Set<String> endNodeTypes = new HashSet<String>(); for (String branch : branches) { List<String> nodesInBranch = getNodesInBranch(branch); String lastNode = ""; for (String node : nodesInBranch) { lastNode = node; } if (!lastNode.isEmpty()) { List<String> motifParts = getPartsOfNode(lastNode); // we want the 2nd word. This is always the node type in our motif representation. String type = motifParts.size() > 1 ? motifParts.get(1) : motifParts.get(0); if (type.startsWith("ref")) { type = type.replaceAll("ref|_|(\\d+)", ""); } if (!type.isEmpty()) { endNodeTypes.add(type.trim()); } } } // if this set is bigger than 1, then we have a 'bad' motif since there is more than one end node type. return endNodeTypes.size() == 1; } private static String removeSoloKeys(String representation, Map<String, List<Integer>> idToStartIndex) { // we do the replacement in reverse to avoid problems with indexes. Set<String> toRemove = new HashSet<String>(); for (String key : idToStartIndex.keySet()) { if (idToStartIndex.get(key).size() == 1) { representation = representation.replaceAll(key, key.substring(0, key.indexOf(":"))); toRemove.add(key); } } for (String key : toRemove) { idToStartIndex.remove(key); } return representation; } public static Set<Long> flattenNodeIds(Collection<Set<Long>> nodesInMotif) { Set<Long> nodes = new HashSet<Long>(); synchronized (nodesInMotif) { try { for (Set<Long> motifNodes : nodesInMotif) { nodes.addAll(motifNodes); } } catch (ConcurrentModificationException cme) { System.err.println("Error occurred " + cme.getMessage()); // don't do anything } } return nodes; } }
ISA-tools/Automacron
src/main/java/org/isatools/macros/utils/MotifProcessingUtils.java
Java
gpl-3.0
8,126
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This plugin is used to access user's private files * * @since 2.0 * @package repository_user * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once($CFG->dirroot . '/repository/lib.php'); /** * repository_user class is used to browse user private files * * @since 2.0 * @package repository_user * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class repository_user extends repository { /** * user plugin doesn't require login * * @return mixed */ public function print_login() { return $this->get_listing(); } /** * Get file listing * * @param string $encodedpath * @return mixed */ public function get_listing($encodedpath = '', $page = '') { global $CFG, $USER, $OUTPUT; $ret = array(); $ret['dynload'] = true; $ret['nosearch'] = true; $ret['nologin'] = true; $manageurl = new moodle_url('/user/files.php'); $ret['manage'] = $manageurl->out(); $list = array(); if (!empty($encodedpath)) { $params = json_decode(base64_decode($encodedpath), true); if (is_array($params)) { $filepath = clean_param($params['filepath'], PARAM_PATH); $filename = clean_param($params['filename'], PARAM_FILE); } } else { $itemid = 0; $filepath = '/'; $filename = null; } $filearea = 'private'; $component = 'user'; $itemid = 0; $context = context_user::instance($USER->id); try { $browser = get_file_browser(); if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) { $pathnodes = array(); $level = $fileinfo; $params = $fileinfo->get_params(); while ($level && $params['component'] == 'user' && $params['filearea'] == 'private') { $encodedpath = base64_encode(json_encode($level->get_params())); $pathnodes[] = array('name'=>$level->get_visible_name(), 'path'=>$encodedpath); $level = $level->get_parent(); $params = $level->get_params(); } $ret['path'] = array_reverse($pathnodes); // build file tree $children = $fileinfo->get_children(); foreach ($children as $child) { if ($child->is_directory()) { $encodedpath = base64_encode(json_encode($child->get_params())); $node = array( 'title' => $child->get_visible_name(), 'datemodified' => $child->get_timemodified(), 'datecreated' => $child->get_timecreated(), 'path' => $encodedpath, 'children'=>array(), 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false) ); $list[] = $node; } else { $encodedpath = base64_encode(json_encode($child->get_params())); $node = array( 'title' => $child->get_visible_name(), 'size' => $child->get_filesize(), 'datemodified' => $child->get_timemodified(), 'datecreated' => $child->get_timecreated(), 'author' => $child->get_author(), 'license' => $child->get_license(), 'isref' => $child->is_external_file(), 'source'=> $encodedpath, 'icon' => $OUTPUT->pix_url(file_file_icon($child, 24))->out(false), 'thumbnail' => $OUTPUT->pix_url(file_file_icon($child, 90))->out(false) ); if ($child->get_status() == 666) { $node['originalmissing'] = true; } if ($imageinfo = $child->get_imageinfo()) { $fileurl = new moodle_url($child->get_url()); $node['realthumbnail'] = $fileurl->out(false, array('preview' => 'thumb', 'oid' => $child->get_timemodified())); $node['realicon'] = $fileurl->out(false, array('preview' => 'tinyicon', 'oid' => $child->get_timemodified())); $node['image_width'] = $imageinfo['width']; $node['image_height'] = $imageinfo['height']; } $list[] = $node; } } } } catch (Exception $e) { throw new repository_exception('emptyfilelist', 'repository_user'); } $ret['list'] = $list; $ret['list'] = array_filter($list, array($this, 'filter')); return $ret; } /** * Does this repository used to browse moodle files? * * @return boolean */ public function has_moodle_files() { return true; } /** * User cannot use the external link to dropbox * * @return int */ public function supported_returntypes() { return FILE_INTERNAL | FILE_REFERENCE; } /** * Return reference file life time * * @param string $ref * @return int */ public function get_reference_file_lifetime($ref) { // this should be realtime return 0; } /** * Is this repository accessing private data? * * @return bool */ public function contains_private_data() { return false; } }
abhinay100/moodle_app
repository/user/lib.php
PHP
gpl-3.0
6,764
#ifndef KONIG_SUITRANK_HPP #define KONIG_SUITRANK_HPP #include <cstdint> #include <cassert> #include <string> #include <konig/core.hpp> namespace konig { class SuitRank { public: enum internal_enum { seven = 7, four = seven, low_pip = seven, min = seven, eight = 8, three = eight, nine = 9, two = nine, ten = 10, one = ten, ace = one, jack = 11, knight = 12, queen = 13, king = 14, max = 15 }; static SuitRank from_value(const std::uint8_t v) { return SuitRank(internal_enum(v)); } static SuitRank from_char(const char c) { return SuitRank(std::string(1, c)); } SuitRank(const internal_enum v) : value_(v) { assert(valid()); } explicit SuitRank(const std::string& s); bool valid() const { return value_ >= low_pip && value_ <= king; } bool face() const { assert(valid()); return value_ >= jack; } char to_char(bool is_red = false) const; operator internal_enum() const { return internal_enum(value_); } SuitRank& operator++() { ++value_; return *this; } SuitRank& operator--() { --value_; return *this; } private: std::uint8_t value_; }; std::ostream& operator<<(std::ostream& o, const SuitRank r); } #endif // KONIG_SUITRANK_HPP
jbytheway/konig
konig/suitrank.hpp
C++
gpl-3.0
1,317
package cz.clovekvtisni.coordinator.server.web.controller; import cz.clovekvtisni.coordinator.server.domain.EventEntity; import cz.clovekvtisni.coordinator.server.domain.PoiEntity; import cz.clovekvtisni.coordinator.server.domain.UserEntity; import cz.clovekvtisni.coordinator.server.filter.EventFilter; import cz.clovekvtisni.coordinator.server.filter.OrganizationInEventFilter; import cz.clovekvtisni.coordinator.server.service.EventService; import cz.clovekvtisni.coordinator.server.tool.objectify.ResultList; import cz.clovekvtisni.coordinator.server.web.util.Breadcrumb; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.Calendar; import java.util.List; @Controller @RequestMapping("/superadmin/event/list") public class EventListController extends AbstractSuperadminController { @Autowired private EventService eventService; @RequestMapping public String list(@RequestParam(value = "bookmark", required = false) String bookmark, Model model) { UserEntity loggedUser = getLoggedUser(); ResultList<EventEntity> events; if (loggedUser.isSuperadmin()) { events = eventService.findByFilter(new EventFilter(), DEFAULT_LIST_LENGTH, bookmark, EventService.FLAG_FETCH_LOCATIONS); } else { OrganizationInEventFilter inEventFilter = new OrganizationInEventFilter(); inEventFilter.setOrganizationIdVal(loggedUser.getOrganizationId()); events = eventService.findByOrganizationFilter(inEventFilter, DEFAULT_LIST_LENGTH, bookmark, EventService.FLAG_FETCH_LOCATIONS); } model.addAttribute("events", events.getResult()); return "superadmin/event-list"; } }
Tomucha/coordinator
coordinator-server/src/main/java/cz/clovekvtisni/coordinator/server/web/controller/EventListController.java
Java
gpl-3.0
2,011
package com.chat.db.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; public class ContactProvider extends ContentProvider{ private final static String AUTHORITY = ContactProvider.class.getCanonicalName(); /**ÁªÏµÈËÊý¾Ý¿â*/ private final static String DB_NAME = "contact.db"; /**ÁªÏµÈË*/ private final static String CONTACT_TABLE = "contact"; /**ÁªÏµÈË×é*/ private final static String CONTACT_GROUP_TABLE = "group"; /**Êý¾Ý¿â°æ±¾*/ private final static int DB_VERSION = 1; /**ÁªÏµÈË uri*/ public final static Uri CONTACT_URI = Uri.parse("content://"+AUTHORITY+"/"+CONTACT_TABLE); /**ÁªÏµ×é uri*/ public final static Uri CONTACT_GROUP_URI = Uri.parse("content://"+AUTHORITY+"/"+CONTACT_GROUP_TABLE); private SQLiteOpenHelper dbHelper; private SQLiteDatabase db; private static final UriMatcher URI_MATCHER; /**UriMatcherÆ¥ÅäÖµ*/ public static final int CONTACTS = 1; public static final int GROUPS = 2; static{ URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(AUTHORITY, CONTACT_TABLE, CONTACTS); URI_MATCHER.addURI(AUTHORITY, CONTACT_GROUP_TABLE, GROUPS); } @Override public boolean onCreate() { dbHelper = new ContactDatabaseHelper(getContext()); return (dbHelper == null) ?false:true; } /**¸ù¾Ýuri²éѯ³öselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼ÆäÖÐprojection¾ÍÊÇÒ»¸öÁÐÃûÁÐ±í£¬±íÃ÷ֻѡÔñÖ¸¶¨µÄÊý¾ÝÁÐ*/ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder) { Log.e("SQLite£º","½øÈë²éѯ "); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); db = dbHelper.getReadableDatabase(); Cursor ret = null; switch(URI_MATCHER.match(uri)){ case CONTACTS: qb.setTables(CONTACT_TABLE); ret = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); break; case GROUPS: break; } ret.setNotificationUri(getContext().getContentResolver(), uri); return ret; } /**¸ù¾ÝuriËù²åÈëvalues*/ @Override public Uri insert(Uri uri, ContentValues values) { Log.e("SQLite£º","½øÈë²åÈë "); db = dbHelper.getWritableDatabase(); Uri result = null; switch(URI_MATCHER.match(uri)){ case CONTACTS: long rowId = db.insert(CONTACT_TABLE, ContactColumns.ACCOUNT, values); result = ContentUris.withAppendedId(uri, rowId); break; default:break; } if(result!=null){ getContext().getContentResolver().notifyChange(result,null); } return result; } /** ¸ù¾ÝUriɾ³ýselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼ */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { db = dbHelper.getWritableDatabase(); int count = 0; Log.e("SQLite£º","½øÈëɾ³ý "); switch(URI_MATCHER.match(uri)){ case CONTACTS: count = db.delete(CONTACT_TABLE, selection, selectionArgs); break; default:break; } if (count != 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /**¸ù¾ÝuriÐÞ¸ÄselectionÌõ¼þËùÆ¥ÅäµÄÈ«²¿¼Ç¼*/ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { db = dbHelper.getWritableDatabase(); int count = 0; Log.e("SQLite£º","½øÈë¸üР"); switch(URI_MATCHER.match(uri)){ case CONTACTS: count = db.update(CONTACT_TABLE, values, selection, selectionArgs); break; default:break; } Log.e("SQLite£º","¸üнá¹û " + count); if (count != 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /** *¸Ã·½·¨ÓÃÓÚ·µ»Øµ±Ç°UriËù´ú±íµÄÊý¾ÝµÄMIMEÀàÐÍ */ @Override public String getType(Uri uri) { return null; } /**ÁªÏµÈËÐÅÏ¢Êý¾Ý¿â*/ private class ContactDatabaseHelper extends SQLiteOpenHelper{ public ContactDatabaseHelper(Context context){ super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + CONTACT_TABLE + "(" + ContactColumns._ID+ " INTEGER PRIMARY KEY," + ContactColumns.AVATAR + " BLOB," +ContactColumns.SORT + " TEXT," +ContactColumns.NAME + " TEXT," +ContactColumns.JID + " TEXT," +ContactColumns.TYPE + " TEXT," +ContactColumns.STATUS + " TEXT," +ContactColumns.ACCOUNT + " TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+ CONTACT_TABLE); onCreate(db); } } /** * ÁªÏµÈËÊôÐÔ *BaseColumnsÊÇ×Ô¶¨ÒåÁÐÃû£¬ ÀïÃæÓÐÁ½¸ö×Ö¶Î _id,_count,ÏÂÃæÊÇÀ©Õ¹ */ public static class ContactColumns implements BaseColumns{ //Óû§Í·Ïñ public static final String AVATAR = "avatar"; //Óû§±¸×¢ public static final String NAME = "name"; //Ö÷È˵ĺÃÓÑ public static final String ACCOUNT = "account"; //ºÃÓѵÄÊ××Öĸ public static final String SORT = "sort"; //Ö÷ÈË public static final String JID = "jid"; //ºÃÓÑÀàÐÍ(Ìí¼ÓºÃÓÑʱ£ºboth£¬to£¬from) public static final String TYPE = "type"; //ºÃÓÑ״̬£¨ÔÚÏß»¹ÊÇÀëÏß £© public static final String STATUS = "status"; } }
masach/FaceWhat
FacewhatDroid/src/com/chat/DB/provider/ContactProvider.java
Java
gpl-3.0
5,381
package cn.edu.jxnu.awesome_campus.database.table.education; /** * Created by MummyDing on 16-1-26. * GitHub: https://github.com/MummyDing * Blog: http://blog.csdn.net/mummyding */ public class ExamTimeTable { /*** * 考试安排表 */ public static final String NAME = "ExamTimeTable"; /** * 考试安排表 * 不设主键 * 说明: 注销需清空此表 否则新账号登陆考试安排信息将发生冲突 */ public static final String COURSE_ID = "CourseID"; public static final String COURSE_NAME = "CourseName"; public static final String EXAM_TIME = "ExamTime"; public static final String EXAM_ROOM = "ExamRoom"; public static final String EXAM_SEAT = "ExamSeat"; // 备注信息 public static final String REMARK = "Remark"; /** * 字段ID 数据库操作建立字段对应关系 从0开始 */ public static final int ID_COURSE_ID = 0; public static final int ID_COURSE_NAME =1; public static final int ID_EXAM_TIME = 2; public static final int ID_EXAM_ROOM = 3; public static final int ID_EXAM_SEAT = 4; public static final int ID_REMARK = 5; public static final String CREATE_TABLE = "create table "+NAME+"("+ COURSE_ID+" text, "+ COURSE_NAME+" text, "+ EXAM_TIME+" text, "+ EXAM_ROOM+" text, "+ EXAM_SEAT+" text, "+ REMARK+" text)"; }
MummyDing/Awesome-Campus
app/src/main/java/cn/edu/jxnu/awesome_campus/database/table/education/ExamTimeTable.java
Java
gpl-3.0
1,445
function divReplaceWith(selector, url) { $.get(url, function(response) { $(selector).html(response); }) }
smcs/online-language-lab
examples/dynamic-replacement/js/main.js
JavaScript
gpl-3.0
109
package com.excalibur.frame.exception; import com.excalibur.core.base.ExcaliburException; /** * Thrown to indicate that a compulsory parameter is missing. * * @author Foxykeep */ public final class DataException extends ExcaliburException { private static final long serialVersionUID = -6031863210486494461L; /** * Constructs a new {@link DataException} that includes the current stack trace. */ public DataException() { super(); } /** * Constructs a new {@link DataException} that includes the current stack trace, the * specified detail message and the specified cause. * * @param detailMessage The detail message for this exception. * @param throwable The cause of this exception. */ public DataException(final String detailMessage, final Throwable throwable) { super(detailMessage, throwable); } /** * Constructs a new {@link DataException} that includes the current stack trace and the * specified detail message. * * @param detailMessage The detail message for this exception. */ public DataException(final String detailMessage) { super(detailMessage); } /** * Constructs a new {@link DataException} that includes the current stack trace and the * specified cause. * * @param throwable The cause of this exception. */ public DataException(final Throwable throwable) { super(throwable); } }
jorson/excalibur
excalibur-frame/src/main/java/com/excalibur/frame/exception/DataException.java
Java
gpl-3.0
1,486
package lab.p03_employee_info.models; import lab.p03_employee_info.contracts.Formatter; import lab.p03_employee_info.contracts.InfoProvider; public class ConsoleClient { private Formatter formatter; private InfoProvider infoProvider; public ConsoleClient(Formatter formatter, InfoProvider infoProvider) { this.formatter = formatter; this.infoProvider = infoProvider; } public void printEmployeesByName(){ System.out.println(this.formatter.format(this.infoProvider.getEmployeesByName())); } public void printEmployeesBySalary() { System.out.println(this.formatter.format(this.infoProvider.getEmployeesBySalary())); } }
kostovhg/SoftUni
Java Fundamentals-Sep17/Java_OOP_Advanced/h_InterfaceSegregationDependencyInversion/src/lab/p03_employee_info/models/ConsoleClient.java
Java
gpl-3.0
689
/* * Copyright (C) 2014 Mustafa Gönül * * dnw 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. * * dnw 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/>. * **/ /** * @file utility/string.hpp * @author Mustafa Gönül */ #ifndef DNW_UTILITY_STRING_HPP #define DNW_UTILITY_STRING_HPP #include "utility/common.hpp" #include <map> namespace dnw { namespace utility { namespace string { using Map = std::map<String, String>; /** * @brief Splits @a str with @a delimiter into @a result. * @param str * @param delimiter * @param result */ void split(String const &str, char delimiter, Strings &result); /** * @brief Splits @a str @a delimiter into @a result. * @param str * @param delimiter * @param result */ void split(String const &str, String const &delimiter, Strings &result); /** * @brief Splits @a str with newline character into @a result. * @param str * @param result */ void split(String const &str, Strings &result); /** * @brief Merges @a items with @a delimiter into @result * @param items * @param delimiter * @param result */ void merge(Strings const &items, char delimiter, String &result); /** * @brief Replaces @a from strings to @a to strings in the @a str. * @param from * @param to * @param str */ void replace(String const &from, String const &to, String &str); // TODO mustafa: doxygen void convert(Map const &map, String &str); // TODO mustafa: doxygen void convert(String const &expression, Map const &map, String &str); } } } #endif // DNW_UTILITY_STRING_HPP
mustafagonul/dnw
utility/string.hpp
C++
gpl-3.0
2,289
using TuBS; using System; using Gtk; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Linq; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; public partial class MainWindow : Gtk.Window { protected List<string> DumpText (FileInfo file, char[] code_page) { List<string> script = new List<string> (); BinaryReader reader = new BinaryReader (File.OpenRead(file.FullName)); Scene scene = new Scene (); string str = ""; string strsq = ""; while (reader.BaseStream.Position < reader.BaseStream.Length) { ushort num1 = reader.ReadUInt16 (); if ((int)num1 < 32768) {//ordinary char from "font" if (code_page.Length > num1) str += code_page [num1].ToString (); else str += "<" + num1.ToString () + ">"; } else if ((int)num1 == 38147) str = str + "<[" + (reader.ReadUInt16 ()).ToString () + "," + (reader.ReadUInt16 ()).ToString () + "," + (reader.ReadUInt16 ()).ToString () + "]"; else if ((int)num1 == 32769) str = str + "●" + "[" + (reader.ReadUInt16 ()).ToString () + "]"; else if ((int)num1 == 38144) str += ">"; else if ((int)num1 == 33536) str += "\r\n"; else if ((int)num1 == 44544) str += "▲"; else if ((int)num1 == 33024) { // window end if (scene.Active == true) script.Add ("#" + scene.Window + "; Size: " + scene.GetSize () + "; " + scene.GetActor ()); script.Add (str); script.Add ("-----------------------"); str = ""; //info bytes } else if ((int)num1 == 35074) { str += "■"; reader.BaseStream.Position -= 2; strsq += "["; for (int i = 0; i < 6; i++) strsq += reader.ReadByte () + "."; strsq += "]"; } else if ((int)num1 == 39168) { //upper window scene.Window = "Upper Window"; str += "■"; reader.BaseStream.Position -= 2; strsq += "[" + reader.ReadByte () + "." + reader.ReadByte () + ".]"; } else if ((int)num1 == 39424) { //lower window scene.Window = "Lower Window"; str += "■"; reader.BaseStream.Position -= 2; strsq += "[" + reader.ReadByte () + "." + reader.ReadByte () + ".]"; } else if ((int)num1 == 2024 || (int)num1 == 33280 || (int)num1 == 39936 || (int)num1 == 47104) { //some strange chars str += "■"; reader.BaseStream.Position -= 2; strsq += "[" + reader.ReadByte () + "." + reader.ReadByte () + ".]"; } else if ((int)num1 == 41985) { //actor tag ushort actor_id = reader.ReadUInt16 (); scene.SetActor (actor_id); str += "■"; reader.BaseStream.Position -= 4; strsq += "["; for (int i = 0; i < 4; i++) if (reader.BaseStream.Position < reader.BaseStream.Length) { strsq += reader.ReadByte () + "."; } strsq += "]"; } else if ((int)num1 == 40961) { //window size ushort size = reader.ReadUInt16 (); scene.SetSize (size); str += "■"; reader.BaseStream.Position -= 4; strsq += "["; for (int i = 0; i < 4; i++) if (reader.BaseStream.Position < reader.BaseStream.Length) { strsq += reader.ReadByte () + "."; } strsq += "]"; } else { str += "■"; reader.BaseStream.Position -= 2; strsq += "["; for (int i = 0; i < 4; i++) if (reader.BaseStream.Position < reader.BaseStream.Length) { strsq += reader.ReadByte () + "."; } strsq += "]"; } } if (str != "") script.Add (str); if (strsq != "") { StreamWriter sqwriter = new StreamWriter (file.Directory.ToString () + System.IO.Path.DirectorySeparatorChar + "Squares.txt", true); sqwriter.WriteLine ("<" + file.Name + ">"); sqwriter.WriteLine (strsq); sqwriter.WriteLine (); sqwriter.Flush (); sqwriter.Close (); } reader.Close (); return script; } protected void ScriptMaker (string script_dir, string out_txt) { StreamWriter writer = new StreamWriter ((Stream)new FileStream (out_txt, FileMode.Create)); DirectoryInfo info = new DirectoryInfo (script_dir); FileInfo[] files = info.GetFiles ().OrderBy (p => p.CreationTime).ToArray (); string[] num = script_dir.Split(System.IO.Path.DirectorySeparatorChar); char[] code_page; if(num.Length == 3) code_page = GetCodePage(Int32.Parse(num[1]), num[2]); else code_page = GetCodePage(Int32.Parse(num[1])); int index = 0; foreach (FileInfo file in files) { index++; if (file.Extension == "") { List<string> script_list = DumpText (file, code_page); string line = "#### File " + index + ": " + file.Name + " ####"; if (script_list.Count > 0) { if (script_list.Count == 1 && script_list [0] == "\r\n") continue; writer.WriteLine (line); for (int index2 = 0; index2 < script_list.Count; ++index2) { writer.Write (script_list [index2]); writer.WriteLine (); } writer.WriteLine ("###### End ######"); writer.WriteLine (); } } } writer.Flush (); writer.Close (); } } class Scene { ushort upper_actor; ushort lower_actor; ushort upper_size; ushort lower_size; public string Window = "Lower Window"; //message appears in lower window by default public bool Active = false; public void SetSize (ushort size) { if (Window == "Upper Window") upper_size = size; else lower_size = size; } public string GetSize () { if (Window == "Upper Window") return upper_size.ToString (); return lower_size.ToString (); } public void SetActor (ushort id) { Active = true; if (Window == "Upper Window") upper_actor = id; else //"Lower Window" lower_actor = id; } public string GetActor () { if (Window == "Upper Window") return Cast.GetActorById (upper_actor); return Cast.GetActorById (lower_actor); } } static class Cast { static string[] actors; static Cast () { if (File.Exists ("faces.txt")) actors = File.ReadAllLines ("faces.txt"); else actors = new string[1568]; } public static string GetActorById (ushort id) { return actors [id]; } }
Lightgazer/Berwick-Saga-translation
TuBS/TuBS/ExportScript.cs
C#
gpl-3.0
5,979
### # Copyright 2016 - 2022 Green River Data Analysis, LLC # # License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md ### require 'rails_helper' require_relative 'datalab_caper_context' RSpec.describe 'Datalab 2021 CAPER - RRH', type: :model do include_context 'datalab caper context' before(:all) do setup run(rrh_1_filter) end after(:all) do cleanup end it 'Q4a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q4a', skip: [ 'B2', # expected is a name not and ID? 'L2', # Is the generator name, so not expected to match ], ) end it 'Q5a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q5a', ) end it 'Q6a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6a', ) end it 'Q6b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6b', ) end it 'Q6c' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6c', ) end it 'Q6d' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6d', ) end it 'Q6e' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6e', ) end it 'Q6f' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q6f', ) end it 'Q7a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q7a', ) end it 'Q7b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q7b', ) end it 'Q8a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q8a', ) end it 'Q8b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q8b', ) end it 'Q9a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q9a', ) end it 'Q9b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q9b', ) end it 'Q10a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q10a', ) end it 'Q10b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q10b', ) end it 'Q10c' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q10c', ) end it 'Q10d' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q10d', ) end it 'Q11' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q11', ) end it 'Q12a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q12a', ) end it 'Q12b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q12b', ) end it 'Q13a1' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q13a1', ) end it 'Q13b1' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q13b1', ) end it 'Q13c1' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q13c1', ) end it 'Q14a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q14a', ) end it 'Q14b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q14b', ) end it 'Q15' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q15', ) end it 'Q16' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q16', ) end it 'Q17' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q17', ) end it 'Q19b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q19b', ) end it 'Q20a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q20a', ) end it 'Q21' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q21', ) end it 'Q22a2' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q22a2', ) end it 'Q22c' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q22c', ) end it 'Q22d' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q22d', ) end it 'Q22e' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q22e', ) end it 'Q23c' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q23c', ) end it 'Q24' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q24', ) end it 'Q25a' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q25a', ) end it 'Q26b' do compare_results( file_path: result_file_prefix + 'rrh', question: 'Q26b', ) end end
greenriver/hmis-warehouse
drivers/hud_apr/spec/models/fy2021/datalab_caper/rrh_spec.rb
Ruby
gpl-3.0
5,241
package org.trusst.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Properties; import org.trusst.market.MarketItem; import org.trusst.market.item.AppItem; public class DBUtils { private static Connection conn = null; private static Statement stmt = null; private static String dbLocation = "droidReviewDB"; private static String dbURL = "jdbc:derby://localhost:1527/"; private static String driverName = "org.apache.derby.jdbc.ClientDriver"; private static Connection getConnInstance() { if (conn == null) { conn = createConnection("admin","admin"); } return conn; } public static boolean populateMarketItemToDB(MarketItem marketItem) { boolean result = false; conn = getConnInstance(); if (conn!= null){ result = incertMarketItem(conn, marketItem); result = incertMarketItemReviews(conn, marketItem); }else { System.out.print("Could not connect to the database"); System.out.println("Check that the Derby Network Server is running on localhost."); } return result; } private static boolean incertMarketItem(Connection conn, MarketItem item ){ // Create Star ratings array String sql = "insert into APP.MarketItem " + "(id, " + "recordDate, " + "ItemId, " + "ItemName, " + "ItemDeveloper, " + "ItemDeveloperRating, " + "ItemAvgRating, " + "RatingCount, " + "LastUpdate, " + "NumOfInstalls, " + "ItemPrice, " + "ItemSize, " + "CurrentVersion, " + "ContentRating, " + "fiveStars, " + "fourStars, " + "threeStarts, " + "twoStars, " + "oneStar)" + "values " + "("+getNextID("APP.MarketItem")+"," + "'" + (getCurrentDateTime()) + "', " + "'" + (item.getItemId()).replaceAll("[^a-zA-Z0-9. ]+","") + "', " + "'" + (item.getItemName()).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (item.getItemDeveloper()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemDeveloperRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemAvgRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getRatingCount()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getLastUpdate()).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (item.getNumOfDownloads()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemPrice()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getItemSize()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getCurrentVersion()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getContentRating()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getFiveStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getFourStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getThreeStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getTwoStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "', " + "'" + (item.getOneStarRatings()).replaceAll("[^a-zA-Z0-9]+","") + "')"; int numRows = executeUpdate(conn,sql); return ((numRows == 1) ? true : false ); } private static boolean incertMarketItemReviews(Connection conn, MarketItem item ){ boolean result = false; // Create Star ratings array String splittableString = item.getItemUserReviews(); String[] reviewList = splittableString.split(" :::: "); for (int i = 0; i < reviewList.length; i++) { String[] review = reviewList[i].split(" :: "); if (review.length <= 1){ review = new String[]{"none","none","none","none","none","none"}; } String sql = "insert into APP.MarketItemReviews " + "(id, " + "recordDate, " + "reviewItemId, " + "reviewUserId, " + "reviewUser, " + "reviewDate, " + "reviewStarValue, " + "reviewHeading, " + "reviewBody)" + "values " + "("+getNextID("APP.MarketItemReviews")+"," + "'" + (getCurrentDateTime()) + "', " + +(getNextID("APP.MarketItem")-1)+"," + "'" + (review[0]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[1]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[2]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[3]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[4]).replaceAll("[^a-zA-Z0-9 ]+","") + "', " + "'" + (review[5]).replaceAll("[^a-zA-Z0-9 ]++","") + "')"; int numRows = executeUpdate(conn,sql); result = (numRows == 1) ? true : false ; } return result ; } private static Connection createConnection(String userName, String password) { try { Class.forName(driverName); Properties dbProps = new Properties(); dbProps.put("user", userName); dbProps.put("password", password); conn = DriverManager.getConnection(dbURL + dbLocation, dbProps); } catch (Exception except){ System.out.print("Could not connect to the database with username: " + userName); System.out.println(" password " + password); System.out.println("Check that the Derby Network Server is running on localhost."); except.printStackTrace(); } return conn; } private static int executeUpdate(Connection conn, String sql) { // the number of rows affected by the update or insert int numRows = 0; try { stmt = conn.createStatement(); numRows = stmt.executeUpdate(sql); stmt.close(); } catch (SQLException sqlExcept) { sqlExcept.printStackTrace(); } return numRows; } private static String[] runQuery(Connection conn, String sql) { List<String> list = Collections.synchronizedList(new ArrayList<String>(10)); try { stmt = conn.createStatement(); ResultSet results = stmt.executeQuery(sql); ResultSetMetaData rsmd = results.getMetaData(); int numberCols = rsmd.getColumnCount(); while(results.next()) { StringBuffer sbuf = new StringBuffer(200); for (int i = 1; i <= numberCols; i++){ sbuf.append(results.getString(i)); sbuf.append(", "); } list.add(sbuf.toString()); } results.close(); stmt.close(); } catch (SQLException sqlExcept) { sqlExcept.printStackTrace(); } return list.toArray(new String[list.size()]); } private static boolean dropAllReceordsFromTable(Connection conn, String table) { String sql = "delete from " + table ; int numRows = executeUpdate(conn,sql); if (numRows >= 0){ return true; } return false; } private static String getCurrentDateTime(){ Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); String dateNow = formatter.format(currentDate.getTime()); return dateNow; } private static int getNextID(String table){ Connection conn = getConnInstance(); StringBuffer sqlStringBuffer = new StringBuffer(); sqlStringBuffer.append("select max(id) from "); sqlStringBuffer.append(table); String[] runQueryResult = runQuery(conn, sqlStringBuffer.toString()); if (runQueryResult.length == 0){ return 0; } else if (runQueryResult[0].equals("null, ")) { return 1; }else{ Integer result = Integer.parseInt(runQueryResult[0].split(",")[0]); return result.intValue()+1; } } }
sandakith/TRRuSST
TrReviewScraper/src/main/java/org/trusst/utils/DBUtils.java
Java
gpl-3.0
8,980
# revlog.py - storage back-end for mercurial # # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. """Storage back-end for Mercurial. This provides efficient delta storage with O(1) retrieve and append and O(changes) merge between branches. """ # import stuff from node for others to import from revlog from node import bin, hex, nullid, nullrev from i18n import _ import ancestor, mdiff, parsers, error, util, dagutil import struct, zlib, errno _pack = struct.pack _unpack = struct.unpack _compress = zlib.compress _decompress = zlib.decompress _sha = util.sha1 # revlog header flags REVLOGV0 = 0 REVLOGNG = 1 REVLOGNGINLINEDATA = (1 << 16) REVLOGGENERALDELTA = (1 << 17) REVLOG_DEFAULT_FLAGS = REVLOGNGINLINEDATA REVLOG_DEFAULT_FORMAT = REVLOGNG REVLOG_DEFAULT_VERSION = REVLOG_DEFAULT_FORMAT | REVLOG_DEFAULT_FLAGS REVLOGNG_FLAGS = REVLOGNGINLINEDATA | REVLOGGENERALDELTA # revlog index flags REVIDX_KNOWN_FLAGS = 0 # max size of revlog with inline data _maxinline = 131072 _chunksize = 1048576 RevlogError = error.RevlogError LookupError = error.LookupError def getoffset(q): return int(q >> 16) def gettype(q): return int(q & 0xFFFF) def offset_type(offset, type): return long(long(offset) << 16 | type) nullhash = _sha(nullid) def hash(text, p1, p2): """generate a hash from the given text and its parent hashes This hash combines both the current file contents and its history in a manner that makes it easy to distinguish nodes with the same content in the revision graph. """ # As of now, if one of the parent node is null, p2 is null if p2 == nullid: # deep copy of a hash is faster than creating one s = nullhash.copy() s.update(p1) else: # none of the parent nodes are nullid l = [p1, p2] l.sort() s = _sha(l[0]) s.update(l[1]) s.update(text) return s.digest() def compress(text): """ generate a possibly-compressed representation of text """ if not text: return ("", text) l = len(text) bin = None if l < 44: pass elif l > 1000000: # zlib makes an internal copy, thus doubling memory usage for # large files, so lets do this in pieces z = zlib.compressobj() p = [] pos = 0 while pos < l: pos2 = pos + 2**20 p.append(z.compress(text[pos:pos2])) pos = pos2 p.append(z.flush()) if sum(map(len, p)) < l: bin = "".join(p) else: bin = _compress(text) if bin is None or len(bin) > l: if text[0] == '\0': return ("", text) return ('u', text) return ("", bin) def decompress(bin): """ decompress the given input """ if not bin: return bin t = bin[0] if t == '\0': return bin if t == 'x': return _decompress(bin) if t == 'u': return bin[1:] raise RevlogError(_("unknown compression type %r") % t) indexformatv0 = ">4l20s20s20s" v0shaoffset = 56 class revlogoldio(object): def __init__(self): self.size = struct.calcsize(indexformatv0) def parseindex(self, data, inline): s = self.size index = [] nodemap = {nullid: nullrev} n = off = 0 l = len(data) while off + s <= l: cur = data[off:off + s] off += s e = _unpack(indexformatv0, cur) # transform to revlogv1 format e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3], nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6]) index.append(e2) nodemap[e[6]] = n n += 1 # add the magic null revision at -1 index.append((0, 0, 0, -1, -1, -1, -1, nullid)) return index, nodemap, None def packentry(self, entry, node, version, rev): if gettype(entry[0]): raise RevlogError(_("index entry flags need RevlogNG")) e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4], node(entry[5]), node(entry[6]), entry[7]) return _pack(indexformatv0, *e2) # index ng: # 6 bytes: offset # 2 bytes: flags # 4 bytes: compressed length # 4 bytes: uncompressed length # 4 bytes: base rev # 4 bytes: link rev # 4 bytes: parent 1 rev # 4 bytes: parent 2 rev # 32 bytes: nodeid indexformatng = ">Qiiiiii20s12x" ngshaoffset = 32 versionformat = ">I" class revlogio(object): def __init__(self): self.size = struct.calcsize(indexformatng) def parseindex(self, data, inline): # call the C implementation to parse the index data index, cache = parsers.parse_index2(data, inline) return index, getattr(index, 'nodemap', None), cache def packentry(self, entry, node, version, rev): p = _pack(indexformatng, *entry) if rev == 0: p = _pack(versionformat, version) + p[4:] return p class revlog(object): """ the underlying revision storage object A revlog consists of two parts, an index and the revision data. The index is a file with a fixed record size containing information on each revision, including its nodeid (hash), the nodeids of its parents, the position and offset of its data within the data file, and the revision it's based on. Finally, each entry contains a linkrev entry that can serve as a pointer to external data. The revision data itself is a linear collection of data chunks. Each chunk represents a revision and is usually represented as a delta against the previous chunk. To bound lookup time, runs of deltas are limited to about 2 times the length of the original version data. This makes retrieval of a version proportional to its size, or O(1) relative to the number of revisions. Both pieces of the revlog are written to in an append-only fashion, which means we never need to rewrite a file to insert or remove data, and can use some simple techniques to avoid the need for locking while reading. """ def __init__(self, opener, indexfile): """ create a revlog object opener is a function that abstracts the file opening operation and can be used to implement COW semantics or the like. """ self.indexfile = indexfile self.datafile = indexfile[:-2] + ".d" self.opener = opener self._cache = None self._basecache = (0, 0) self._chunkcache = (0, '') self.index = [] self._pcache = {} self._nodecache = {nullid: nullrev} self._nodepos = None v = REVLOG_DEFAULT_VERSION opts = getattr(opener, 'options', None) if opts is not None: if 'revlogv1' in opts: if 'generaldelta' in opts: v |= REVLOGGENERALDELTA else: v = 0 i = '' self._initempty = True try: f = self.opener(self.indexfile) i = f.read() f.close() if len(i) > 0: v = struct.unpack(versionformat, i[:4])[0] self._initempty = False except IOError, inst: if inst.errno != errno.ENOENT: raise self.version = v self._inline = v & REVLOGNGINLINEDATA self._generaldelta = v & REVLOGGENERALDELTA flags = v & ~0xFFFF fmt = v & 0xFFFF if fmt == REVLOGV0 and flags: raise RevlogError(_("index %s unknown flags %#04x for format v0") % (self.indexfile, flags >> 16)) elif fmt == REVLOGNG and flags & ~REVLOGNG_FLAGS: raise RevlogError(_("index %s unknown flags %#04x for revlogng") % (self.indexfile, flags >> 16)) elif fmt > REVLOGNG: raise RevlogError(_("index %s unknown format %d") % (self.indexfile, fmt)) self._io = revlogio() if self.version == REVLOGV0: self._io = revlogoldio() try: d = self._io.parseindex(i, self._inline) except (ValueError, IndexError): raise RevlogError(_("index %s is corrupted") % (self.indexfile)) self.index, nodemap, self._chunkcache = d if nodemap is not None: self.nodemap = self._nodecache = nodemap if not self._chunkcache: self._chunkclear() def tip(self): return self.node(len(self.index) - 2) def __len__(self): return len(self.index) - 1 def __iter__(self): for i in xrange(len(self)): yield i @util.propertycache def nodemap(self): self.rev(self.node(0)) return self._nodecache def hasnode(self, node): try: self.rev(node) return True except KeyError: return False def clearcaches(self): try: self._nodecache.clearcaches() except AttributeError: self._nodecache = {nullid: nullrev} self._nodepos = None def rev(self, node): try: return self._nodecache[node] except RevlogError: # parsers.c radix tree lookup failed raise LookupError(node, self.indexfile, _('no node')) except KeyError: # pure python cache lookup failed n = self._nodecache i = self.index p = self._nodepos if p is None: p = len(i) - 2 for r in xrange(p, -1, -1): v = i[r][7] n[v] = r if v == node: self._nodepos = r - 1 return r raise LookupError(node, self.indexfile, _('no node')) def node(self, rev): return self.index[rev][7] def linkrev(self, rev): return self.index[rev][4] def parents(self, node): i = self.index d = i[self.rev(node)] return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline def parentrevs(self, rev): return self.index[rev][5:7] def start(self, rev): return int(self.index[rev][0] >> 16) def end(self, rev): return self.start(rev) + self.length(rev) def length(self, rev): return self.index[rev][1] def chainbase(self, rev): index = self.index base = index[rev][3] while base != rev: rev = base base = index[rev][3] return base def flags(self, rev): return self.index[rev][0] & 0xFFFF def rawsize(self, rev): """return the length of the uncompressed text for a given revision""" l = self.index[rev][2] if l >= 0: return l t = self.revision(self.node(rev)) return len(t) size = rawsize def reachable(self, node, stop=None): """return the set of all nodes ancestral to a given node, including the node itself, stopping when stop is matched""" reachable = set((node,)) visit = [node] if stop: stopn = self.rev(stop) else: stopn = 0 while visit: n = visit.pop(0) if n == stop: continue if n == nullid: continue for p in self.parents(n): if self.rev(p) < stopn: continue if p not in reachable: reachable.add(p) visit.append(p) return reachable def ancestors(self, *revs): """Generate the ancestors of 'revs' in reverse topological order. Yield a sequence of revision numbers starting with the parents of each revision in revs, i.e., each revision is *not* considered an ancestor of itself. Results are in breadth-first order: parents of each rev in revs, then parents of those, etc. Result does not include the null revision.""" visit = list(revs) seen = set([nullrev]) while visit: for parent in self.parentrevs(visit.pop(0)): if parent not in seen: visit.append(parent) seen.add(parent) yield parent def descendants(self, *revs): """Generate the descendants of 'revs' in revision order. Yield a sequence of revision numbers starting with a child of some rev in revs, i.e., each revision is *not* considered a descendant of itself. Results are ordered by revision number (a topological sort).""" first = min(revs) if first == nullrev: for i in self: yield i return seen = set(revs) for i in xrange(first + 1, len(self)): for x in self.parentrevs(i): if x != nullrev and x in seen: seen.add(i) yield i break def findcommonmissing(self, common=None, heads=None): """Return a tuple of the ancestors of common and the ancestors of heads that are not ancestors of common. In revset terminology, we return the tuple: ::common, (::heads) - (::common) The list is sorted by revision number, meaning it is topologically sorted. 'heads' and 'common' are both lists of node IDs. If heads is not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: common = [nullid] if heads is None: heads = self.heads() common = [self.rev(n) for n in common] heads = [self.rev(n) for n in heads] # we want the ancestors, but inclusive has = set(self.ancestors(*common)) has.add(nullrev) has.update(common) # take all ancestors from heads that aren't in has missing = set() visit = [r for r in heads if r not in has] while visit: r = visit.pop(0) if r in missing: continue else: missing.add(r) for p in self.parentrevs(r): if p not in has: visit.append(p) missing = list(missing) missing.sort() return has, [self.node(r) for r in missing] def findmissing(self, common=None, heads=None): """Return the ancestors of heads that are not ancestors of common. More specifically, return a list of nodes N such that every N satisfies the following constraints: 1. N is an ancestor of some node in 'heads' 2. N is not an ancestor of any node in 'common' The list is sorted by revision number, meaning it is topologically sorted. 'heads' and 'common' are both lists of node IDs. If heads is not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" _common, missing = self.findcommonmissing(common, heads) return missing def nodesbetween(self, roots=None, heads=None): """Return a topological path from 'roots' to 'heads'. Return a tuple (nodes, outroots, outheads) where 'nodes' is a topologically sorted list of all nodes N that satisfy both of these constraints: 1. N is a descendant of some node in 'roots' 2. N is an ancestor of some node in 'heads' Every node is considered to be both a descendant and an ancestor of itself, so every reachable node in 'roots' and 'heads' will be included in 'nodes'. 'outroots' is the list of reachable nodes in 'roots', i.e., the subset of 'roots' that is returned in 'nodes'. Likewise, 'outheads' is the subset of 'heads' that is also in 'nodes'. 'roots' and 'heads' are both lists of node IDs. If 'roots' is unspecified, uses nullid as the only root. If 'heads' is unspecified, uses list of all of the revlog's heads.""" nonodes = ([], [], []) if roots is not None: roots = list(roots) if not roots: return nonodes lowestrev = min([self.rev(n) for n in roots]) else: roots = [nullid] # Everybody's a descendant of nullid lowestrev = nullrev if (lowestrev == nullrev) and (heads is None): # We want _all_ the nodes! return ([self.node(r) for r in self], [nullid], list(self.heads())) if heads is None: # All nodes are ancestors, so the latest ancestor is the last # node. highestrev = len(self) - 1 # Set ancestors to None to signal that every node is an ancestor. ancestors = None # Set heads to an empty dictionary for later discovery of heads heads = {} else: heads = list(heads) if not heads: return nonodes ancestors = set() # Turn heads into a dictionary so we can remove 'fake' heads. # Also, later we will be using it to filter out the heads we can't # find from roots. heads = dict.fromkeys(heads, False) # Start at the top and keep marking parents until we're done. nodestotag = set(heads) # Remember where the top was so we can use it as a limit later. highestrev = max([self.rev(n) for n in nodestotag]) while nodestotag: # grab a node to tag n = nodestotag.pop() # Never tag nullid if n == nullid: continue # A node's revision number represents its place in a # topologically sorted list of nodes. r = self.rev(n) if r >= lowestrev: if n not in ancestors: # If we are possibly a descendant of one of the roots # and we haven't already been marked as an ancestor ancestors.add(n) # Mark as ancestor # Add non-nullid parents to list of nodes to tag. nodestotag.update([p for p in self.parents(n) if p != nullid]) elif n in heads: # We've seen it before, is it a fake head? # So it is, real heads should not be the ancestors of # any other heads. heads.pop(n) if not ancestors: return nonodes # Now that we have our set of ancestors, we want to remove any # roots that are not ancestors. # If one of the roots was nullid, everything is included anyway. if lowestrev > nullrev: # But, since we weren't, let's recompute the lowest rev to not # include roots that aren't ancestors. # Filter out roots that aren't ancestors of heads roots = [n for n in roots if n in ancestors] # Recompute the lowest revision if roots: lowestrev = min([self.rev(n) for n in roots]) else: # No more roots? Return empty list return nonodes else: # We are descending from nullid, and don't need to care about # any other roots. lowestrev = nullrev roots = [nullid] # Transform our roots list into a set. descendants = set(roots) # Also, keep the original roots so we can filter out roots that aren't # 'real' roots (i.e. are descended from other roots). roots = descendants.copy() # Our topologically sorted list of output nodes. orderedout = [] # Don't start at nullid since we don't want nullid in our output list, # and if nullid shows up in descedents, empty parents will look like # they're descendants. for r in xrange(max(lowestrev, 0), highestrev + 1): n = self.node(r) isdescendant = False if lowestrev == nullrev: # Everybody is a descendant of nullid isdescendant = True elif n in descendants: # n is already a descendant isdescendant = True # This check only needs to be done here because all the roots # will start being marked is descendants before the loop. if n in roots: # If n was a root, check if it's a 'real' root. p = tuple(self.parents(n)) # If any of its parents are descendants, it's not a root. if (p[0] in descendants) or (p[1] in descendants): roots.remove(n) else: p = tuple(self.parents(n)) # A node is a descendant if either of its parents are # descendants. (We seeded the dependents list with the roots # up there, remember?) if (p[0] in descendants) or (p[1] in descendants): descendants.add(n) isdescendant = True if isdescendant and ((ancestors is None) or (n in ancestors)): # Only include nodes that are both descendants and ancestors. orderedout.append(n) if (ancestors is not None) and (n in heads): # We're trying to figure out which heads are reachable # from roots. # Mark this head as having been reached heads[n] = True elif ancestors is None: # Otherwise, we're trying to discover the heads. # Assume this is a head because if it isn't, the next step # will eventually remove it. heads[n] = True # But, obviously its parents aren't. for p in self.parents(n): heads.pop(p, None) heads = [n for n, flag in heads.iteritems() if flag] roots = list(roots) assert orderedout assert roots assert heads return (orderedout, roots, heads) def headrevs(self): count = len(self) if not count: return [nullrev] ishead = [1] * (count + 1) index = self.index for r in xrange(count): e = index[r] ishead[e[5]] = ishead[e[6]] = 0 return [r for r in xrange(count) if ishead[r]] def heads(self, start=None, stop=None): """return the list of all nodes that have no children if start is specified, only heads that are descendants of start will be returned if stop is specified, it will consider all the revs from stop as if they had no children """ if start is None and stop is None: if not len(self): return [nullid] return [self.node(r) for r in self.headrevs()] if start is None: start = nullid if stop is None: stop = [] stoprevs = set([self.rev(n) for n in stop]) startrev = self.rev(start) reachable = set((startrev,)) heads = set((startrev,)) parentrevs = self.parentrevs for r in xrange(startrev + 1, len(self)): for p in parentrevs(r): if p in reachable: if r not in stoprevs: reachable.add(r) heads.add(r) if p in heads and p not in stoprevs: heads.remove(p) return [self.node(r) for r in heads] def children(self, node): """find the children of a given node""" c = [] p = self.rev(node) for r in range(p + 1, len(self)): prevs = [pr for pr in self.parentrevs(r) if pr != nullrev] if prevs: for pr in prevs: if pr == p: c.append(self.node(r)) elif p == nullrev: c.append(self.node(r)) return c def descendant(self, start, end): if start == nullrev: return True for i in self.descendants(start): if i == end: return True elif i > end: break return False def ancestor(self, a, b): """calculate the least common ancestor of nodes a and b""" # fast path, check if it is a descendant a, b = self.rev(a), self.rev(b) start, end = sorted((a, b)) if self.descendant(start, end): return self.node(start) def parents(rev): return [p for p in self.parentrevs(rev) if p != nullrev] c = ancestor.ancestor(a, b, parents) if c is None: return nullid return self.node(c) def _match(self, id): if isinstance(id, (long, int)): # rev return self.node(id) if len(id) == 20: # possibly a binary node # odds of a binary node being all hex in ASCII are 1 in 10**25 try: node = id self.rev(node) # quick search the index return node except LookupError: pass # may be partial hex id try: # str(rev) rev = int(id) if str(rev) != id: raise ValueError if rev < 0: rev = len(self) + rev if rev < 0 or rev >= len(self): raise ValueError return self.node(rev) except (ValueError, OverflowError): pass if len(id) == 40: try: # a full hex nodeid? node = bin(id) self.rev(node) return node except (TypeError, LookupError): pass def _partialmatch(self, id): if id in self._pcache: return self._pcache[id] if len(id) < 40: try: # hex(node)[:...] l = len(id) // 2 # grab an even number of digits prefix = bin(id[:l * 2]) nl = [e[7] for e in self.index if e[7].startswith(prefix)] nl = [n for n in nl if hex(n).startswith(id)] if len(nl) > 0: if len(nl) == 1: self._pcache[id] = nl[0] return nl[0] raise LookupError(id, self.indexfile, _('ambiguous identifier')) return None except TypeError: pass def lookup(self, id): """locate a node based on: - revision number or str(revision number) - nodeid or subset of hex nodeid """ n = self._match(id) if n is not None: return n n = self._partialmatch(id) if n: return n raise LookupError(id, self.indexfile, _('no match found')) def cmp(self, node, text): """compare text with a given file revision returns True if text is different than what is stored. """ p1, p2 = self.parents(node) return hash(text, p1, p2) != node def _addchunk(self, offset, data): o, d = self._chunkcache # try to add to existing cache if o + len(d) == offset and len(d) + len(data) < _chunksize: self._chunkcache = o, d + data else: self._chunkcache = offset, data def _loadchunk(self, offset, length): if self._inline: df = self.opener(self.indexfile) else: df = self.opener(self.datafile) readahead = max(65536, length) df.seek(offset) d = df.read(readahead) df.close() self._addchunk(offset, d) if readahead > length: return util.buffer(d, 0, length) return d def _getchunk(self, offset, length): o, d = self._chunkcache l = len(d) # is it in the cache? cachestart = offset - o cacheend = cachestart + length if cachestart >= 0 and cacheend <= l: if cachestart == 0 and cacheend == l: return d # avoid a copy return util.buffer(d, cachestart, cacheend - cachestart) return self._loadchunk(offset, length) def _chunkraw(self, startrev, endrev): start = self.start(startrev) length = self.end(endrev) - start if self._inline: start += (startrev + 1) * self._io.size return self._getchunk(start, length) def _chunk(self, rev): return decompress(self._chunkraw(rev, rev)) def _chunkbase(self, rev): return self._chunk(rev) def _chunkclear(self): self._chunkcache = (0, '') def deltaparent(self, rev): """return deltaparent of the given revision""" base = self.index[rev][3] if base == rev: return nullrev elif self._generaldelta: return base else: return rev - 1 def revdiff(self, rev1, rev2): """return or calculate a delta between two revisions""" if rev1 != nullrev and self.deltaparent(rev2) == rev1: return str(self._chunk(rev2)) return mdiff.textdiff(self.revision(rev1), self.revision(rev2)) def revision(self, nodeorrev): """return an uncompressed revision of a given node or revision number. """ if isinstance(nodeorrev, int): rev = nodeorrev node = self.node(rev) else: node = nodeorrev rev = None cachedrev = None if node == nullid: return "" if self._cache: if self._cache[0] == node: return self._cache[2] cachedrev = self._cache[1] # look up what we need to read text = None if rev is None: rev = self.rev(node) # check rev flags if self.flags(rev) & ~REVIDX_KNOWN_FLAGS: raise RevlogError(_('incompatible revision flag %x') % (self.flags(rev) & ~REVIDX_KNOWN_FLAGS)) # build delta chain chain = [] index = self.index # for performance generaldelta = self._generaldelta iterrev = rev e = index[iterrev] while iterrev != e[3] and iterrev != cachedrev: chain.append(iterrev) if generaldelta: iterrev = e[3] else: iterrev -= 1 e = index[iterrev] chain.reverse() base = iterrev if iterrev == cachedrev: # cache hit text = self._cache[2] # drop cache to save memory self._cache = None self._chunkraw(base, rev) if text is None: text = str(self._chunkbase(base)) bins = [self._chunk(r) for r in chain] text = mdiff.patches(text, bins) text = self._checkhash(text, node, rev) self._cache = (node, rev, text) return text def _checkhash(self, text, node, rev): p1, p2 = self.parents(node) if node != hash(text, p1, p2): raise RevlogError(_("integrity check failed on %s:%d") % (self.indexfile, rev)) return text def checkinlinesize(self, tr, fp=None): if not self._inline or (self.start(-2) + self.length(-2)) < _maxinline: return trinfo = tr.find(self.indexfile) if trinfo is None: raise RevlogError(_("%s not found in the transaction") % self.indexfile) trindex = trinfo[2] dataoff = self.start(trindex) tr.add(self.datafile, dataoff) if fp: fp.flush() fp.close() df = self.opener(self.datafile, 'w') try: for r in self: df.write(self._chunkraw(r, r)) finally: df.close() fp = self.opener(self.indexfile, 'w', atomictemp=True) self.version &= ~(REVLOGNGINLINEDATA) self._inline = False for i in self: e = self._io.packentry(self.index[i], self.node, self.version, i) fp.write(e) # if we don't call close, the temp file will never replace the # real index fp.close() tr.replace(self.indexfile, trindex * self._io.size) self._chunkclear() def addrevision(self, text, transaction, link, p1, p2, cachedelta=None): """add a revision to the log text - the revision data to add transaction - the transaction object used for rollback link - the linkrev data to add p1, p2 - the parent nodeids of the revision cachedelta - an optional precomputed delta """ node = hash(text, p1, p2) if node in self.nodemap: return node dfh = None if not self._inline: dfh = self.opener(self.datafile, "a") ifh = self.opener(self.indexfile, "a+") try: return self._addrevision(node, text, transaction, link, p1, p2, cachedelta, ifh, dfh) finally: if dfh: dfh.close() ifh.close() def _addrevision(self, node, text, transaction, link, p1, p2, cachedelta, ifh, dfh): """internal function to add revisions to the log see addrevision for argument descriptions. invariants: - text is optional (can be None); if not set, cachedelta must be set. if both are set, they must correspond to eachother. """ btext = [text] def buildtext(): if btext[0] is not None: return btext[0] # flush any pending writes here so we can read it in revision if dfh: dfh.flush() ifh.flush() basetext = self.revision(self.node(cachedelta[0])) btext[0] = mdiff.patch(basetext, cachedelta[1]) chk = hash(btext[0], p1, p2) if chk != node: raise RevlogError(_("consistency error in delta")) return btext[0] def builddelta(rev): # can we use the cached delta? if cachedelta and cachedelta[0] == rev: delta = cachedelta[1] else: t = buildtext() ptext = self.revision(self.node(rev)) delta = mdiff.textdiff(ptext, t) data = compress(delta) l = len(data[1]) + len(data[0]) if basecache[0] == rev: chainbase = basecache[1] else: chainbase = self.chainbase(rev) dist = l + offset - self.start(chainbase) if self._generaldelta: base = rev else: base = chainbase return dist, l, data, base, chainbase curr = len(self) prev = curr - 1 base = chainbase = curr offset = self.end(prev) flags = 0 d = None basecache = self._basecache p1r, p2r = self.rev(p1), self.rev(p2) # should we try to build a delta? if prev != nullrev: if self._generaldelta: if p1r >= basecache[1]: d = builddelta(p1r) elif p2r >= basecache[1]: d = builddelta(p2r) else: d = builddelta(prev) else: d = builddelta(prev) dist, l, data, base, chainbase = d # full versions are inserted when the needed deltas # become comparable to the uncompressed text if text is None: textlen = mdiff.patchedsize(self.rawsize(cachedelta[0]), cachedelta[1]) else: textlen = len(text) if d is None or dist > textlen * 2: text = buildtext() data = compress(text) l = len(data[1]) + len(data[0]) base = chainbase = curr e = (offset_type(offset, flags), l, textlen, base, link, p1r, p2r, node) self.index.insert(-1, e) self.nodemap[node] = curr entry = self._io.packentry(e, self.node, self.version, curr) if not self._inline: transaction.add(self.datafile, offset) transaction.add(self.indexfile, curr * len(entry)) if data[0]: dfh.write(data[0]) dfh.write(data[1]) dfh.flush() ifh.write(entry) else: offset += curr * self._io.size transaction.add(self.indexfile, offset, curr) ifh.write(entry) ifh.write(data[0]) ifh.write(data[1]) self.checkinlinesize(transaction, ifh) if type(text) == str: # only accept immutable objects self._cache = (node, curr, text) self._basecache = (curr, chainbase) return node def group(self, nodelist, bundler, reorder=None): """Calculate a delta group, yielding a sequence of changegroup chunks (strings). Given a list of changeset revs, return a set of deltas and metadata corresponding to nodes. The first delta is first parent(nodelist[0]) -> nodelist[0], the receiver is guaranteed to have this parent as it has all history before these changesets. In the case firstparent is nullrev the changegroup starts with a full revision. """ # if we don't have any revisions touched by these changesets, bail if len(nodelist) == 0: yield bundler.close() return # for generaldelta revlogs, we linearize the revs; this will both be # much quicker and generate a much smaller bundle if (self._generaldelta and reorder is not False) or reorder: dag = dagutil.revlogdag(self) revs = set(self.rev(n) for n in nodelist) revs = dag.linearize(revs) else: revs = sorted([self.rev(n) for n in nodelist]) # add the parent of the first rev p = self.parentrevs(revs[0])[0] revs.insert(0, p) # build deltas for r in xrange(len(revs) - 1): prev, curr = revs[r], revs[r + 1] for c in bundler.revchunk(self, curr, prev): yield c yield bundler.close() def addgroup(self, bundle, linkmapper, transaction): """ add a delta group given a set of deltas, add them to the revision log. the first delta is against its parent, which should be in our log, the rest are against the previous delta. """ # track the base of the current delta log content = [] node = None r = len(self) end = 0 if r: end = self.end(r - 1) ifh = self.opener(self.indexfile, "a+") isize = r * self._io.size if self._inline: transaction.add(self.indexfile, end + isize, r) dfh = None else: transaction.add(self.indexfile, isize, r) transaction.add(self.datafile, end) dfh = self.opener(self.datafile, "a") try: # loop through our set of deltas chain = None while True: chunkdata = bundle.deltachunk(chain) if not chunkdata: break node = chunkdata['node'] p1 = chunkdata['p1'] p2 = chunkdata['p2'] cs = chunkdata['cs'] deltabase = chunkdata['deltabase'] delta = chunkdata['delta'] content.append(node) link = linkmapper(cs) if node in self.nodemap: # this can happen if two branches make the same change chain = node continue for p in (p1, p2): if not p in self.nodemap: raise LookupError(p, self.indexfile, _('unknown parent')) if deltabase not in self.nodemap: raise LookupError(deltabase, self.indexfile, _('unknown delta base')) baserev = self.rev(deltabase) chain = self._addrevision(node, None, transaction, link, p1, p2, (baserev, delta), ifh, dfh) if not dfh and not self._inline: # addrevision switched from inline to conventional # reopen the index ifh.close() dfh = self.opener(self.datafile, "a") ifh = self.opener(self.indexfile, "a") finally: if dfh: dfh.close() ifh.close() return content def strip(self, minlink, transaction): """truncate the revlog on the first revision with a linkrev >= minlink This function is called when we're stripping revision minlink and its descendants from the repository. We have to remove all revisions with linkrev >= minlink, because the equivalent changelog revisions will be renumbered after the strip. So we truncate the revlog on the first of these revisions, and trust that the caller has saved the revisions that shouldn't be removed and that it'll re-add them after this truncation. """ if len(self) == 0: return for rev in self: if self.index[rev][4] >= minlink: break else: return # first truncate the files on disk end = self.start(rev) if not self._inline: transaction.add(self.datafile, end) end = rev * self._io.size else: end += rev * self._io.size transaction.add(self.indexfile, end) # then reset internal state in memory to forget those revisions self._cache = None self._chunkclear() for x in xrange(rev, len(self)): del self.nodemap[self.node(x)] del self.index[rev:-1] def checksize(self): expected = 0 if len(self): expected = max(0, self.end(len(self) - 1)) try: f = self.opener(self.datafile) f.seek(0, 2) actual = f.tell() f.close() dd = actual - expected except IOError, inst: if inst.errno != errno.ENOENT: raise dd = 0 try: f = self.opener(self.indexfile) f.seek(0, 2) actual = f.tell() f.close() s = self._io.size i = max(0, actual // s) di = actual - (i * s) if self._inline: databytes = 0 for r in self: databytes += max(0, self.length(r)) dd = 0 di = actual - len(self) * s - databytes except IOError, inst: if inst.errno != errno.ENOENT: raise di = 0 return (dd, di) def files(self): res = [self.indexfile] if not self._inline: res.append(self.datafile) return res
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/mercurial-2.2.3-py2.7-linux-x86_64-ucs4.egg/mercurial/revlog.py
Python
gpl-3.0
44,332
<script type="text/javascript"> function verif(){ var patroi_hutsik = /^\s*$/; var pasahitza = $("#pasahitza").val(); var pasahitza2 = $("#pasahitza2").val(); <?php if ($edit_id) { // Ikaslea editatzen ari bagara pasahitzak hautazkoak dira... ?> // Erabiltzaileak pasahitza aldatu nahi badu pasahitzak bat datozela egiaztatu. if ((pasahitza && pasahitza2) && pasahitza !== pasahitza2) { alert("Pasahitzak ez datoz bat."); return false; } <?php } else { // ikasle berria bada pasahitzak derrigorrezkoak dira... ?> // Pasahitzen eremuak ez daudela hutsik egiaztatu. if (!pasahitza && !pasahitza2) { alert("Pasahitzak derrigorrezkoak dira."); return false; } // Pasahitzak bat datozela egiaztatu. if (pasahitza !== pasahitza2) { alert("Pasahitzak ez datoz bat."); return false; } <?php } ?> return (confirm ("Ikaslea gorde?")); } </script> <div class="navbar"> <div class="navbar-inner"> <div class="brand"><a href="<?php echo URL_BASE_ADMIN; ?>ikasleak">Ikasleak</a> > <?php if ($edit_id) { echo $ikaslea->izena . " " . $ikaslea->abizenak; } else { echo "Gehitu berria"; } ?></div> <div class="pull-right"> <a class="btn" href="<?php echo $url_base . $url_param; ?>"><i class="icon-circle-arrow-left"></i>&nbsp;Atzera</a> </div> </div> </div> <div class="formularioa"> <form id="f1" name="f1" method="post" action="<?php echo $url_base . "form" . $url_param; ?>" class="form-horizontal" enctype="multipart/form-data" onsubmit="javascript: return verif();"> <input type="hidden" name="gorde" value="BAI" /> <input type="hidden" name="edit_id" value="<?php echo $edit_id; ?>" /> <fieldset> <div class="control-group"> <label for="izena">Izena:</label> <input class="input-xxlarge" type="text" id="izena" name="izena" value="<?php echo testu_formatua_input ($ikaslea->izena); ?>" /> </div> <div class="control-group"> <label for="abizenak">Abizenak:</label> <input class="input-xxlarge" type="text" id="abizenak" name="abizenak" value="<?php echo testu_formatua_input ($ikaslea->abizenak); ?>" /> </div> <div class="control-group"> <label for="e_posta">e-posta:</label> <input class="input-xxlarge" type="text" id="e_posta" name="e_posta" value="<?php echo testu_formatua_input ($ikaslea->e_posta); ?>" /> </div> <div class="control-group"> <label for="pasahitza"><?php if ($edit_id) { echo "Aldatu pasahitza:"; } else { echo "Pasahitza: "; } ?></label> <input class="input-xxlarge" type="password" id="pasahitza" name="pasahitza" value="" /> </div> <div class="control-group"> <label for="pasahitza2">Berretsi pasahitza:</label> <input class="input-xxlarge" type="password" id="pasahitza2" name="pasahitza2" value="" /> </div> </fieldset> <div class="control-group text-center"> <button type="submit" class="btn"><i class="icon-edit"></i>&nbsp;Gorde</button> <button type="reset" class="btn"><i class="icon-repeat"></i>&nbsp;Berrezarri</button> </div> </form> </div>
iametza/ikuslang
admin/inc/bistak/ikasleak/ikaslea.php
PHP
gpl-3.0
3,337
// Copyright 2017 voidALPHA, Inc. // This file is part of the Haxxis video generation system and is provided // by voidALPHA in support of the Cyber Grand Challenge. // Haxxis 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. // Haxxis 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 // Haxxis. If not, see <http://www.gnu.org/licenses/>. using System; namespace Adapters.TraceAdapters.Instructions { [Serializable] public class ExceInstruction : Instruction { public int ExceptionCode { get; set; } public string ExceptionString { get; set; } } }
voidALPHA/cgc_viz
Assets/Adapters/TraceAdapters/Instructions/ExceInstruction.cs
C#
gpl-3.0
949
#!/usr/bin/php <? if (!function_exists('file_put_contents')) { function file_put_contents($filename, $data, $lockflag) { $f = @fopen($filename, 'w'); if (!$f) { return false; } else { $bytes = fwrite($f, $data); fclose($f); return $bytes; } } } function convertquotes($in) { $ret = ""; $qs= 0; for ($x=0;$x<strlen($in); $x++) { if ($in[$x] == '"') { if (!$qs) { $qs=1; } else { $qs=0; if ($x < strlen($in) && $in[$x+1] == '"') { $ret .= "\\"; continue; } } } $ret .= $in[$x]; } return $ret; } function swell_rc2cpp_dialog($fp) // returns array with ["data"] and optionally ["error"] { fseek($fp,0,SEEK_SET); $errstr=""; $retstr = ""; $retstr .= '#ifndef SWELL_DLG_SCALE_AUTOGEN' . "\n"; $retstr .= '#define SWELL_DLG_SCALE_AUTOGEN 1.7' . "\n"; $retstr .= '#endif' . "\n"; $retstr .= '#ifndef SWELL_DLG_FLAGS_AUTOGEN' . "\n"; $retstr .= '#define SWELL_DLG_FLAGS_AUTOGEN SWELL_DLG_WS_FLIPPED|SWELL_DLG_WS_NOAUTOSIZE' . "\n"; $retstr .= "#endif\n"; $retstr .= "\n"; $dlg_state=0; // 1 = before BEGIN, 2=after BEGIN $dlg_name=""; $dlg_size_w=0; $dlg_size_h=0; $dlg_title = ""; $dlg_styles = "SWELL_DLG_FLAGS_AUTOGEN"; $dlg_contents=""; $next_line=""; for (;;) { if ($next_line != "") { $x=$next_line; $next_line =""; } else if (!($x=fgets($fp))) break; $x = convertquotes($x); $y=trim($x); if ($dlg_state>=2) { $dlg_contents .= $y . "\n"; if ($y == "END") { if ($dlg_state==2) $dlg_styles.="|SWELL_DLG_WS_OPAQUE"; $retstr .= "#ifndef SET_$dlg_name" . "_SCALE\n"; $retstr .= "#define SET_$dlg_name" . "_SCALE SWELL_DLG_SCALE_AUTOGEN\n"; $retstr .= "#endif\n"; $retstr .= "#ifndef SET_$dlg_name" . "_STYLE\n"; $retstr .= "#define SET_$dlg_name" . "_STYLE $dlg_styles\n"; $retstr .= "#endif\n"; $retstr .= "SWELL_DEFINE_DIALOG_RESOURCE_BEGIN($dlg_name,SET_$dlg_name" . "_STYLE,\"$dlg_title\",$dlg_size_w,$dlg_size_h,SET_$dlg_name" . "_SCALE)\n"; $dlg_contents=str_replace("NOT WS_VISIBLE","SWELL_NOT_WS_VISIBLE",$dlg_contents); $dlg_contents=str_replace("NOT\nWS_VISIBLE","SWELL_NOT_WS_VISIBLE",$dlg_contents); $dlg_contents=str_replace("NOT \nWS_VISIBLE","SWELL_NOT_WS_VISIBLE",$dlg_contents); $retstr .= $dlg_contents; $retstr .= "SWELL_DEFINE_DIALOG_RESOURCE_END($dlg_name)\n\n\n"; $dlg_state=0; } else if (strlen($y)>1) $dlg_state=3; } else { $parms = explode(" ", $y); if (count($parms) > 0) { if ($dlg_state == 0) { // if (substr($parms[0],0,8) == "IDD_PREF") if (count($parms)>4 && ($parms[1] == 'DIALOGEX'||$parms[1] == 'DIALOG')) { $dlg_name=$parms[0]; $rdidx = 2; if ($parms[$rdidx] == 'DISCARDABLE') $rdidx++; while ($parms[$rdidx] == "" && $rdidx < count($parms)) $rdidx++; $rdidx += 2; $dlg_size_w = str_replace(",","",$parms[$rdidx++]); $dlg_size_h = str_replace(",","",$parms[$rdidx++]); if (count($parms) >= $rdidx && $dlg_size_w != "" && $dlg_size_h != "") { $dlg_title=""; $dlg_styles="SWELL_DLG_FLAGS_AUTOGEN"; $dlg_contents=""; $dlg_state=1; } else $errstr .= "WARNING: corrupted $dlg_name resource\n"; } } else if ($dlg_state == 1) { if ($parms[0] == "BEGIN") { $dlg_state=2; $dlg_contents = $y ."\n"; } else { if ($parms[0] == "CAPTION") { $dlg_title = str_replace("\"","",trim(substr($y,8))); } else if ($parms[0] == "STYLE" || $parms[0] == "EXSTYLE") { $rep=0; for (;;) { $next_line = fgets($fp,4096); if (!($next_line )) { $next_line=""; break; } if (substr($next_line,0,1)==" " || substr($next_line,0,1)=="\t") { $y .= " " . trim(convertquotes($next_line)); $rep++; $next_line=""; } else break; } if ($rep) $parms = explode(" ", $y); $opmode=0; $rdidx=1; while ($rdidx < count($parms)) { if ($parms[$rdidx] == '|') { $opmode=0; } else if ($parms[$rdidx] == 'NOT') { $opmode=1; } else if ($parms[$rdidx] == 'WS_CHILD') { if (!$opmode) $dlg_styles .= "|SWELL_DLG_WS_CHILD"; } else if ($parms[$rdidx] == 'WS_THICKFRAME') { if (!$opmode) $dlg_styles .= "|SWELL_DLG_WS_RESIZABLE"; } else if ($parms[$rdidx] == 'WS_EX_ACCEPTFILES') { if (!$opmode) $dlg_styles .= "|SWELL_DLG_WS_DROPTARGET"; } else $opmode=0; $rdidx++; } } } } } } } if ($dlg_state != 0) $errstr .= "WARNING: there may have been a truncated dialog resource ($dlg_name)\n"; $retstr .= "\n//EOF\n\n"; $rv = array(); $rv["data"] = $retstr; $rv["error"] = $errstr; return $rv; } function swell_rc2cpp_menu($fp) // returns array with ["data"] and optionally ["error"] { $retstr=""; $errstr=""; fseek($fp,0,SEEK_SET); $menu_symbol=""; $menu_depth=0; while (($x=fgets($fp))) { $x = convertquotes($x); $y=trim($x); if ($menu_symbol == "") { $parms = explode(" ", $y); $tok = "MENU"; if (count($parms) >= 2 && $parms[1] == $tok) { $menu_symbol = $parms[0]; $menu_depth=0; $retstr .= "SWELL_DEFINE_MENU_RESOURCE_BEGIN($menu_symbol)\n"; } } else { if ($y == "END") { $menu_depth-=1; if ($menu_depth == 0) { $retstr .= "SWELL_DEFINE_MENU_RESOURCE_END($menu_symbol)\n\n\n"; } if ($menu_depth < 1) $menu_symbol=""; } if ($menu_depth>0) { if (substr($y,-strlen(", HELP")) == ", HELP") { $x=substr(rtrim($x),0,-strlen(", HELP")) . "\n"; } $retstr .= $x; } if ($y == "BEGIN") $menu_depth+=1; } } $retstr .= "\n//EOF\n\n"; $rv = array(); $rv["data"] = $retstr; $rv["error"] = $errstr; return $rv; } if (count($argv)<2) die("usage: mac_resgen.php [--force] file.rc ...\n"); $x=1; $forcemode = 0; if ($argv[$x] == "--force") { $forcemode=1; $x++; } $lp = dirname(__FILE__); $proc=0; $skipped=0; $err=0; for (; $x < count($argv); $x ++) { $srcfn = $argv[$x]; if (!stristr($srcfn,".rc") || !($fp = @fopen($srcfn,"r"))) { $err++; echo "$srcfn: not valid or not found!\n"; continue; } echo "$srcfn: "; $ofnmenu = $srcfn . "_mac_menu"; $ofndlg = $srcfn . "_mac_dlg"; $res = swell_rc2cpp_dialog($fp); $res2 = swell_rc2cpp_menu($fp); fclose($fp); if ($res["error"] != "" || $res2["error"] != "") { $err++; echo "error"; if ($res["error"] != "") echo " dialog: " . $res["error"]; if ($res2["error"] != "") echo " menu: " . $res2["error"]; echo "\n"; continue; } $f=""; if ($forcemode || !file_exists($ofndlg) || file_get_contents($ofndlg) != $res["data"]) { $f .= "dlg updated"; if (!file_put_contents($ofndlg,$res["data"],LOCK_EX)) { echo "error writing $ofndlg\n"; $err++; } } if ($forcemode || !file_exists($ofnmenu) || file_get_contents($ofnmenu) != $res2["data"]) { if ($f != "") $f .= ", "; $f .= "menu updated"; if (!file_put_contents($ofnmenu,$res2["data"],LOCK_EX)) { echo "error writing $ofnmenu\n"; $err++; } } if ($f) echo "$f\n"; else echo "skipped\n"; if ($f != "") $proc++; else $skipped++; } echo "processed $proc, skipped $skipped, error $err\n"; ?>
austensatterlee/VOSIMSynth
libs/WDL/swell/mac_resgen.php
PHP
gpl-3.0
8,328
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PyQt5 import QtWidgets from view.analysis_widget import AnalysisWidget # noinspection PyPep8Naming class TemporalAnalysisWidget(AnalysisWidget): # noinspection PyArgumentList def __init__(self, mplCanvas): """ Construct the Temporal Analysis page in the main window. |br| A ``ScatterPlot.mplCanvas`` will be shown on this page. :param mplCanvas: The ``ScatterPlot.mplCanvas`` widget. """ super().__init__() upperLabel = QtWidgets.QLabel("Temporal Distribution &Graph:") upperLabel.setMargin(1) upperLabel.setBuddy(mplCanvas) lowerLabel = QtWidgets.QLabel("Temporal Correlation &Quotient:") lowerLabel.setMargin(1) lowerLabel.setBuddy(self.tableWidget) mainLayout = QtWidgets.QVBoxLayout() mainLayout.addWidget(upperLabel) mainLayout.addWidget(mplCanvas) mainLayout.addWidget(lowerLabel) mainLayout.addWidget(self.tableWidget) self.setLayout(mainLayout)
yuwen41200/biodiversity-analysis
src/view/temporal_analysis_widget.py
Python
gpl-3.0
1,068
/* ************************************************************************ */ /* Georgiev Lab (c) 2015 */ /* ************************************************************************ */ /* Department of Cybernetics */ /* Faculty of Applied Sciences */ /* University of West Bohemia in Pilsen */ /* ************************************************************************ */ /* */ /* This file is part of CeCe. */ /* */ /* CeCe 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. */ /* */ /* CeCe 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 CeCe. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* ************************************************************************ */ #pragma once /* ************************************************************************ */ // CeCe #include "cece/core/Factory.hpp" #include "cece/init/Initializer.hpp" /* ************************************************************************ */ namespace cece { namespace init { /* ************************************************************************ */ /** * @brief Initializer factory interface. */ using Factory = Factory<Initializer>; /* ************************************************************************ */ /** * @brief Initializer factory for specific module. * * @tparam InitializerType */ template<typename InitializerType> using FactoryTyped = FactoryTyped<core::Factory, InitializerType, Initializer>; /* ************************************************************************ */ /** * @brief Initializer factory with callable backend. * * @tparam Callable */ template<typename Callable> using FactoryCallable = FactoryCallable<core::Factory, Callable, Initializer>; /* ************************************************************************ */ /** * @brief Make callable module factory. * * @param callable Callable object. * * @return Callable module factory. */ template<typename Callable> FactoryCallable<Callable> makeCallableFactory(Callable callable) noexcept { return FactoryCallable<Callable>{std::move(callable)}; } /* ************************************************************************ */ } } /* ************************************************************************ */
GustavoPB/CeCe
cece/init/Factory.hpp
C++
gpl-3.0
3,446
# Copyright 2008 Dan Smith <dsmith@danplanet.com> # Copyright 2012 Tom Hayward <tom@tomh.us> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import tempfile import urllib from glob import glob import shutil import time import gtk import gobject gobject.threads_init() if __name__ == "__main__": import sys sys.path.insert(0, "..") from chirpui import inputdialog, common try: import serial except ImportError,e: common.log_exception() common.show_error("\nThe Pyserial module is not installed!") from chirp import platform, generic_xml, generic_csv, directory, util from chirp import ic9x, kenwood_live, idrp, vx7, vx5, vx6 from chirp import CHIRP_VERSION, chirp_common, detect, errors from chirp import icf, ic9x_icf from chirpui import editorset, clone, miscwidgets, config, reporting, fips from chirpui import bandplans CONF = config.get() KEEP_RECENT = 8 RB_BANDS = { "--All--" : 0, "10 meters (29MHz)" : 29, "6 meters (54MHz)" : 5, "2 meters (144MHz)" : 14, "1.25 meters (220MHz)" : 22, "70 centimeters (440MHz)" : 4, "33 centimeters (900MHz)" : 9, "23 centimeters (1.2GHz)" : 12, } def key_bands(band): if band.startswith("-"): return -1 amount, units, mhz = band.split(" ") scale = units == "meters" and 100 or 1 return 100000 - (float(amount) * scale) class ModifiedError(Exception): pass class ChirpMain(gtk.Window): def get_current_editorset(self): page = self.tabs.get_current_page() if page is not None: return self.tabs.get_nth_page(page) else: return None def ev_tab_switched(self, pagenum=None): def set_action_sensitive(action, sensitive): self.menu_ag.get_action(action).set_sensitive(sensitive) if pagenum is not None: eset = self.tabs.get_nth_page(pagenum) else: eset = self.get_current_editorset() upload_sens = bool(eset and isinstance(eset.radio, chirp_common.CloneModeRadio)) if not eset or isinstance(eset.radio, chirp_common.LiveRadio): save_sens = False elif isinstance(eset.radio, chirp_common.NetworkSourceRadio): save_sens = False else: save_sens = True for i in ["import", "importsrc", "stock"]: set_action_sensitive(i, eset is not None and not eset.get_read_only()) for i in ["save", "saveas"]: set_action_sensitive(i, save_sens) for i in ["upload"]: set_action_sensitive(i, upload_sens) for i in ["cancelq"]: set_action_sensitive(i, eset is not None and not save_sens) for i in ["export", "close", "columns", "irbook", "irfinder", "move_up", "move_dn", "exchange", "iradioreference", "cut", "copy", "paste", "delete", "viewdeveloper"]: set_action_sensitive(i, eset is not None) def ev_status(self, editorset, msg): self.sb_radio.pop(0) self.sb_radio.push(0, msg) def ev_usermsg(self, editorset, msg): self.sb_general.pop(0) self.sb_general.push(0, msg) def ev_editor_selected(self, editorset, editortype): mappings = { "memedit" : ["view", "edit"], } for _editortype, actions in mappings.items(): for _action in actions: action = self.menu_ag.get_action(_action) action.set_sensitive(editortype.startswith(_editortype)) def _connect_editorset(self, eset): eset.connect("want-close", self.do_close) eset.connect("status", self.ev_status) eset.connect("usermsg", self.ev_usermsg) eset.connect("editor-selected", self.ev_editor_selected) def do_diff_radio(self): if self.tabs.get_n_pages() < 2: common.show_error("Diff tabs requires at least two open tabs!") return esets = [] for i in range(0, self.tabs.get_n_pages()): esets.append(self.tabs.get_nth_page(i)) d = gtk.Dialog(title="Diff Radios", buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), parent=self) choices = [] for eset in esets: choices.append("%s %s (%s)" % (eset.rthread.radio.VENDOR, eset.rthread.radio.MODEL, eset.filename)) choice_a = miscwidgets.make_choice(choices, False, choices[0]) choice_a.show() chan_a = gtk.SpinButton() chan_a.get_adjustment().set_all(1, -1, 999, 1, 10, 0) chan_a.show() hbox = gtk.HBox(False, 3) hbox.pack_start(choice_a, 1, 1, 1) hbox.pack_start(chan_a, 0, 0, 0) hbox.show() d.vbox.pack_start(hbox, 0, 0, 0) choice_b = miscwidgets.make_choice(choices, False, choices[1]) choice_b.show() chan_b = gtk.SpinButton() chan_b.get_adjustment().set_all(1, -1, 999, 1, 10, 0) chan_b.show() hbox = gtk.HBox(False, 3) hbox.pack_start(choice_b, 1, 1, 1) hbox.pack_start(chan_b, 0, 0, 0) hbox.show() d.vbox.pack_start(hbox, 0, 0, 0) r = d.run() sel_a = choice_a.get_active_text() sel_chan_a = chan_a.get_value() sel_b = choice_b.get_active_text() sel_chan_b = chan_b.get_value() d.destroy() if r == gtk.RESPONSE_CANCEL: return if sel_a == sel_b: common.show_error("Can't diff the same tab!") return print "Selected %s@%i and %s@%i" % (sel_a, sel_chan_a, sel_b, sel_chan_b) eset_a = esets[choices.index(sel_a)] eset_b = esets[choices.index(sel_b)] def _show_diff(mem_b, mem_a): # Step 3: Show the diff diff = common.simple_diff(mem_a, mem_b) common.show_diff_blob("Differences", diff) def _get_mem_b(mem_a): # Step 2: Get memory b job = common.RadioJob(_show_diff, "get_raw_memory", int(sel_chan_b)) job.set_cb_args(mem_a) eset_b.rthread.submit(job) if sel_chan_a >= 0 and sel_chan_b >= 0: # Diff numbered memory # Step 1: Get memory a job = common.RadioJob(_get_mem_b, "get_raw_memory", int(sel_chan_a)) eset_a.rthread.submit(job) elif isinstance(eset_a.rthread.radio, chirp_common.CloneModeRadio) and\ isinstance(eset_b.rthread.radio, chirp_common.CloneModeRadio): # Diff whole (can do this without a job, since both are clone-mode) a = util.hexprint(eset_a.rthread.radio._mmap.get_packed()) b = util.hexprint(eset_b.rthread.radio._mmap.get_packed()) common.show_diff_blob("Differences", common.simple_diff(a, b)) else: common.show_error("Cannot diff whole live-mode radios!") def do_new(self): eset = editorset.EditorSet(_("Untitled") + ".csv", self) self._connect_editorset(eset) eset.prime() eset.show() tab = self.tabs.append_page(eset, eset.get_tab_label()) self.tabs.set_current_page(tab) def _do_manual_select(self, filename): radiolist = {} for drv, radio in directory.DRV_TO_RADIO.items(): if not issubclass(radio, chirp_common.CloneModeRadio): continue radiolist["%s %s" % (radio.VENDOR, radio.MODEL)] = drv lab = gtk.Label("""<b><big>Unable to detect model!</big></b> If you think that it is valid, you can select a radio model below to force an open attempt. If selecting the model manually works, please file a bug on the website and attach your image. If selecting the model does not work, it is likely that you are trying to open some other type of file. """) lab.set_justify(gtk.JUSTIFY_FILL) lab.set_line_wrap(True) lab.set_use_markup(True) lab.show() choice = miscwidgets.make_choice(sorted(radiolist.keys()), False, sorted(radiolist.keys())[0]) d = gtk.Dialog(title="Detection Failed", buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) d.vbox.pack_start(lab, 0, 0, 0) d.vbox.pack_start(choice, 0, 0, 0) d.vbox.set_spacing(5) choice.show() d.set_default_size(400, 200) #d.set_resizable(False) r = d.run() d.destroy() if r != gtk.RESPONSE_OK: return try: rc = directory.DRV_TO_RADIO[radiolist[choice.get_active_text()]] return rc(filename) except: return def do_open(self, fname=None, tempname=None): if not fname: types = [(_("CHIRP Radio Images") + " (*.img)", "*.img"), (_("CHIRP Files") + " (*.chirp)", "*.chirp"), (_("CSV Files") + " (*.csv)", "*.csv"), (_("EVE Files (VX5)") + " (*.eve)", "*.eve"), (_("ICF Files") + " (*.icf)", "*.icf"), (_("VX5 Commander Files") + " (*.vx5)", "*.vx5"), (_("VX6 Commander Files") + " (*.vx6)", "*.vx6"), (_("VX7 Commander Files") + " (*.vx7)", "*.vx7"), ] fname = platform.get_platform().gui_open_file(types=types) if not fname: return self.record_recent_file(fname) if icf.is_icf_file(fname): a = common.ask_yesno_question(\ _("ICF files cannot be edited, only displayed or imported " "into another file. Open in read-only mode?"), self) if not a: return read_only = True else: read_only = False if icf.is_9x_icf(fname): # We have to actually instantiate the IC9xICFRadio to get its # sub-devices radio = ic9x_icf.IC9xICFRadio(fname) else: try: radio = directory.get_radio_by_image(fname) except errors.ImageDetectFailed: radio = self._do_manual_select(fname) if not radio: return print "Manually selected %s" % radio except Exception, e: common.log_exception() common.show_error(os.path.basename(fname) + ": " + str(e)) return first_tab = False try: eset = editorset.EditorSet(radio, self, filename=fname, tempname=tempname) except Exception, e: common.log_exception() common.show_error( _("There was an error opening {fname}: {error}").format( fname=fname, error=e)) return eset.set_read_only(read_only) self._connect_editorset(eset) eset.show() self.tabs.append_page(eset, eset.get_tab_label()) if hasattr(eset.rthread.radio, "errors") and \ eset.rthread.radio.errors: msg = _("{num} errors during open:").format( num=len(eset.rthread.radio.errors)) common.show_error_text(msg, "\r\n".join(eset.rthread.radio.errors)) def do_live_warning(self, radio): d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) d.set_markup("<big><b>" + _("Note:") + "</b></big>") msg = _("The {vendor} {model} operates in <b>live mode</b>. " "This means that any changes you make are immediately sent " "to the radio. Because of this, you cannot perform the " "<u>Save</u> or <u>Upload</u> operations. If you wish to " "edit the contents offline, please <u>Export</u> to a CSV " "file, using the <b>File menu</b>.").format(vendor=radio.VENDOR, model=radio.MODEL) d.format_secondary_markup(msg) again = gtk.CheckButton(_("Don't show this again")) again.show() d.vbox.pack_start(again, 0, 0, 0) d.run() CONF.set_bool("live_mode", again.get_active(), "noconfirm") d.destroy() def do_open_live(self, radio, tempname=None, read_only=False): eset = editorset.EditorSet(radio, self, tempname=tempname) eset.connect("want-close", self.do_close) eset.connect("status", self.ev_status) eset.set_read_only(read_only) eset.show() self.tabs.append_page(eset, eset.get_tab_label()) if isinstance(radio, chirp_common.LiveRadio): reporting.report_model_usage(radio, "live", True) if not CONF.get_bool("live_mode", "noconfirm"): self.do_live_warning(radio) def do_save(self, eset=None): if not eset: eset = self.get_current_editorset() # For usability, allow Ctrl-S to short-circuit to Save-As if # we are working on a yet-to-be-saved image if not os.path.exists(eset.filename): return self.do_saveas() eset.save() def do_saveas(self): eset = self.get_current_editorset() label = _("{vendor} {model} image file").format(\ vendor=eset.radio.VENDOR, model=eset.radio.MODEL) types = [(label + " (*.%s)" % eset.radio.FILE_EXTENSION, eset.radio.FILE_EXTENSION)] if isinstance(eset.radio, vx7.VX7Radio): types += [(_("VX7 Commander") + " (*.vx7)", "vx7")] elif isinstance(eset.radio, vx6.VX6Radio): types += [(_("VX6 Commander") + " (*.vx6)", "vx6")] elif isinstance(eset.radio, vx5.VX5Radio): types += [(_("EVE") + " (*.eve)", "eve")] types += [(_("VX5 Commander") + " (*.vx5)", "vx5")] while True: fname = platform.get_platform().gui_save_file(types=types) if not fname: return if os.path.exists(fname): dlg = inputdialog.OverwriteDialog(fname) owrite = dlg.run() dlg.destroy() if owrite == gtk.RESPONSE_OK: break else: break try: eset.save(fname) except Exception,e: d = inputdialog.ExceptionDialog(e) d.run() d.destroy() def cb_clonein(self, radio, emsg=None): radio.pipe.close() reporting.report_model_usage(radio, "download", bool(emsg)) if not emsg: self.do_open_live(radio, tempname="(" + _("Untitled") + ")") else: d = inputdialog.ExceptionDialog(emsg) d.run() d.destroy() def cb_cloneout(self, radio, emsg= None): radio.pipe.close() reporting.report_model_usage(radio, "upload", True) if emsg: d = inputdialog.ExceptionDialog(emsg) d.run() d.destroy() def _get_recent_list(self): recent = [] for i in range(0, KEEP_RECENT): fn = CONF.get("recent%i" % i, "state") if fn: recent.append(fn) return recent def _set_recent_list(self, recent): for fn in recent: CONF.set("recent%i" % recent.index(fn), fn, "state") def update_recent_files(self): i = 0 for fname in self._get_recent_list(): action_name = "recent%i" % i path = "/MenuBar/file/recent" old_action = self.menu_ag.get_action(action_name) if old_action: self.menu_ag.remove_action(old_action) file_basename = os.path.basename(fname).replace("_", "__") action = gtk.Action(action_name, "_%i. %s" % (i+1, file_basename), _("Open recent file {name}").format(name=fname), "") action.connect("activate", lambda a,f: self.do_open(f), fname) mid = self.menu_uim.new_merge_id() self.menu_uim.add_ui(mid, path, action_name, action_name, gtk.UI_MANAGER_MENUITEM, False) self.menu_ag.add_action(action) i += 1 def record_recent_file(self, filename): recent_files = self._get_recent_list() if filename not in recent_files: if len(recent_files) == KEEP_RECENT: del recent_files[-1] recent_files.insert(0, filename) self._set_recent_list(recent_files) self.update_recent_files() def import_stock_config(self, action, config): eset = self.get_current_editorset() count = eset.do_import(config) def copy_shipped_stock_configs(self, stock_dir): execpath = platform.get_platform().executable_path() basepath = os.path.abspath(os.path.join(execpath, "stock_configs")) if not os.path.exists(basepath): basepath = "/usr/share/chirp/stock_configs" files = glob(os.path.join(basepath, "*.csv")) for fn in files: if os.path.exists(os.path.join(stock_dir, os.path.basename(fn))): print "Skipping existing stock config" continue try: shutil.copy(fn, stock_dir) print "Copying %s -> %s" % (fn, stock_dir) except Exception, e: print "ERROR: Unable to copy %s to %s: %s" % (fn, stock_dir, e) return False return True def update_stock_configs(self): stock_dir = platform.get_platform().config_file("stock_configs") if not os.path.isdir(stock_dir): try: os.mkdir(stock_dir) except Exception, e: print "ERROR: Unable to create directory: %s" % stock_dir return if not self.copy_shipped_stock_configs(stock_dir): return def _do_import_action(config): name = os.path.splitext(os.path.basename(config))[0] action_name = "stock-%i" % configs.index(config) path = "/MenuBar/radio/stock" action = gtk.Action(action_name, name, _("Import stock " "configuration {name}").format(name=name), "") action.connect("activate", self.import_stock_config, config) mid = self.menu_uim.new_merge_id() mid = self.menu_uim.add_ui(mid, path, action_name, action_name, gtk.UI_MANAGER_MENUITEM, False) self.menu_ag.add_action(action) def _do_open_action(config): name = os.path.splitext(os.path.basename(config))[0] action_name = "openstock-%i" % configs.index(config) path = "/MenuBar/file/openstock" action = gtk.Action(action_name, name, _("Open stock " "configuration {name}").format(name=name), "") action.connect("activate", lambda a,c: self.do_open(c), config) mid = self.menu_uim.new_merge_id() mid = self.menu_uim.add_ui(mid, path, action_name, action_name, gtk.UI_MANAGER_MENUITEM, False) self.menu_ag.add_action(action) configs = glob(os.path.join(stock_dir, "*.csv")) for config in configs: _do_import_action(config) _do_open_action(config) def _confirm_experimental(self, rclass): sql_key = "warn_experimental_%s" % directory.radio_class_id(rclass) if CONF.is_defined(sql_key, "state") and \ not CONF.get_bool(sql_key, "state"): return True title = _("Proceed with experimental driver?") text = rclass.get_prompts().experimental msg = _("This radio's driver is experimental. " "Do you want to proceed?") resp, squelch = common.show_warning(msg, text, title=title, buttons=gtk.BUTTONS_YES_NO, can_squelch=True) if resp == gtk.RESPONSE_YES: CONF.set_bool(sql_key, not squelch, "state") return resp == gtk.RESPONSE_YES def _show_instructions(self, radio, message): if message is None: return if CONF.get_bool("clone_instructions", "noconfirm"): return d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) d.set_markup("<big><b>" + _("{name} Instructions").format( name=radio.get_name()) + "</b></big>") msg = _("{instructions}").format(instructions=message) d.format_secondary_markup(msg) again = gtk.CheckButton(_("Don't show instructions for any radio again")) again.show() d.vbox.pack_start(again, 0, 0, 0) h_button_box = d.vbox.get_children()[2] try: ok_button = h_button_box.get_children()[0] ok_button.grab_default() ok_button.grab_focus() except AttributeError: # don't grab focus on GTK+ 2.0 pass d.run() d.destroy() CONF.set_bool("clone_instructions", again.get_active(), "noconfirm") def do_download(self, port=None, rtype=None): d = clone.CloneSettingsDialog(parent=self) settings = d.run() d.destroy() if not settings: return rclass = settings.radio_class if issubclass(rclass, chirp_common.ExperimentalRadio) and \ not self._confirm_experimental(rclass): # User does not want to proceed with experimental driver return self._show_instructions(rclass, rclass.get_prompts().pre_download) print "User selected %s %s on port %s" % (rclass.VENDOR, rclass.MODEL, settings.port) try: ser = serial.Serial(port=settings.port, baudrate=rclass.BAUD_RATE, rtscts=rclass.HARDWARE_FLOW, timeout=0.25) ser.flushInput() except serial.SerialException, e: d = inputdialog.ExceptionDialog(e) d.run() d.destroy() return radio = settings.radio_class(ser) fn = tempfile.mktemp() if isinstance(radio, chirp_common.CloneModeRadio): ct = clone.CloneThread(radio, "in", cb=self.cb_clonein, parent=self) ct.start() else: self.do_open_live(radio) def do_upload(self, port=None, rtype=None): eset = self.get_current_editorset() radio = eset.radio settings = clone.CloneSettings() settings.radio_class = radio.__class__ d = clone.CloneSettingsDialog(settings, parent=self) settings = d.run() d.destroy() if not settings: return if isinstance(radio, chirp_common.ExperimentalRadio) and \ not self._confirm_experimental(radio.__class__): # User does not want to proceed with experimental driver return try: ser = serial.Serial(port=settings.port, baudrate=radio.BAUD_RATE, rtscts=radio.HARDWARE_FLOW, timeout=0.25) ser.flushInput() except serial.SerialException, e: d = inputdialog.ExceptionDialog(e) d.run() d.destroy() return self._show_instructions(radio, radio.get_prompts().pre_upload) radio.set_pipe(ser) ct = clone.CloneThread(radio, "out", cb=self.cb_cloneout, parent=self) ct.start() def do_close(self, tab_child=None): if tab_child: eset = tab_child else: eset = self.get_current_editorset() if not eset: return False if eset.is_modified(): dlg = miscwidgets.YesNoDialog(title=_("Save Changes?"), parent=self, buttons=(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO, gtk.RESPONSE_NO, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) dlg.set_text(_("File is modified, save changes before closing?")) res = dlg.run() dlg.destroy() if res == gtk.RESPONSE_YES: self.do_save(eset) elif res == gtk.RESPONSE_CANCEL: raise ModifiedError() eset.rthread.stop() eset.rthread.join() eset.prepare_close() if eset.radio.pipe: eset.radio.pipe.close() if isinstance(eset.radio, chirp_common.LiveRadio): action = self.menu_ag.get_action("openlive") if action: action.set_sensitive(True) page = self.tabs.page_num(eset) if page is not None: self.tabs.remove_page(page) return True def do_import(self): types = [(_("CHIRP Files") + " (*.chirp)", "*.chirp"), (_("CHIRP Radio Images") + " (*.img)", "*.img"), (_("CSV Files") + " (*.csv)", "*.csv"), (_("EVE Files (VX5)") + " (*.eve)", "*.eve"), (_("ICF Files") + " (*.icf)", "*.icf"), (_("Kenwood HMK Files") + " (*.hmk)", "*.hmk"), (_("Kenwood ITM Files") + " (*.itm)", "*.itm"), (_("Travel Plus Files") + " (*.tpe)", "*.tpe"), (_("VX5 Commander Files") + " (*.vx5)", "*.vx5"), (_("VX6 Commander Files") + " (*.vx6)", "*.vx6"), (_("VX7 Commander Files") + " (*.vx7)", "*.vx7")] filen = platform.get_platform().gui_open_file(types=types) if not filen: return eset = self.get_current_editorset() count = eset.do_import(filen) reporting.report_model_usage(eset.rthread.radio, "import", count > 0) def do_repeaterbook_prompt(self): if not CONF.get_bool("has_seen_credit", "repeaterbook"): d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) d.set_markup("<big><big><b>RepeaterBook</b></big>\r\n" + \ "<i>North American Repeater Directory</i></big>") d.format_secondary_markup("For more information about this " +\ "free service, please go to\r\n" +\ "http://www.repeaterbook.com") d.run() d.destroy() CONF.set_bool("has_seen_credit", True, "repeaterbook") default_state = "Oregon" default_county = "--All--" default_band = "--All--" try: try: code = int(CONF.get("state", "repeaterbook")) except: code = CONF.get("state", "repeaterbook") for k,v in fips.FIPS_STATES.items(): if code == v: default_state = k break code = CONF.get("county", "repeaterbook") for k,v in fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].items(): if code == v: default_county = k break code = int(CONF.get("band", "repeaterbook")) for k,v in RB_BANDS.items(): if code == v: default_band = k break except: pass state = miscwidgets.make_choice(sorted(fips.FIPS_STATES.keys()), False, default_state) county = miscwidgets.make_choice(sorted(fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].keys()), False, default_county) band = miscwidgets.make_choice(sorted(RB_BANDS.keys(), key=key_bands), False, default_band) def _changed(box, county): state = fips.FIPS_STATES[box.get_active_text()] county.get_model().clear() for fips_county in sorted(fips.FIPS_COUNTIES[state].keys()): county.append_text(fips_county) county.set_active(0) state.connect("changed", _changed, county) d = inputdialog.FieldDialog(title=_("RepeaterBook Query"), parent=self) d.add_field("State", state) d.add_field("County", county) d.add_field("Band", band) r = d.run() d.destroy() if r != gtk.RESPONSE_OK: return False code = fips.FIPS_STATES[state.get_active_text()] county_id = fips.FIPS_COUNTIES[code][county.get_active_text()] freq = RB_BANDS[band.get_active_text()] CONF.set("state", str(code), "repeaterbook") CONF.set("county", str(county_id), "repeaterbook") CONF.set("band", str(freq), "repeaterbook") return True def do_repeaterbook(self, do_import): self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) if not self.do_repeaterbook_prompt(): self.window.set_cursor(None) return try: code = "%02i" % int(CONF.get("state", "repeaterbook")) except: try: code = CONF.get("state", "repeaterbook") except: code = '41' # Oregon default try: county = CONF.get("county", "repeaterbook") except: county = '%' # --All-- default try: band = int(CONF.get("band", "repeaterbook")) except: band = 14 # 2m default query = "http://www.repeaterbook.com/repeaters/downloads/chirp.php?" + \ "func=default&state_id=%s&band=%s&freq=%%&band6=%%&loc=%%" + \ "&county_id=%s&status_id=%%&features=%%&coverage=%%&use=%%" query = query % (code, band and band or "%%", county and county or "%%") # Do this in case the import process is going to take a while # to make sure we process events leading up to this gtk.gdk.window_process_all_updates() while gtk.events_pending(): gtk.main_iteration(False) fn = tempfile.mktemp(".csv") filename, headers = urllib.urlretrieve(query, fn) if not os.path.exists(filename): print "Failed, headers were:" print str(headers) common.show_error(_("RepeaterBook query failed")) self.window.set_cursor(None) return class RBRadio(generic_csv.CSVRadio, chirp_common.NetworkSourceRadio): VENDOR = "RepeaterBook" MODEL = "" try: # Validate CSV radio = RBRadio(filename) if radio.errors: reporting.report_misc_error("repeaterbook", ("query=%s\n" % query) + ("\n") + ("\n".join(radio.errors))) except errors.InvalidDataError, e: common.show_error(str(e)) self.window.set_cursor(None) return except Exception, e: common.log_exception() reporting.report_model_usage(radio, "import", True) self.window.set_cursor(None) if do_import: eset = self.get_current_editorset() count = eset.do_import(filename) else: self.do_open_live(radio, read_only=True) def do_przemienniki_prompt(self): d = inputdialog.FieldDialog(title='przemienniki.net query', parent=self) fields = { "Country": (miscwidgets.make_choice(['by', 'cz', 'de', 'lt', 'pl', 'sk', 'uk'], False), lambda x: str(x.get_active_text())), "Band": (miscwidgets.make_choice(['10m', '4m', '6m', '2m', '70cm', '23cm', '13cm', '3cm'], False, '2m'), lambda x: str(x.get_active_text())), "Mode": (miscwidgets.make_choice(['fm', 'dv'], False), lambda x: str(x.get_active_text())), "Only Working": (miscwidgets.make_choice(['', 'yes'], False), lambda x: str(x.get_active_text())), "Latitude": (gtk.Entry(), lambda x: float(x.get_text())), "Longitude": (gtk.Entry(), lambda x: float(x.get_text())), "Range": (gtk.Entry(), lambda x: int(x.get_text())), } for name in sorted(fields.keys()): value, fn = fields[name] d.add_field(name, value) while d.run() == gtk.RESPONSE_OK: query = "http://przemienniki.net/export/chirp.csv?" args = [] for name, (value, fn) in fields.items(): if isinstance(value, gtk.Entry): contents = value.get_text() else: contents = value.get_active_text() if contents: try: _value = fn(value) except ValueError: common.show_error(_("Invalid value for %s") % name) query = None continue args.append("=".join((name.replace(" ", "").lower(), contents))) query += "&".join(args) print query d.destroy() return query d.destroy() return query def do_przemienniki(self, do_import): url = self.do_przemienniki_prompt() if not url: return fn = tempfile.mktemp(".csv") filename, headers = urllib.urlretrieve(url, fn) if not os.path.exists(filename): print "Failed, headers were:" print str(headers) common.show_error(_("Query failed")) return class PRRadio(generic_csv.CSVRadio, chirp_common.NetworkSourceRadio): VENDOR = "przemienniki.net" MODEL = "" try: radio = PRRadio(filename) except Exception, e: common.show_error(str(e)) return if do_import: eset = self.get_current_editorset() count = eset.do_import(filename) else: self.do_open_live(radio, read_only=True) def do_rfinder_prompt(self): fields = {"1Email" : (gtk.Entry(), lambda x: "@" in x), "2Password" : (gtk.Entry(), lambda x: x), "3Latitude" : (gtk.Entry(), lambda x: float(x) < 90 and \ float(x) > -90), "4Longitude": (gtk.Entry(), lambda x: float(x) < 180 and \ float(x) > -180), "5Range_in_Miles": (gtk.Entry(), lambda x: int(x) > 0 and int(x) < 5000), } d = inputdialog.FieldDialog(title="RFinder Login", parent=self) for k in sorted(fields.keys()): d.add_field(k[1:].replace("_", " "), fields[k][0]) fields[k][0].set_text(CONF.get(k[1:], "rfinder") or "") fields[k][0].set_visibility(k != "2Password") while d.run() == gtk.RESPONSE_OK: valid = True for k in sorted(fields.keys()): widget, validator = fields[k] try: if validator(widget.get_text()): CONF.set(k[1:], widget.get_text(), "rfinder") continue except Exception: pass common.show_error("Invalid value for %s" % k[1:]) valid = False break if valid: d.destroy() return True d.destroy() return False def do_rfinder(self, do_import): self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) if not self.do_rfinder_prompt(): self.window.set_cursor(None) return lat = CONF.get_float("Latitude", "rfinder") lon = CONF.get_float("Longitude", "rfinder") passwd = CONF.get("Password", "rfinder") email = CONF.get("Email", "rfinder") miles = CONF.get_int("Range_in_Miles", "rfinder") # Do this in case the import process is going to take a while # to make sure we process events leading up to this gtk.gdk.window_process_all_updates() while gtk.events_pending(): gtk.main_iteration(False) if do_import: eset = self.get_current_editorset() count = eset.do_import("rfinder://%s/%s/%f/%f/%i" % (email, passwd, lat, lon, miles)) else: from chirp import rfinder radio = rfinder.RFinderRadio(None) radio.set_params((lat, lon), miles, email, passwd) self.do_open_live(radio, read_only=True) self.window.set_cursor(None) def do_radioreference_prompt(self): fields = {"1Username" : (gtk.Entry(), lambda x: x), "2Password" : (gtk.Entry(), lambda x: x), "3Zipcode" : (gtk.Entry(), lambda x: x), } d = inputdialog.FieldDialog(title=_("RadioReference.com Query"), parent=self) for k in sorted(fields.keys()): d.add_field(k[1:], fields[k][0]) fields[k][0].set_text(CONF.get(k[1:], "radioreference") or "") fields[k][0].set_visibility(k != "2Password") while d.run() == gtk.RESPONSE_OK: valid = True for k in sorted(fields.keys()): widget, validator = fields[k] try: if validator(widget.get_text()): CONF.set(k[1:], widget.get_text(), "radioreference") continue except Exception: pass common.show_error("Invalid value for %s" % k[1:]) valid = False break if valid: d.destroy() return True d.destroy() return False def do_radioreference(self, do_import): self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) if not self.do_radioreference_prompt(): self.window.set_cursor(None) return username = CONF.get("Username", "radioreference") passwd = CONF.get("Password", "radioreference") zipcode = CONF.get("Zipcode", "radioreference") # Do this in case the import process is going to take a while # to make sure we process events leading up to this gtk.gdk.window_process_all_updates() while gtk.events_pending(): gtk.main_iteration(False) if do_import: eset = self.get_current_editorset() count = eset.do_import("radioreference://%s/%s/%s" % (zipcode, username, passwd)) else: try: from chirp import radioreference radio = radioreference.RadioReferenceRadio(None) radio.set_params(zipcode, username, passwd) self.do_open_live(radio, read_only=True) except errors.RadioError, e: common.show_error(e) self.window.set_cursor(None) def do_export(self): types = [(_("CSV Files") + " (*.csv)", "csv"), (_("CHIRP Files") + " (*.chirp)", "chirp"), ] eset = self.get_current_editorset() if os.path.exists(eset.filename): base = os.path.basename(eset.filename) if "." in base: base = base[:base.rindex(".")] defname = base else: defname = "radio" filen = platform.get_platform().gui_save_file(default_name=defname, types=types) if not filen: return if os.path.exists(filen): dlg = inputdialog.OverwriteDialog(filen) owrite = dlg.run() dlg.destroy() if owrite != gtk.RESPONSE_OK: return os.remove(filen) count = eset.do_export(filen) reporting.report_model_usage(eset.rthread.radio, "export", count > 0) def do_about(self): d = gtk.AboutDialog() d.set_transient_for(self) import sys verinfo = "GTK %s\nPyGTK %s\nPython %s\n" % ( \ ".".join([str(x) for x in gtk.gtk_version]), ".".join([str(x) for x in gtk.pygtk_version]), sys.version.split()[0]) d.set_name("CHIRP") d.set_version(CHIRP_VERSION) d.set_copyright("Copyright 2013 Dan Smith (KK7DS)") d.set_website("http://chirp.danplanet.com") d.set_authors(("Dan Smith KK7DS <dsmith@danplanet.com>", _("With significant contributions from:"), "Tom KD7LXL", "Marco IZ3GME", "Jim KC9HI" )) d.set_translator_credits("Polish: Grzegorz SQ2RBY" + os.linesep + "Italian: Fabio IZ2QDH" + os.linesep + "Dutch: Michael PD4MT" + os.linesep + "German: Benjamin HB9EUK" + os.linesep + "Hungarian: Attila HA7JA" + os.linesep + "Russian: Dmitry Slukin" + os.linesep + "Portuguese (BR): Crezivando PP7CJ") d.set_comments(verinfo) d.run() d.destroy() def do_documentation(self): d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=self, type=gtk.MESSAGE_INFO) d.set_markup("<b><big>" + _("CHIRP Documentation") + "</big></b>\r\n") msg = _("Documentation for CHIRP, including FAQs, and help for common " "problems is available on the CHIRP web site, please go to\n\n" "<a href=\"http://chirp.danplanet.com/projects/chirp/wiki/" "Documentation\">" "http://chirp.danplanet.com/projects/chirp/wiki/" "Documentation</a>\n") d.format_secondary_markup(msg.replace("\n","\r\n")) d.run() d.destroy() def do_columns(self): eset = self.get_current_editorset() driver = directory.get_driver(eset.rthread.radio.__class__) radio_name = "%s %s %s" % (eset.rthread.radio.VENDOR, eset.rthread.radio.MODEL, eset.rthread.radio.VARIANT) d = gtk.Dialog(title=_("Select Columns"), parent=self, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) vbox = gtk.VBox() vbox.show() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) sw.add_with_viewport(vbox) sw.show() d.vbox.pack_start(sw, 1, 1, 1) d.set_size_request(-1, 300) d.set_resizable(False) label = gtk.Label(_("Visible columns for {radio}").format(radio=radio_name)) label.show() vbox.pack_start(label) fields = [] memedit = eset.get_current_editor() #.editors["memedit"] unsupported = memedit.get_unsupported_columns() for colspec in memedit.cols: if colspec[0].startswith("_"): continue elif colspec[0] in unsupported: continue label = colspec[0] visible = memedit.get_column_visible(memedit.col(label)) widget = gtk.CheckButton(label) widget.set_active(visible) fields.append(widget) vbox.pack_start(widget, 1, 1, 1) widget.show() res = d.run() selected_columns = [] if res == gtk.RESPONSE_OK: for widget in fields: colnum = memedit.col(widget.get_label()) memedit.set_column_visible(colnum, widget.get_active()) if widget.get_active(): selected_columns.append(widget.get_label()) d.destroy() CONF.set(driver, ",".join(selected_columns), "memedit_columns") def do_hide_unused(self, action): eset = self.get_current_editorset() if eset is None: conf = config.get("memedit") conf.set_bool("hide_unused", action.get_active()) else: for editortype, editor in eset.editors.iteritems(): if "memedit" in editortype: editor.set_hide_unused(action.get_active()) def do_clearq(self): eset = self.get_current_editorset() eset.rthread.flush() def do_copy(self, cut): eset = self.get_current_editorset() eset.get_current_editor().copy_selection(cut) def do_paste(self): eset = self.get_current_editorset() eset.get_current_editor().paste_selection() def do_delete(self): eset = self.get_current_editorset() eset.get_current_editor().copy_selection(True) def do_toggle_report(self, action): if not action.get_active(): d = gtk.MessageDialog(buttons=gtk.BUTTONS_YES_NO, parent=self) d.set_markup("<b><big>" + _("Reporting is disabled") + "</big></b>") msg = _("The reporting feature of CHIRP is designed to help " "<u>improve quality</u> by allowing the authors to focus " "on the radio drivers used most often and errors " "experienced by the users. The reports contain no " "identifying information and are used only for statistical " "purposes by the authors. Your privacy is extremely " "important, but <u>please consider leaving this feature " "enabled to help make CHIRP better!</u>\n\n<b>Are you " "sure you want to disable this feature?</b>") d.format_secondary_markup(msg.replace("\n", "\r\n")) r = d.run() d.destroy() if r == gtk.RESPONSE_NO: action.set_active(not action.get_active()) conf = config.get() conf.set_bool("no_report", not action.get_active()) def do_toggle_no_smart_tmode(self, action): CONF.set_bool("no_smart_tmode", not action.get_active(), "memedit") def do_toggle_developer(self, action): conf = config.get() conf.set_bool("developer", action.get_active(), "state") for name in ["viewdeveloper", "loadmod"]: devaction = self.menu_ag.get_action(name) devaction.set_visible(action.get_active()) def do_change_language(self): langs = ["Auto", "English", "Polish", "Italian", "Dutch", "German", "Hungarian", "Russian", "Portuguese (BR)"] d = inputdialog.ChoiceDialog(langs, parent=self, title="Choose Language") d.label.set_text(_("Choose a language or Auto to use the " "operating system default. You will need to " "restart the application before the change " "will take effect")) d.label.set_line_wrap(True) r = d.run() if r == gtk.RESPONSE_OK: print "Chose language %s" % d.choice.get_active_text() conf = config.get() conf.set("language", d.choice.get_active_text(), "state") d.destroy() def load_module(self): types = [(_("Python Modules") + "*.py", "*.py")] filen = platform.get_platform().gui_open_file(types=types) if not filen: return # We're in development mode, so we need to tell the directory to # allow a loaded module to override an existing driver, against # its normal better judgement directory.enable_reregistrations() try: module = file(filen) code = module.read() module.close() pyc = compile(code, filen, 'exec') # See this for why: # http://stackoverflow.com/questions/2904274/globals-and-locals-in-python-exec exec(pyc, globals(), globals()) except Exception, e: common.log_exception() common.show_error("Unable to load module: %s" % e) def mh(self, _action, *args): action = _action.get_name() if action == "quit": gtk.main_quit() elif action == "new": self.do_new() elif action == "open": self.do_open() elif action == "save": self.do_save() elif action == "saveas": self.do_saveas() elif action.startswith("download"): self.do_download(*args) elif action.startswith("upload"): self.do_upload(*args) elif action == "close": self.do_close() elif action == "import": self.do_import() elif action in ["qrfinder", "irfinder"]: self.do_rfinder(action[0] == "i") elif action in ["qradioreference", "iradioreference"]: self.do_radioreference(action[0] == "i") elif action == "export": self.do_export() elif action in ["qrbook", "irbook"]: self.do_repeaterbook(action[0] == "i") elif action in ["qpr", "ipr"]: self.do_przemienniki(action[0] == "i") elif action == "about": self.do_about() elif action == "documentation": self.do_documentation() elif action == "columns": self.do_columns() elif action == "hide_unused": self.do_hide_unused(_action) elif action == "cancelq": self.do_clearq() elif action == "report": self.do_toggle_report(_action) elif action == "channel_defaults": # The memedit thread also has an instance of bandplans. bp = bandplans.BandPlans(CONF) bp.select_bandplan(self) elif action == "no_smart_tmode": self.do_toggle_no_smart_tmode(_action) elif action == "developer": self.do_toggle_developer(_action) elif action in ["cut", "copy", "paste", "delete", "move_up", "move_dn", "exchange", "devshowraw", "devdiffraw"]: self.get_current_editorset().get_current_editor().hotkey(_action) elif action == "devdifftab": self.do_diff_radio() elif action == "language": self.do_change_language() elif action == "loadmod": self.load_module() else: return self.ev_tab_switched() def make_menubar(self): menu_xml = """ <ui> <menubar name="MenuBar"> <menu action="file"> <menuitem action="new"/> <menuitem action="open"/> <menu action="openstock" name="openstock"/> <menu action="recent" name="recent"/> <menuitem action="save"/> <menuitem action="saveas"/> <menuitem action="loadmod"/> <separator/> <menuitem action="import"/> <menuitem action="export"/> <separator/> <menuitem action="close"/> <menuitem action="quit"/> </menu> <menu action="edit"> <menuitem action="cut"/> <menuitem action="copy"/> <menuitem action="paste"/> <menuitem action="delete"/> <separator/> <menuitem action="move_up"/> <menuitem action="move_dn"/> <menuitem action="exchange"/> </menu> <menu action="view"> <menuitem action="columns"/> <menuitem action="hide_unused"/> <menuitem action="no_smart_tmode"/> <menu action="viewdeveloper"> <menuitem action="devshowraw"/> <menuitem action="devdiffraw"/> <menuitem action="devdifftab"/> </menu> <menuitem action="language"/> </menu> <menu action="radio" name="radio"> <menuitem action="download"/> <menuitem action="upload"/> <menu action="importsrc" name="importsrc"> <menuitem action="iradioreference"/> <menuitem action="irbook"/> <menuitem action="ipr"/> <menuitem action="irfinder"/> </menu> <menu action="querysrc" name="querysrc"> <menuitem action="qradioreference"/> <menuitem action="qrbook"/> <menuitem action="qpr"/> <menuitem action="qrfinder"/> </menu> <menu action="stock" name="stock"/> <separator/> <menuitem action="channel_defaults"/> <separator/> <menuitem action="cancelq"/> </menu> <menu action="help"> <menuitem action="about"/> <menuitem action="documentation"/> <menuitem action="report"/> <menuitem action="developer"/> </menu> </menubar> </ui> """ actions = [\ ('file', None, _("_File"), None, None, self.mh), ('new', gtk.STOCK_NEW, None, None, None, self.mh), ('open', gtk.STOCK_OPEN, None, None, None, self.mh), ('openstock', None, _("Open stock config"), None, None, self.mh), ('recent', None, _("_Recent"), None, None, self.mh), ('save', gtk.STOCK_SAVE, None, None, None, self.mh), ('saveas', gtk.STOCK_SAVE_AS, None, None, None, self.mh), ('loadmod', None, _("Load Module"), None, None, self.mh), ('close', gtk.STOCK_CLOSE, None, None, None, self.mh), ('quit', gtk.STOCK_QUIT, None, None, None, self.mh), ('edit', None, _("_Edit"), None, None, self.mh), ('cut', None, _("_Cut"), "<Ctrl>x", None, self.mh), ('copy', None, _("_Copy"), "<Ctrl>c", None, self.mh), ('paste', None, _("_Paste"), "<Ctrl>v", None, self.mh), ('delete', None, _("_Delete"), "Delete", None, self.mh), ('move_up', None, _("Move _Up"), "<Control>Up", None, self.mh), ('move_dn', None, _("Move Dow_n"), "<Control>Down", None, self.mh), ('exchange', None, _("E_xchange"), "<Control><Shift>x", None, self.mh), ('view', None, _("_View"), None, None, self.mh), ('columns', None, _("Columns"), None, None, self.mh), ('viewdeveloper', None, _("Developer"), None, None, self.mh), ('devshowraw', None, _('Show raw memory'), "<Control><Shift>r", None, self.mh), ('devdiffraw', None, _("Diff raw memories"), "<Control><Shift>d", None, self.mh), ('devdifftab', None, _("Diff tabs"), "<Control><Shift>t", None, self.mh), ('language', None, _("Change language"), None, None, self.mh), ('radio', None, _("_Radio"), None, None, self.mh), ('download', None, _("Download From Radio"), "<Alt>d", None, self.mh), ('upload', None, _("Upload To Radio"), "<Alt>u", None, self.mh), ('import', None, _("Import"), "<Alt>i", None, self.mh), ('export', None, _("Export"), "<Alt>x", None, self.mh), ('importsrc', None, _("Import from data source"), None, None, self.mh), ('iradioreference', None, _("RadioReference.com"), None, None, self.mh), ('irfinder', None, _("RFinder"), None, None, self.mh), ('irbook', None, _("RepeaterBook"), None, None, self.mh), ('ipr', None, _("przemienniki.net"), None, None, self.mh), ('querysrc', None, _("Query data source"), None, None, self.mh), ('qradioreference', None, _("RadioReference.com"), None, None, self.mh), ('qrfinder', None, _("RFinder"), None, None, self.mh), ('qpr', None, _("przemienniki.net"), None, None, self.mh), ('qrbook', None, _("RepeaterBook"), None, None, self.mh), ('export_chirp', None, _("CHIRP Native File"), None, None, self.mh), ('export_csv', None, _("CSV File"), None, None, self.mh), ('stock', None, _("Import from stock config"), None, None, self.mh), ('channel_defaults', None, _("Channel defaults"), None, None, self.mh), ('cancelq', gtk.STOCK_STOP, None, "Escape", None, self.mh), ('help', None, _('Help'), None, None, self.mh), ('about', gtk.STOCK_ABOUT, None, None, None, self.mh), ('documentation', None, _("Documentation"), None, None, self.mh), ] conf = config.get() re = not conf.get_bool("no_report"); hu = conf.get_bool("hide_unused", "memedit") dv = conf.get_bool("developer", "state") st = not conf.get_bool("no_smart_tmode", "memedit") toggles = [\ ('report', None, _("Report statistics"), None, None, self.mh, re), ('hide_unused', None, _("Hide Unused Fields"), None, None, self.mh, hu), ('no_smart_tmode', None, _("Smart Tone Modes"), None, None, self.mh, st), ('developer', None, _("Enable Developer Functions"), None, None, self.mh, dv), ] self.menu_uim = gtk.UIManager() self.menu_ag = gtk.ActionGroup("MenuBar") self.menu_ag.add_actions(actions) self.menu_ag.add_toggle_actions(toggles) self.menu_uim.insert_action_group(self.menu_ag, 0) self.menu_uim.add_ui_from_string(menu_xml) self.add_accel_group(self.menu_uim.get_accel_group()) self.recentmenu = self.menu_uim.get_widget("/MenuBar/file/recent") # Initialize self.do_toggle_developer(self.menu_ag.get_action("developer")) return self.menu_uim.get_widget("/MenuBar") def make_tabs(self): self.tabs = gtk.Notebook() return self.tabs def close_out(self): num = self.tabs.get_n_pages() while num > 0: num -= 1 print "Closing %i" % num try: self.do_close(self.tabs.get_nth_page(num)) except ModifiedError: return False gtk.main_quit() return True def make_status_bar(self): box = gtk.HBox(False, 2) self.sb_general = gtk.Statusbar() self.sb_general.set_has_resize_grip(False) self.sb_general.show() box.pack_start(self.sb_general, 1,1,1) self.sb_radio = gtk.Statusbar() self.sb_radio.set_has_resize_grip(True) self.sb_radio.show() box.pack_start(self.sb_radio, 1,1,1) box.show() return box def ev_delete(self, window, event): if not self.close_out(): return True # Don't exit def ev_destroy(self, window): if not self.close_out(): return True # Don't exit def setup_extra_hotkeys(self): accelg = self.menu_uim.get_accel_group() memedit = lambda a: self.get_current_editorset().editors["memedit"].hotkey(a) actions = [ # ("action_name", "key", function) ] for name, key, fn in actions: a = gtk.Action(name, name, name, "") a.connect("activate", fn) self.menu_ag.add_action_with_accel(a, key) a.set_accel_group(accelg) a.connect_accelerator() def _set_icon(self): execpath = platform.get_platform().executable_path() path = os.path.abspath(os.path.join(execpath, "share", "chirp.png")) if not os.path.exists(path): path = "/usr/share/pixmaps/chirp.png" if os.path.exists(path): self.set_icon_from_file(path) else: print "Icon %s not found" % path def _updates(self, version): if not version: return if version == CHIRP_VERSION: return print "Server reports version %s is available" % version # Report new updates every seven days intv = 3600 * 24 * 7 if CONF.is_defined("last_update_check", "state") and \ (time.time() - CONF.get_int("last_update_check", "state")) < intv: return CONF.set_int("last_update_check", int(time.time()), "state") d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=self, type=gtk.MESSAGE_INFO) d.set_property("text", _("A new version of CHIRP is available: " + "{ver}. ".format(ver=version) + "It is recommended that you upgrade, so " + "go to http://chirp.danplanet.com soon!")) d.run() d.destroy() def _init_macos(self, menu_bar): try: import gtk_osxapplication macapp = gtk_osxapplication.OSXApplication() except ImportError, e: print "No MacOS support: %s" % e return menu_bar.hide() macapp.set_menu_bar(menu_bar) quititem = self.menu_uim.get_widget("/MenuBar/file/quit") quititem.hide() aboutitem = self.menu_uim.get_widget("/MenuBar/help/about") macapp.insert_app_menu_item(aboutitem, 0) documentationitem = self.menu_uim.get_widget("/MenuBar/help/documentation") macapp.insert_app_menu_item(documentationitem, 0) macapp.set_use_quartz_accelerators(False) macapp.ready() print "Initialized MacOS support" def __init__(self, *args, **kwargs): gtk.Window.__init__(self, *args, **kwargs) def expose(window, event): allocation = window.get_allocation() CONF.set_int("window_w", allocation.width, "state") CONF.set_int("window_h", allocation.height, "state") self.connect("expose_event", expose) def state_change(window, event): CONF.set_bool( "window_maximized", event.new_window_state == gtk.gdk.WINDOW_STATE_MAXIMIZED, "state") self.connect("window-state-event", state_change) d = CONF.get("last_dir", "state") if d and os.path.isdir(d): platform.get_platform().set_last_dir(d) vbox = gtk.VBox(False, 2) self._recent = [] self.menu_ag = None mbar = self.make_menubar() if os.name != "nt": self._set_icon() # Windows gets the icon from the exe if os.uname()[0] == "Darwin": self._init_macos(mbar) vbox.pack_start(mbar, 0, 0, 0) self.tabs = None tabs = self.make_tabs() tabs.connect("switch-page", lambda n, _, p: self.ev_tab_switched(p)) tabs.connect("page-removed", lambda *a: self.ev_tab_switched()) tabs.show() self.ev_tab_switched() vbox.pack_start(tabs, 1, 1, 1) vbox.pack_start(self.make_status_bar(), 0, 0, 0) vbox.show() self.add(vbox) try: width = CONF.get_int("window_w", "state") height = CONF.get_int("window_h", "state") except Exception: width = 800 height = 600 self.set_default_size(width, height) if CONF.get_bool("window_maximized", "state"): self.maximize() self.set_title("CHIRP") self.connect("delete_event", self.ev_delete) self.connect("destroy", self.ev_destroy) if not CONF.get_bool("warned_about_reporting") and \ not CONF.get_bool("no_report"): d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=self) d.set_markup("<b><big>" + _("Error reporting is enabled") + "</big></b>") d.format_secondary_markup(\ _("If you wish to disable this feature you may do so in " "the <u>Help</u> menu")) d.run() d.destroy() CONF.set_bool("warned_about_reporting", True) self.update_recent_files() self.update_stock_configs() self.setup_extra_hotkeys() def updates_callback(ver): gobject.idle_add(self._updates, ver) if not CONF.get_bool("skip_update_check", "state"): reporting.check_for_updates(updates_callback)
cl4u2/chirp
chirpui/mainapp.py
Python
gpl-3.0
67,000
<? /** * This file is a part of LibWebta, PHP class library. * * LICENSE * * This program is protected by international copyright laws. Any * use of this program is subject to the terms of the license * agreement included as part of this distribution archive. * Any other uses are strictly prohibited without the written permission * of "Webta" and all other rights are reserved. * This notice may not be removed from this source code file. * This source file is subject to version 1.1 of the license, * that is bundled with this package in the file LICENSE. * If the backage does not contain LICENSE file, this source file is * subject to general license, available at http://webta.net/license.html * * @category LibWebta * @package IO * @subpackage PCNTL * @copyright Copyright (c) 2003-2009 Webta Inc, http://webta.net/copyright.html * @license http://webta.net/license.html */ /** * @name ProcessManager * @category LibWebta * @package IO * @subpackage PCNTL * @version 1.0 * @author Igor Savchenko <http://webta.net/company.html> * @example tests.php * @see tests.php */ class ProcessManager extends Core { /** * SignalHandler * * @var SignalHandler * @access private */ private $SignalHandler; /** * Proccess object * * @var object * @access protected */ protected $ProcessObject; /** * PIDs of child processes * * @var array * @access public */ public $PIDs; /** * Maximum allowed childs in one moment * * @var integer * @access public */ public $MaxChilds; /** * Proccess manager Constructor * * @param SignalHandler $SignalHandler */ function __construct(&$SignalHandler) { if ($SignalHandler instanceof SignalHandler) { $SignalHandler->ProcessManager = &$this; $this->SignalHandler = $SignalHandler; $this->MaxChilds = 5; //Log::Log("Process initialized.", E_NOTICE); } else self::RaiseError("Invalid signal handler"); } /** * Destructor * @ignore */ function __destruct() { } /** * Set MaxChilds * * @param integer $num * @final */ final public function SetMaxChilds($num) { if (count($this->PIDs) == 0) { $this->MaxChilds = $num; //Log::Log("Number of MaxChilds set to {$num}", E_NOTICE); } else self::RaiseError("You can only set MaxChilds *before* you Run() is executed."); } /** * Start Forking * * @param object $ProcessObject * @final */ final public function Run(&$ProcessObject) { // Check for ProcessObject existence if (!is_object($ProcessObject) || !($ProcessObject instanceof IProcess)) self::RaiseError("Invalid Proccess object", E_ERROR); // Set class property $this->ProcessObject = $ProcessObject; //Log::Log("Executing 'OnStartForking' routine", E_NOTICE); // Run routines before threading $this->ProcessObject->OnStartForking(); //Log::Log("'OnStartForking' successfully executed.", E_NOTICE); if (count($this->ProcessObject->ThreadArgs) == 0) { //Log::Log("ProcessObject::ThreadArgs is empty. Nothing to do.", E_NOTICE); return true; } //Log::Log("Executing ProcessObject::ForkThreads()", E_NOTICE); // Start Threading $this->ForkThreads(); // Wait while threads working $iteration = 1; while (true) { if (count($this->PIDs) == 0) break; sleep(2); if ($iteration++ == 10) { //Log::Log("Goin to MPWL. PIDs(".implode(", ", $this->PIDs).")", E_NOTICE); // // Zomby not needed. // $pid = pcntl_wait($status, WNOHANG | WUNTRACED); if ($pid > 0) { //Log::Log("MPWL: pcntl_wait() from child with PID# {$pid} (Exit code: {$status})", E_NOTICE); foreach((array)$this->PIDs as $kk=>$vv) { if ($vv == $pid) unset($this->PIDs[$kk]); } $this->ForkThreads(); } foreach ($this->PIDs as $k=>$pid) { $res = posix_kill($pid, 0); //Log::Log("MPWL: Sending 0 signal to {$pid} = ".intval($res), E_NOTICE); if ($res === FALSE) { //Log::Log("MPWL: Deleting '{$pid}' from PIDs query", E_NOTICE); unset($this->PIDs[$k]); } } $iteration = 1; } } //Log::Log("All childs exited. Executing OnEndForking routine", E_NOTICE); // Run routines after forking $this->ProcessObject->OnEndForking(); //Log::Log("Process complete. Exiting...", E_NOTICE); exit(); } /** * Start forking processes while number of childs less than MaxChilds and we have data in ThreadArgs * @access private * @final */ final public function ForkThreads() { while(count($this->ProcessObject->ThreadArgs) > 0 && count($this->PIDs) < $this->MaxChilds) { $arg = array_shift($this->ProcessObject->ThreadArgs); $this->Fork($arg); usleep(500000); } } /** * Fork child process * * @param mixed $arg * @final */ final private function Fork($arg) { $pid = @pcntl_fork(); if(!$pid) { try { $this->ProcessObject->StartThread($arg); } catch (Exception $err) { //Log::Log($err->getMessage(), E_CORE_ERROR); } exit(); } else { //Log::Log("Child with PID# {$pid} successfully forked", E_NOTICE); $this->PIDs[] = $pid; } } } ?>
DicsyDel/epp-drs
app/src/LibWebta/library/IO/PCNTL/class.ProcessManager.php
PHP
gpl-3.0
7,372
class FileInformation < ActiveRecord::Base belongs_to :external_file, foreign_key: :external_file_id end
SomeLabs/UniDrive
app/models/file_information.rb
Ruby
gpl-3.0
107
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '0.1.3'
sciunto-org/scifig
libscifig/__init__.py
Python
gpl-3.0
69
<?php return [ 'version' => 'Verzija', 'powered' => 'Powered By Akaunting', 'link' => 'https://akaunting.com', 'software' => 'Slobodan računovodstveni softver', ];
akaunting/akaunting
resources/lang/hr-HR/footer.php
PHP
gpl-3.0
242
<?php session_start(); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title> Sistema De Login :: w3layouts </title> <link rel="stylesheet" href="css/font-awesome.min.css" /> <link href="css/style.css" rel='stylesheet' type='text/css' media="all"> <link href="//fonts.googleapis.com/css?family=Poiret+One" rel="stylesheet"> </head> <body> <h1>Sistema De Login</h1> <div class="main-w3"> <?php if(isset($_SESSION['loginerro'])){ echo '<div class="login-w3ls"><div class="icons">'; echo '<div class="alert alert-danger wrapper hidden-vertical animated fadeInUp text-sm text-center">'; echo $_SESSION['loginerro']; echo '</div>'; echo '</div></div>'; unset($_SESSION['loginerro']); }elseif(isset($_SESSION['logout'])){ echo '<div class="login-w3ls"><div class="icons">'; echo '<div class="alert alert-success wrapper hidden-vertical animated fadeInUp text-sm text-center">'; echo $_SESSION['logout']; echo '</div>'; echo '</div></div>'; unset($_SESSION['logout']); } ?> <form action="./php/validar-login.php" method="post"> <h2><span class="fa fa-user t-w3" aria-hidden="true"></span></h2> <div class="login-w3ls"> <div class="icons"> <input type="email" name="email" placeholder="E-Mail" required=""> <span class="fa fa-user" aria-hidden="true"></span> <div class="clear"></div> </div> <div class="icons"> <input type="password" name="senha" placeholder="Senha" required=""> <span class="fa fa-key" aria-hidden="true"></span> <div class="clear"></div> </div> <div class="btnn"> <button type="submit">Entrar</button> </div> </div> </form> </div> <div class="copy"> <p>Sistema De Login - 2017 / Tema Via -> W3Layouts</p> </div> </body> </html>
ewersonsv/loginsystem
login.php
PHP
gpl-3.0
2,248
<?php require(dirname(__FILE__, 3) . '/framework/loader.php'); BeaconTemplate::SetTitle('Item Spawn Codes'); BeaconTemplate::AddScript(BeaconCommon::AssetURI('clipboard-polyfill.js')); BeaconTemplate::AddScript(BeaconCommon::AssetURI('spawncodes.js')); BeaconTemplate::AddStylesheet(BeaconCommon::AssetURI('spawncodes.scss')); $mod_id = array_key_exists('mod_id', $_GET) ? $_GET['mod_id'] : null; $database = BeaconCommon::Database(); if (is_null($mod_id) == false) { if (BeaconCommon::IsUUID($mod_id) == false) { header('Location: https://www.youtube.com/watch?v=dQw4w9WgXcQ'); http_response_code(302); echo 'caught'; exit; } } elseif (isset($_GET['workshop_id'])) { $workshop_id = $_GET['workshop_id']; if (is_null(filter_var($workshop_id, FILTER_VALIDATE_INT, ['options' => ['min_range' => -2147483648, 'max_range' => 2147483647], 'flags' => FILTER_NULL_ON_FAILURE]))) { header('Location: https://www.youtube.com/watch?v=dQw4w9WgXcQ'); http_response_code(302); exit; } $mod = BeaconMod::GetByConfirmedWorkshopID($workshop_id); if (is_array($mod) && count($mod) == 1) { $mod_id = $mod[0]->ModID(); } else { echo '<h1>Mod is not registered with Beacon.</h1>'; echo '<p>If you are the mod owner, see <a href="' . BeaconCommon::AbsoluteURL('/read/f21f4863-8043-4323-b6df-a9f96bbd982c') . '">Registering your mod with Beacon</a> for help.</p>'; exit; } } $results = $database->Query("SELECT build_number FROM updates ORDER BY build_number DESC LIMIT 1;"); if ($results->RecordCount() == 1) { $build = intval($results->Field('build_number')); } else { $build = 0; } $results = $database->Query("SELECT MAX(last_update) FROM objects WHERE min_version <= $1;", array($build)); $last_database_update = new DateTime($results->Field("max"), new DateTimeZone('UTC')); $include_mod_names = true; $cache_key = 'spawn_' . (is_null($mod_id) ? 'all' : $mod_id) . '_' . $build . '_' . $last_database_update->format('U'); $cached = BeaconCache::Get($cache_key); $title = BeaconCache::Get($cache_key . '_title'); if (is_null($cached) || is_null($title)) { ob_start(); if ($mod_id === null) { $title = 'All Spawn Codes'; $engrams = BeaconEngram::GetAll(); $creatures = BeaconCreature::GetAll(); } else { $engrams = BeaconEngram::Get($mod_id); $creatures = BeaconCreature::Get($mod_id); $mod_names = array(); foreach ($engrams as $engram) { if (in_array($engram->ModName(), $mod_names) === false) { $mod_names[] = $engram->ModName(); } } foreach ($creatures as $creature) { if (in_array($creature->ModName(), $mod_names) === false) { $mod_names[] = $creature->ModName(); } } asort($mod_names); if (count($mod_names) == 0) { echo 'Mod is not registered with Beacon.'; exit; } elseif (count($mod_names) == 1) { $title = $mod_names[0]; $include_mod_names = false; } elseif (count($mod_names) == 2) { $title = $mod_names[0] . ' and ' . $mod_names[1]; } else { $last = array_pop($mod_names); $title = implode(', ', $mod_names) . ', and ' . $last; } $title = 'Spawn codes for ' . $title; } ?><h1><?php echo htmlentities($title); ?><br><span class="subtitle">Up to date as of <?php echo '<time datetime="' . $last_database_update->format('c') . '">' . $last_database_update->format('F jS, Y') . ' at ' . $last_database_update->format('g:i A') . ' UTC</time>'; ?></span></h1> <p><input type="search" id="beacon-filter-field" placeholder="Filter Engrams" autocomplete="off"></p> <table id="spawntable" class="generic"> <thead> <tr> <td>Item Name</td> <td>Spawn Code</td> <td>Copy</td> </tr> </thead> <tbody> <?php $blueprints = array_merge($engrams, $creatures); uasort($blueprints, 'CompareBlueprints'); foreach ($blueprints as $blueprint) { $id = $blueprint->ObjectID(); $class = $blueprint->ClassString(); $label = $blueprint->Label(); $spawn = $blueprint->SpawnCode(); $mod = $blueprint->ModName(); echo '<tr id="spawn_' . htmlentities($id) . '" class="beacon-engram" beacon-label="' . htmlentities(strtolower($label)) . '" beacon-spawn-code="' . htmlentities($spawn) . '" beacon-uuid="' . $id . '">'; echo '<td>' . htmlentities($label) . ($include_mod_names ? '<span class="beacon-engram-mod-name"><br>' . htmlentities($mod) . '</span>' : '') . '<div class="beacon-spawn-code-small source-code-font">' . htmlentities($spawn) . '</div></td>'; echo '<td class="source-code-font">' . htmlentities($spawn) . '</td>'; echo '<td><button class="beacon-engram-copy" beacon-uuid="' . htmlentities($id) . '">Copy</button></td>'; echo '</tr>'; } ?> </tbody> </table><?php $cached = ob_get_contents(); ob_end_clean(); BeaconCache::Set($cache_key, $cached); BeaconCache::Set($cache_key . '_title', $title); } echo $cached; BeaconTemplate::SetTitle($title); function CompareBlueprints($left, $right) { $left_label = strtolower($left->Label()); $right_label = strtolower($right->Label()); if ($left_label === $right_label) { return 0; } return ($left_label < $right_label) ? -1 : 1; } ?>
thommcgrath/Beacon
Website/www/spawn/index.php
PHP
gpl-3.0
5,071
# the problem described below was fixed in 9758! # keep_htpsit=False fails since 9473, # on some installations (?) with: # case A (see below in the code): # RuntimeError: Could not locate the Fermi level! # or the energies from the 2nd one behave strange, no convergence: # iter: 1 18:21:49 +1.7 -3608.512512 0 19 # iter: 2 18:22:31 +1.9 -3148.936317 0 # iter: 3 18:23:13 +2.1 -2375.137532 0 # iter: 4 18:23:58 +2.4 -0.9 -1040.851545 216 11 # iter: 5 18:24:43 +2.6 -1.0 822.569589 597 14 # case B (see below in the code): # No convergence when starting from a converged (keep_htpsit=True) run! # WFS error grows to positive values! # Is it an extreme case of https://trac.fysik.dtu.dk/projects/gpaw/ticket/51 ? import os import sys from ase import Atoms from gpaw import GPAW from gpaw import ConvergenceError from gpaw.mpi import rank from gpaw.eigensolvers.rmm_diis_old import RMM_DIIS from gpaw import setup_paths if len(sys.argv) == 1: run = 'A' else: run = sys.argv[1] assert run in ['A', 'B'] # Use setups from the $PWD and $PWD/.. first setup_paths.insert(0, '.') setup_paths.insert(0, '../') positions=[ (-0.069, 0.824,-1.295), ( 0.786, 0.943,-0.752), (-0.414,-0.001,-0.865), (-0.282,-0.674,-3.822), ( 0.018,-0.147,-4.624), (-0.113,-0.080,-3.034), ( 2.253, 1.261, 0.151), ( 2.606, 0.638,-0.539), ( 2.455, 0.790, 1.019), ( 3.106,-0.276,-1.795), ( 2.914, 0.459,-2.386), ( 2.447,-1.053,-1.919), ( 6.257,-0.625,-0.626), ( 7.107,-1.002,-0.317), ( 5.526,-1.129,-0.131), ( 5.451,-1.261,-2.937), ( 4.585,-0.957,-2.503), ( 6.079,-0.919,-2.200), (-0.515, 3.689, 0.482), (-0.218, 3.020,-0.189), ( 0.046, 3.568, 1.382), (-0.205, 2.640,-3.337), (-1.083, 2.576,-3.771), (-0.213, 1.885,-2.680), ( 0.132, 6.301,-0.278), ( 1.104, 6.366,-0.068), (-0.148, 5.363,-0.112), (-0.505, 6.680,-3.285), (-0.674, 7.677,-3.447), (-0.965, 6.278,-2.517), ( 4.063, 3.342,-0.474), ( 4.950, 2.912,-0.663), ( 3.484, 2.619,-0.125), ( 2.575, 2.404,-3.170), ( 1.694, 2.841,-3.296), ( 3.049, 2.956,-2.503), ( 6.666, 2.030,-0.815), ( 7.476, 2.277,-0.316), ( 6.473, 1.064,-0.651), ( 6.860, 2.591,-3.584), ( 6.928, 3.530,-3.176), ( 6.978, 2.097,-2.754), ( 2.931, 6.022,-0.243), ( 3.732, 6.562,-0.004), ( 3.226, 5.115,-0.404), ( 2.291, 7.140,-2.455), ( 1.317, 6.937,-2.532), ( 2.586, 6.574,-1.669), ( 6.843, 5.460, 1.065), ( 7.803, 5.290, 0.852), ( 6.727, 5.424, 2.062), ( 6.896, 4.784,-2.130), ( 6.191, 5.238,-2.702), ( 6.463, 4.665,-1.259), ( 0.398, 0.691, 4.098), ( 0.047, 1.567, 3.807), ( 1.268, 0.490, 3.632), ( 2.687, 0.272, 2.641), ( 3.078, 1.126, 3.027), ( 3.376,-0.501, 2.793), ( 6.002,-0.525, 4.002), ( 6.152, 0.405, 3.660), ( 5.987,-0.447, 4.980), ( 0.649, 3.541, 2.897), ( 0.245, 4.301, 3.459), ( 1.638, 3.457, 3.084), (-0.075, 5.662, 4.233), (-0.182, 6.512, 3.776), (-0.241, 5.961, 5.212), ( 3.243, 2.585, 3.878), ( 3.110, 2.343, 4.817), ( 4.262, 2.718, 3.780), ( 5.942, 2.582, 3.712), ( 6.250, 3.500, 3.566), ( 6.379, 2.564, 4.636), ( 2.686, 5.638, 5.164), ( 1.781, 5.472, 4.698), ( 2.454, 6.286, 5.887), ( 6.744, 5.276, 3.826), ( 6.238, 5.608, 4.632), ( 7.707, 5.258, 4.110), ( 8.573, 8.472, 0.407), ( 9.069, 7.656, 0.067), ( 8.472, 8.425, 1.397), ( 8.758, 8.245, 2.989), ( 9.294, 9.091, 3.172), ( 7.906, 8.527, 3.373), ( 4.006, 7.734, 3.021), ( 4.685, 8.238, 3.547), ( 3.468, 7.158, 3.624), ( 5.281, 6.089, 6.035), ( 5.131, 7.033, 6.378), ( 4.428, 5.704, 5.720), ( 5.067, 7.323, 0.662), ( 5.785, 6.667, 0.703), ( 4.718, 7.252, 1.585)] prefix = 'b256H2O' L = 9.8553729 atoms = Atoms('32(OH2)', positions=positions) atoms.set_cell((L,L,L),scale_atoms=False) atoms.set_pbc(1) r = [1, 1, 2] atoms = atoms.repeat(r) n = [56 * ri for ri in r] # nbands (>=128) is the number of bands per 32 water molecules nbands = 2*6*11 # 132 for ri in r: nbands = nbands*ri # the next line decreases memory usage es = RMM_DIIS(keep_htpsit=False) calc = GPAW(nbands=nbands, # uncomment next two lines to use lcao/sz #mode='lcao', #basis='sz', gpts=tuple(n), #maxiter=5, width = 0.01, eigensolver = es, txt=prefix + '.txt', ) if run == 'A': atoms.set_calculator(calc) pot = atoms.get_potential_energy() elif run == 'B': # converge first with keep_htpsit=True calc.set(eigensolver='rmm-diis') calc.set(txt=prefix + '_True.txt') atoms.set_calculator(calc) pot = atoms.get_potential_energy() # fails to converge with keep_htpsit=False calc.set(eigensolver=es) calc.set(maxiter=200) calc.set(txt=prefix + '_False.txt') atoms.set_calculator(calc) pot = atoms.get_potential_energy()
robwarm/gpaw-symm
gpaw/test/big/scf/b256H2O/b256H2O.py
Python
gpl-3.0
4,905
#!/usr/bin/python3 # Copyright (C) 2014-2016, 2018 Rafael Senties Martinelli # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import configparser import os import traceback __version__ = '18.10.16' class CCParser(object): def __init__(self, ini_path='', section='', debug=False): """ To init CCParser you can enter a path and a section. If you doesn't know them yet you can leave them empty. If debug is set to True, all the exceptions will print its traceback. """ self._debug = debug self._config = configparser.ConfigParser() if ini_path != '': self.set_configuration_path(ini_path) if section != '': self.set_section(section) self.__default_bool = False self.__default_string = '' self.__default_int = 0 self.__default_float = 0.0 self.__default_list = [] self._accepted_true_bool = ('true', 'yes') # must be lower case self._accepted_false_bool = ('false', 'no') # must be lower case def __str__(self): return ''' CCParser instance: {} Configuration Path: {} Section: {} Default boolean: {} Default float: {} Default integer: {} Default string: {} Default list: {} '''.format( repr(self), self.get_configuration_path(), self.get_section(), self.get_default_bool(), self.get_default_float(), self.get_default_int(), self.get_default_str(), self.get_default_list()) def check_value(self, value): """ return False if the value don't exists, return True if the value exists """ if not os.path.exists(self.ini_path): return False else: try: self._config.read(self.ini_path) except Exception: print("CCParser Warning: reading damaged file or file without section") print(traceback.format_exc()) print() return False if not self._config.has_section(self.__section): return False elif self._config.has_option(self.__section, value): return True else: return False def get_bool(self, value): """ If the value exists, return the boolean corresponding to the string. If it does not exists, or the value can not be converted to a boolean, return the default boolean. """ if self.check_value(value): val = self._config.get(self.__section, value).lower() if val in self._accepted_false_bool: return False elif val in self._accepted_true_bool: return True else: return self.__default_bool else: return self.__default_bool def get_float(self, value): """ If the value exists, return the float corresponding to the string. If it does not exists, or the value can not be converted to a float, return the default float. """ if self.check_value(value): val = self._config.get(self.__section, value) try: val = float(val) return val except Exception: if self._debug: print(traceback.format_exc()) return self.__default_float else: return self.__default_float def get_int(self, value): """ If the value exists, return the integer corresponding to the string. If it does not exists, or the value can not be converted to a integer, return the default integer. """ if self.check_value(value): val = self._config.get(self.__section, value) try: val = int(val) return val except Exception: if self._debug: print(traceback.format_exc()) return self.__default_int else: return self.__default_int def get_list(self, value): """ If the value exists, return the integer corresponding to the string. If it does not exists, or the value can not be converted to a integer, return the default integer. """ if self.check_value(value): val = self._config.get(self.__section, value) try: val = val.split("|") return val except Exception: if self._debug: print(traceback.format_exc()) return self.__default_list else: return self.__default_list def get_str(self, value): """ If the value exists, return the string, other wise return the default string. """ if self.check_value(value): return self._config.get(self.__section, value) else: return self.__default_string def get_bool_defval(self, value, default): """ If the value exists, return the boolean corresponding to the string. If it does not exists, or the value can not be converted to a boolean, return the the second argument. """ if self.check_value(value): val = self._config.get(self.__section, value).lower() if val in self._accepted_false_bool: return False elif val in self._accepted_true_bool: return True else: return default else: return default def get_float_defval(self, value, default): """ If the value exists, return the float corresponding to the string. If it does not exists, or the value can not be converted to a float, return the the second argument. """ if self.check_value(value): val = self._config.get(self.__section, value) try: val = float(val) return val except Exception: if self._debug: print(traceback.format_exc()) return default else: return default def get_int_defval(self, value, default): """ If the value exists, return the integer corresponding to the string. If it does not exists, or the value can not be converted to a integer, return the the second argument. """ if self.check_value(value): val = self._config.get(self.__section, value) try: val = int(val) return val except Exception: if self._debug: print(traceback.format_exc()) return default else: return default def get_str_defval(self, value, default): """ If the value exists, return the string, if it does not exists, return the the second argument. """ if self.check_value(value): return self._config.get(self.__section, value) else: return default def set_configuration_path(self, ini_path): """ Set the path to the configuration file. """ if isinstance(ini_path, str): self.ini_path = ini_path if not os.path.exists(ini_path) and self._debug: print("CCParser Warning: the path to the configuration file does not exists\n") else: print("CCParser Warning: The path is not valid.\n") self.ini_path = '' def set_section(self, section): """ Set the section to check for values. """ section = str(section) self.__section = section def set_default_float(self, value): """ Set the default float to return when a value does not exists. By default it returns 0.0 """ self.__default_float = value def set_default_string(self, value): """ Set the default string to return when a value does not exists. By default it returns an empty string. """ self.__default_string = value def set_default_bool(self, value): """ Set the default boolean to return when a value does not exists. By default it returns false """ self.__default_bool = value def set_default_int(self, value): """ Set the default integer to return when a value does not exists. By default it returns 0 """ self.__default_int = value def set_default_list(self, value): """ Set the default integer to return when a value does not exists. By default it returns 0 """ self.__default_list = value def write(self, value_name, value): """ Write the value name and its value. If the config file does not exists, or the directories to the path, they will be created. """ if self.ini_path != '' and isinstance(self.ini_path, str): if not os.path.exists(os.path.dirname(self.ini_path)): os.makedirs(os.path.dirname(self.ini_path)) if not os.path.exists(self.ini_path): open(self.ini_path, 'wt').close() try: self._config.read(self.ini_path) except Exception: print("CCParser Warning: reading damaged file or file without section") print(traceback.format_exc()) print() return False if not self._config.has_section(self.__section): self._config.add_section(self.__section) if isinstance(value, list) or isinstance(value, tuple): values = '|'.join(item for item in value) self._config.set(self.__section, value_name, values) else: self._config.set(self.__section, value_name, str(value)) with open(self.ini_path, 'w') as f: self._config.write(f) else: print( "CCParser Error: Trying to write the configuration without an ini path.") print("Configuration Path: " + str(self.get_configuration_path())) print() def get_default_bool(self): return self.__default_bool def get_default_float(self): return self.__default_float def get_default_str(self): return self.__default_string def get_default_int(self): return self.__default_int def get_default_list(self): return self.__default_list def get_section(self): return self.__section def get_configuration_path(self): return self.ini_path if __name__ == '__main__': def test(path): if os.path.exists(path): os.remove(path) cp = CCParser(path, 'test') print('section:', cp.get_section()) cp.write('bool', False) print(cp.get_bool('bool')) cp.write('bool', True) print(cp.get_bool('bool')) cp.write('string1', 'this is a test') print(cp.get_str('string1')) print(cp) test('/home/rsm/Desktop/test.ini') # unexisting file
rsm-gh/alienware-kbl
usr/lib/python3/AKBL/CCParser.py
Python
gpl-3.0
12,434
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-01 20:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('flocks', '0015_auto_20170624_1312'), ('feeding', '0005_auto_20170625_1129'), ] operations = [ migrations.CreateModel( name='FeedingPeriodForFlock', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start_date', models.DateField()), ('end_date', models.DateField(null=True)), ('feed_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='feeding.FeedType')), ('flock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='flocks.Flock')), ], ), migrations.RemoveField( model_name='feedingperiodforroom', name='feed_type', ), migrations.RemoveField( model_name='feedingperiodforroom', name='room', ), migrations.DeleteModel( name='FeedingPeriodForRoom', ), ]
forcaeluz/easy-fat
feeding/migrations/0006_auto_20170701_2013.py
Python
gpl-3.0
1,270
/* * Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1. * Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2. * * This file is part of GOOL. * * GOOL is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, version 3. * * GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License version 3 for more details. * * You should have received a copy of the GNU General Public License along with GOOL, * in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>. */ package gool.ast.core; import gool.ast.type.TypeNone; import gool.generator.GoolGeneratorController; import gool.generator.common.CodeGenerator; /** * This class captures an enhanced for loop in the intermediate language. * Hence it inherits of Expression. * For example, this class captures * {@code * for( String s : array){ * ... * } */ public class EnhancedForLoop extends Expression { /** * The variable declaration in the enhanced for loop. */ private VarDeclaration varDec; /** * The expression used in the enhanced for loop. */ private Expression expr; /** * The statement used in the enhanced for loop. */ private Statement statements; /** * The simple constructor of an enhanced for loop representation. */ private EnhancedForLoop() { super(TypeNone.INSTANCE); } /** * The constructor of an enhanced for loop representation. * @param varDec * : The variable declaration in the enhanced for loop. * @param expr * : The expression used in the enhanced for loop. * @param statements * : The statement used in the enhanced for loop. */ public EnhancedForLoop(VarDeclaration varDec, Expression expr, Statement statements) { this(); this.varDec = varDec; this.expr = expr; this.statements = statements; } /** * Gets the variable declaration in the enhanced for loop. * @return * The variable declaration in the enhanced for loop. */ public VarDeclaration getVarDec() { return varDec; } /** * Gets the expression used in the enhanced for loop. * @return * The expression used in the enhanced for loop. */ public Expression getExpression() { return expr; } /** * Gets the statement used in the enhanced for loop. * @return * The statement used in the enhanced for loop. */ public Statement getStatements() { return statements; } @Override public String callGetCode() { CodeGenerator cg; try{ cg = GoolGeneratorController.generator(); }catch (IllegalStateException e){ return this.getClass().getSimpleName(); } return cg.getCode(this); } }
darrivau/GOOL
src/main/java/gool/ast/core/EnhancedForLoop.java
Java
gpl-3.0
2,878
(function (root) { "use strict"; var Tone; //constructs the main Tone object function Main(func){ Tone = func(); } //invokes each of the modules with the main Tone object as the argument function Module(func){ func(Tone); } /** * Tone.js * @author Yotam Mann * @license http://opensource.org/licenses/MIT MIT License * @copyright 2014-2015 Yotam Mann */ Main(function () { ////////////////////////////////////////////////////////////////////////// // WEB AUDIO CONTEXT /////////////////////////////////////////////////////////////////////////// //borrowed from underscore.js function isUndef(val) { return val === void 0; } //borrowed from underscore.js function isFunction(val) { return typeof val === 'function'; } var audioContext; //polyfill for AudioContext and OfflineAudioContext if (isUndef(window.AudioContext)) { window.AudioContext = window.webkitAudioContext; } if (isUndef(window.OfflineAudioContext)) { window.OfflineAudioContext = window.webkitOfflineAudioContext; } if (!isUndef(AudioContext)) { audioContext = new AudioContext(); } else { throw new Error('Web Audio is not supported in this browser'); } //SHIMS//////////////////////////////////////////////////////////////////// if (!isFunction(AudioContext.prototype.createGain)) { AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; } if (!isFunction(AudioContext.prototype.createDelay)) { AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; } if (!isFunction(AudioContext.prototype.createPeriodicWave)) { AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; } if (!isFunction(AudioBufferSourceNode.prototype.start)) { AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; } if (!isFunction(AudioBufferSourceNode.prototype.stop)) { AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.start)) { OscillatorNode.prototype.start = OscillatorNode.prototype.noteOn; } if (!isFunction(OscillatorNode.prototype.stop)) { OscillatorNode.prototype.stop = OscillatorNode.prototype.noteOff; } if (!isFunction(OscillatorNode.prototype.setPeriodicWave)) { OscillatorNode.prototype.setPeriodicWave = OscillatorNode.prototype.setWaveTable; } //extend the connect function to include Tones AudioNode.prototype._nativeConnect = AudioNode.prototype.connect; AudioNode.prototype.connect = function (B, outNum, inNum) { if (B.input) { if (Array.isArray(B.input)) { if (isUndef(inNum)) { inNum = 0; } this.connect(B.input[inNum]); } else { this.connect(B.input, outNum, inNum); } } else { try { if (B instanceof AudioNode) { this._nativeConnect(B, outNum, inNum); } else { this._nativeConnect(B, outNum); } } catch (e) { throw new Error('error connecting to node: ' + B); } } }; /////////////////////////////////////////////////////////////////////////// // TONE /////////////////////////////////////////////////////////////////////////// /** * @class Tone is the base class of all other classes. It provides * a lot of methods and functionality to all classes that extend * it. * * @constructor * @alias Tone * @param {number} [inputs=1] the number of input nodes * @param {number} [outputs=1] the number of output nodes */ var Tone = function (inputs, outputs) { /** * the input node(s) * @type {GainNode|Array} */ if (isUndef(inputs) || inputs === 1) { this.input = this.context.createGain(); } else if (inputs > 1) { this.input = new Array(inputs); } /** * the output node(s) * @type {GainNode|Array} */ if (isUndef(outputs) || outputs === 1) { this.output = this.context.createGain(); } else if (outputs > 1) { this.output = new Array(inputs); } }; /** * Set the parameters at once. Either pass in an * object mapping parameters to values, or to set a * single parameter, by passing in a string and value. * The last argument is an optional ramp time which * will ramp any signal values to their destination value * over the duration of the rampTime. * @param {Object|string} params * @param {number=} value * @param {Time=} rampTime * @returns {Tone} this * @example * //set values using an object * filter.set({ * "frequency" : 300, * "type" : highpass * }); * @example * filter.set("type", "highpass"); * @example * //ramp to the value 220 over 3 seconds. * oscillator.set({ * "frequency" : 220 * }, 3); */ Tone.prototype.set = function (params, value, rampTime) { if (this.isObject(params)) { rampTime = value; } else if (this.isString(params)) { var tmpObj = {}; tmpObj[params] = value; params = tmpObj; } for (var attr in params) { value = params[attr]; var parent = this; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var i = 0; i < attrSplit.length - 1; i++) { parent = parent[attrSplit[i]]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (isUndef(param)) { continue; } if (Tone.Signal && param instanceof Tone.Signal || Tone.Param && param instanceof Tone.Param) { if (param.value !== value) { if (isUndef(rampTime)) { param.value = value; } else { param.rampTo(value, rampTime); } } } else if (param instanceof AudioParam) { if (param.value !== value) { param.value = value; } } else if (param instanceof Tone) { param.set(value); } else if (param !== value) { parent[attr] = value; } } return this; }; /** * Get the object's attributes. Given no arguments get * will return all available object properties and their corresponding * values. Pass in a single attribute to retrieve or an array * of attributes. The attribute strings can also include a "." * to access deeper properties. * @example * osc.get(); * //returns {"type" : "sine", "frequency" : 440, ...etc} * @example * osc.get("type"); * //returns { "type" : "sine"} * @example * //use dot notation to access deep properties * synth.get(["envelope.attack", "envelope.release"]); * //returns {"envelope" : {"attack" : 0.2, "release" : 0.4}} * @param {Array=|string|undefined} params the parameters to get, otherwise will return * all available. * @returns {Object} */ Tone.prototype.get = function (params) { if (isUndef(params)) { params = this._collectDefaults(this.constructor); } else if (this.isString(params)) { params = [params]; } var ret = {}; for (var i = 0; i < params.length; i++) { var attr = params[i]; var parent = this; var subRet = ret; if (attr.indexOf('.') !== -1) { var attrSplit = attr.split('.'); for (var j = 0; j < attrSplit.length - 1; j++) { var subAttr = attrSplit[j]; subRet[subAttr] = subRet[subAttr] || {}; subRet = subRet[subAttr]; parent = parent[subAttr]; } attr = attrSplit[attrSplit.length - 1]; } var param = parent[attr]; if (this.isObject(params[attr])) { subRet[attr] = param.get(); } else if (Tone.Signal && param instanceof Tone.Signal) { subRet[attr] = param.value; } else if (Tone.Param && param instanceof Tone.Param) { subRet[attr] = param.value; } else if (param instanceof AudioParam) { subRet[attr] = param.value; } else if (param instanceof Tone) { subRet[attr] = param.get(); } else if (!isFunction(param) && !isUndef(param)) { subRet[attr] = param; } } return ret; }; /** * collect all of the default attributes in one * @private * @param {function} constr the constructor to find the defaults from * @return {Array} all of the attributes which belong to the class */ Tone.prototype._collectDefaults = function (constr) { var ret = []; if (!isUndef(constr.defaults)) { ret = Object.keys(constr.defaults); } if (!isUndef(constr._super)) { var superDefs = this._collectDefaults(constr._super); //filter out repeats for (var i = 0; i < superDefs.length; i++) { if (ret.indexOf(superDefs[i]) === -1) { ret.push(superDefs[i]); } } } return ret; }; /** * @returns {string} returns the name of the class as a string */ Tone.prototype.toString = function () { for (var className in Tone) { var isLetter = className[0].match(/^[A-Z]$/); var sameConstructor = Tone[className] === this.constructor; if (isFunction(Tone[className]) && isLetter && sameConstructor) { return className; } } return 'Tone'; }; /////////////////////////////////////////////////////////////////////////// // CLASS VARS /////////////////////////////////////////////////////////////////////////// /** * A static pointer to the audio context accessible as Tone.context. * @type {AudioContext} */ Tone.context = audioContext; /** * The audio context. * @type {AudioContext} */ Tone.prototype.context = Tone.context; /** * the default buffer size * @type {number} * @static * @const */ Tone.prototype.bufferSize = 2048; /** * The delay time of a single frame (128 samples according to the spec). * @type {number} * @static * @const */ Tone.prototype.blockTime = 128 / Tone.context.sampleRate; /////////////////////////////////////////////////////////////////////////// // CONNECTIONS /////////////////////////////////////////////////////////////////////////// /** * disconnect and dispose * @returns {Tone} this */ Tone.prototype.dispose = function () { if (!this.isUndef(this.input)) { if (this.input instanceof AudioNode) { this.input.disconnect(); } this.input = null; } if (!this.isUndef(this.output)) { if (this.output instanceof AudioNode) { this.output.disconnect(); } this.output = null; } return this; }; /** * a silent connection to the DesinationNode * which will ensure that anything connected to it * will not be garbage collected * * @private */ var _silentNode = null; /** * makes a connection to ensure that the node will not be garbage collected * until 'dispose' is explicitly called * * use carefully. circumvents JS and WebAudio's normal Garbage Collection behavior * @returns {Tone} this */ Tone.prototype.noGC = function () { this.output.connect(_silentNode); return this; }; AudioNode.prototype.noGC = function () { this.connect(_silentNode); return this; }; /** * connect the output of a ToneNode to an AudioParam, AudioNode, or ToneNode * @param {Tone | AudioParam | AudioNode} unit * @param {number} [outputNum=0] optionally which output to connect from * @param {number} [inputNum=0] optionally which input to connect to * @returns {Tone} this */ Tone.prototype.connect = function (unit, outputNum, inputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].connect(unit, 0, inputNum); } else { this.output.connect(unit, outputNum, inputNum); } return this; }; /** * disconnect the output * @returns {Tone} this */ Tone.prototype.disconnect = function (outputNum) { if (Array.isArray(this.output)) { outputNum = this.defaultArg(outputNum, 0); this.output[outputNum].disconnect(); } else { this.output.disconnect(); } return this; }; /** * connect together all of the arguments in series * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.connectSeries = function () { if (arguments.length > 1) { var currentUnit = arguments[0]; for (var i = 1; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; /** * fan out the connection from the first argument to the rest of the arguments * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.connectParallel = function () { var connectFrom = arguments[0]; if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { var connectTo = arguments[i]; connectFrom.connect(connectTo); } } return this; }; /** * Connect the output of this node to the rest of the nodes in series. * @example * //connect a node to an effect, panVol and then to the master output * node.chain(effect, panVol, Tone.Master); * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.chain = function () { if (arguments.length > 0) { var currentUnit = this; for (var i = 0; i < arguments.length; i++) { var toUnit = arguments[i]; currentUnit.connect(toUnit); currentUnit = toUnit; } } return this; }; /** * connect the output of this node to the rest of the nodes in parallel. * @param {...AudioParam|Tone|AudioNode} nodes * @returns {Tone} this */ Tone.prototype.fan = function () { if (arguments.length > 0) { for (var i = 0; i < arguments.length; i++) { this.connect(arguments[i]); } } return this; }; //give native nodes chain and fan methods AudioNode.prototype.chain = Tone.prototype.chain; AudioNode.prototype.fan = Tone.prototype.fan; /////////////////////////////////////////////////////////////////////////// // UTILITIES / HELPERS / MATHS /////////////////////////////////////////////////////////////////////////// /** * If the `given` parameter is undefined, use the `fallback`. * If both `given` and `fallback` are object literals, it will * return a deep copy which includes all of the parameters from both * objects. If a parameter is undefined in given, it will return * the fallback property. * <br><br> * WARNING: if object is self referential, it will go into an an * infinite recursive loop. * * @param {*} given * @param {*} fallback * @return {*} */ Tone.prototype.defaultArg = function (given, fallback) { if (this.isObject(given) && this.isObject(fallback)) { var ret = {}; //make a deep copy of the given object for (var givenProp in given) { ret[givenProp] = this.defaultArg(fallback[givenProp], given[givenProp]); } for (var fallbackProp in fallback) { ret[fallbackProp] = this.defaultArg(given[fallbackProp], fallback[fallbackProp]); } return ret; } else { return isUndef(given) ? fallback : given; } }; /** * returns the args as an options object with given arguments * mapped to the names provided. * * if the args given is an array containing only one object, it is assumed * that that's already the options object and will just return it. * * @param {Array} values the 'arguments' object of the function * @param {Array} keys the names of the arguments as they * should appear in the options object * @param {Object=} defaults optional defaults to mixin to the returned * options object * @return {Object} the options object with the names mapped to the arguments */ Tone.prototype.optionsObject = function (values, keys, defaults) { var options = {}; if (values.length === 1 && this.isObject(values[0])) { options = values[0]; } else { for (var i = 0; i < keys.length; i++) { options[keys[i]] = values[i]; } } if (!this.isUndef(defaults)) { return this.defaultArg(options, defaults); } else { return options; } }; /////////////////////////////////////////////////////////////////////////// // TYPE CHECKING /////////////////////////////////////////////////////////////////////////// /** * test if the arg is undefined * @param {*} arg the argument to test * @returns {boolean} true if the arg is undefined * @function */ Tone.prototype.isUndef = isUndef; /** * test if the arg is a function * @param {*} arg the argument to test * @returns {boolean} true if the arg is a function * @function */ Tone.prototype.isFunction = isFunction; /** * Test if the argument is a number. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a number */ Tone.prototype.isNumber = function (arg) { return typeof arg === 'number'; }; /** * Test if the given argument is an object literal (i.e. `{}`); * @param {*} arg the argument to test * @returns {boolean} true if the arg is an object literal. */ Tone.prototype.isObject = function (arg) { return Object.prototype.toString.call(arg) === '[object Object]' && arg.constructor === Object; }; /** * Test if the argument is a boolean. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a boolean */ Tone.prototype.isBoolean = function (arg) { return typeof arg === 'boolean'; }; /** * Test if the argument is an Array * @param {*} arg the argument to test * @returns {boolean} true if the arg is an array */ Tone.prototype.isArray = function (arg) { return Array.isArray(arg); }; /** * Test if the argument is a string. * @param {*} arg the argument to test * @returns {boolean} true if the arg is a string */ Tone.prototype.isString = function (arg) { return typeof arg === 'string'; }; /** * An empty function. * @static */ Tone.noOp = function () { }; /** * Make the property not writable. Internal use only. * @private * @param {string} property the property to make not writable */ Tone.prototype._readOnly = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._readOnly(property[i]); } } else { Object.defineProperty(this, property, { writable: false, enumerable: true }); } }; /** * Make an attribute writeable. Interal use only. * @private * @param {string} property the property to make writable */ Tone.prototype._writable = function (property) { if (Array.isArray(property)) { for (var i = 0; i < property.length; i++) { this._writable(property[i]); } } else { Object.defineProperty(this, property, { writable: true }); } }; /** * Possible play states. * @enum {string} */ Tone.State = { Started: 'started', Stopped: 'stopped', Paused: 'paused' }; /////////////////////////////////////////////////////////////////////////// // GAIN CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Equal power gain scale. Good for cross-fading. * @param {NormalRange} percent (0-1) * @return {Number} output gain (0-1) */ Tone.prototype.equalPowerScale = function (percent) { var piFactor = 0.5 * Math.PI; return Math.sin(percent * piFactor); }; /** * Convert decibels into gain. * @param {Decibels} db * @return {Number} */ Tone.prototype.dbToGain = function (db) { return Math.pow(2, db / 6); }; /** * Convert gain to decibels. * @param {Number} gain (0-1) * @return {Decibels} */ Tone.prototype.gainToDb = function (gain) { return 20 * (Math.log(gain) / Math.LN10); }; /////////////////////////////////////////////////////////////////////////// // TIMING /////////////////////////////////////////////////////////////////////////// /** * Return the current time of the clock + a single buffer frame. * If this value is used to schedule a value to change, the earliest * it could be scheduled is the following frame. * @return {number} the currentTime from the AudioContext */ Tone.prototype.now = function () { return this.context.currentTime; }; /////////////////////////////////////////////////////////////////////////// // INHERITANCE /////////////////////////////////////////////////////////////////////////// /** * have a child inherit all of Tone's (or a parent's) prototype * to inherit the parent's properties, make sure to call * Parent.call(this) in the child's constructor * * based on closure library's inherit function * * @static * @param {function} child * @param {function=} parent (optional) parent to inherit from * if no parent is supplied, the child * will inherit from Tone */ Tone.extend = function (child, parent) { if (isUndef(parent)) { parent = Tone; } function TempConstructor() { } TempConstructor.prototype = parent.prototype; child.prototype = new TempConstructor(); /** @override */ child.prototype.constructor = child; child._super = parent; }; /////////////////////////////////////////////////////////////////////////// // CONTEXT /////////////////////////////////////////////////////////////////////////// /** * array of callbacks to be invoked when a new context is added * @private * @private */ var newContextCallbacks = []; /** * invoke this callback when a new context is added * will be invoked initially with the first context * @private * @static * @param {function(AudioContext)} callback the callback to be invoked * with the audio context */ Tone._initAudioContext = function (callback) { //invoke the callback with the existing AudioContext callback(Tone.context); //add it to the array newContextCallbacks.push(callback); }; /** * Tone automatically creates a context on init, but if you are working * with other libraries which also create an AudioContext, it can be * useful to set your own. If you are going to set your own context, * be sure to do it at the start of your code, before creating any objects. * @static * @param {AudioContext} ctx The new audio context to set */ Tone.setContext = function (ctx) { //set the prototypes Tone.prototype.context = ctx; Tone.context = ctx; //invoke all the callbacks for (var i = 0; i < newContextCallbacks.length; i++) { newContextCallbacks[i](ctx); } }; /** * Bind this to a touchstart event to start the audio on mobile devices. * <br> * http://stackoverflow.com/questions/12517000/no-sound-on-ios-6-web-audio-api/12569290#12569290 * @static */ Tone.startMobile = function () { var osc = Tone.context.createOscillator(); var silent = Tone.context.createGain(); silent.gain.value = 0; osc.connect(silent); silent.connect(Tone.context.destination); var now = Tone.context.currentTime; osc.start(now); osc.stop(now + 1); }; //setup the context Tone._initAudioContext(function (audioContext) { //set the blockTime Tone.prototype.blockTime = 128 / audioContext.sampleRate; _silentNode = audioContext.createGain(); _silentNode.gain.value = 0; _silentNode.connect(audioContext.destination); }); Tone.version = 'r6'; console.log('%c * Tone.js ' + Tone.version + ' * ', 'background: #000; color: #fff'); return Tone; }); Module(function (Tone) { /** * @class Base class for all Signals. Used Internally. * * @constructor * @extends {Tone} */ Tone.SignalBase = function () { }; Tone.extend(Tone.SignalBase); /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.SignalBase} this */ Tone.SignalBase.prototype.connect = function (node, outputNumber, inputNumber) { //zero it out so that the signal can have full control if (Tone.Signal && Tone.Signal === node.constructor || Tone.Param && Tone.Param === node.constructor || Tone.TimelineSignal && Tone.TimelineSignal === node.constructor) { //cancel changes node._param.cancelScheduledValues(0); //reset the value node._param.value = 0; //mark the value as overridden node.overridden = true; } else if (node instanceof AudioParam) { node.cancelScheduledValues(0); node.value = 0; } Tone.prototype.connect.call(this, node, outputNumber, inputNumber); return this; }; return Tone.SignalBase; }); Module(function (Tone) { /** * @class Wraps the native Web Audio API * [WaveShaperNode](http://webaudio.github.io/web-audio-api/#the-waveshapernode-interface). * * @extends {Tone.SignalBase} * @constructor * @param {function|Array|Number} mapping The function used to define the values. * The mapping function should take two arguments: * the first is the value at the current position * and the second is the array position. * If the argument is an array, that array will be * set as the wave shaping function. The input * signal is an AudioRange [-1, 1] value and the output * signal can take on any numerical values. * * @param {Number} [bufferLen=1024] The length of the WaveShaperNode buffer. * @example * var timesTwo = new Tone.WaveShaper(function(val){ * return val * 2; * }, 2048); * @example * //a waveshaper can also be constructed with an array of values * var invert = new Tone.WaveShaper([1, -1]); */ Tone.WaveShaper = function (mapping, bufferLen) { /** * the waveshaper * @type {WaveShaperNode} * @private */ this._shaper = this.input = this.output = this.context.createWaveShaper(); /** * the waveshapers curve * @type {Float32Array} * @private */ this._curve = null; if (Array.isArray(mapping)) { this.curve = mapping; } else if (isFinite(mapping) || this.isUndef(mapping)) { this._curve = new Float32Array(this.defaultArg(mapping, 1024)); } else if (this.isFunction(mapping)) { this._curve = new Float32Array(this.defaultArg(bufferLen, 1024)); this.setMap(mapping); } }; Tone.extend(Tone.WaveShaper, Tone.SignalBase); /** * Uses a mapping function to set the value of the curve. * @param {function} mapping The function used to define the values. * The mapping function take two arguments: * the first is the value at the current position * which goes from -1 to 1 over the number of elements * in the curve array. The second argument is the array position. * @returns {Tone.WaveShaper} this * @example * //map the input signal from [-1, 1] to [0, 10] * shaper.setMap(function(val, index){ * return (val + 1) * 5; * }) */ Tone.WaveShaper.prototype.setMap = function (mapping) { for (var i = 0, len = this._curve.length; i < len; i++) { var normalized = i / len * 2 - 1; this._curve[i] = mapping(normalized, i); } this._shaper.curve = this._curve; return this; }; /** * The array to set as the waveshaper curve. For linear curves * array length does not make much difference, but for complex curves * longer arrays will provide smoother interpolation. * @memberOf Tone.WaveShaper# * @type {Array} * @name curve */ Object.defineProperty(Tone.WaveShaper.prototype, 'curve', { get: function () { return this._shaper.curve; }, set: function (mapping) { this._curve = new Float32Array(mapping); this._shaper.curve = this._curve; } }); /** * Specifies what type of oversampling (if any) should be used when * applying the shaping curve. Can either be "none", "2x" or "4x". * @memberOf Tone.WaveShaper# * @type {string} * @name oversample */ Object.defineProperty(Tone.WaveShaper.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { if ([ 'none', '2x', '4x' ].indexOf(oversampling) !== -1) { this._shaper.oversample = oversampling; } else { throw new Error('invalid oversampling: ' + oversampling); } } }); /** * Clean up. * @returns {Tone.WaveShaper} this */ Tone.WaveShaper.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.disconnect(); this._shaper = null; this._curve = null; return this; }; return Tone.WaveShaper; }); Module(function (Tone) { /////////////////////////////////////////////////////////////////////////// // TYPES /////////////////////////////////////////////////////////////////////////// /** * Units which a value can take on. * @enum {String} */ Tone.Type = { /** * The default value is a number which can take on any value between [-Infinity, Infinity] */ Default: 'number', /** * Time can be described in a number of ways. Read more [Time](https://github.com/Tonejs/Tone.js/wiki/Time). * * <ul> * <li>Numbers, which will be taken literally as the time (in seconds).</li> * <li>Notation, ("4n", "8t") describes time in BPM and time signature relative values.</li> * <li>TransportTime, ("4:3:2") will also provide tempo and time signature relative times * in the form BARS:QUARTERS:SIXTEENTHS.</li> * <li>Frequency, ("8hz") is converted to the length of the cycle in seconds.</li> * <li>Now-Relative, ("+1") prefix any of the above with "+" and it will be interpreted as * "the current time plus whatever expression follows".</li> * <li>Expressions, ("3:0 + 2 - (1m / 7)") any of the above can also be combined * into a mathematical expression which will be evaluated to compute the desired time.</li> * <li>No Argument, for methods which accept time, no argument will be interpreted as * "now" (i.e. the currentTime).</li> * </ul> * * @typedef {Time} */ Time: 'time', /** * Frequency can be described similar to time, except ultimately the * values are converted to frequency instead of seconds. A number * is taken literally as the value in hertz. Additionally any of the * Time encodings can be used. Note names in the form * of NOTE OCTAVE (i.e. C4) are also accepted and converted to their * frequency value. * @typedef {Frequency} */ Frequency: 'frequency', /** * Normal values are within the range [0, 1]. * @typedef {NormalRange} */ NormalRange: 'normalRange', /** * AudioRange values are between [-1, 1]. * @typedef {AudioRange} */ AudioRange: 'audioRange', /** * Decibels are a logarithmic unit of measurement which is useful for volume * because of the logarithmic way that we perceive loudness. 0 decibels * means no change in volume. -10db is approximately half as loud and 10db * is twice is loud. * @typedef {Decibels} */ Decibels: 'db', /** * Half-step note increments, i.e. 12 is an octave above the root. and 1 is a half-step up. * @typedef {Interval} */ Interval: 'interval', /** * Beats per minute. * @typedef {BPM} */ BPM: 'bpm', /** * The value must be greater than or equal to 0. * @typedef {Positive} */ Positive: 'positive', /** * A cent is a hundredth of a semitone. * @typedef {Cents} */ Cents: 'cents', /** * Angle between 0 and 360. * @typedef {Degrees} */ Degrees: 'degrees', /** * A number representing a midi note. * @typedef {MIDI} */ MIDI: 'midi', /** * A colon-separated representation of time in the form of * BARS:QUARTERS:SIXTEENTHS. * @typedef {TransportTime} */ TransportTime: 'transportTime', /** * Ticks are the basic subunit of the Transport. They are * the smallest unit of time that the Transport supports. * @typedef {Ticks} */ Ticks: 'tick', /** * A frequency represented by a letter name, * accidental and octave. This system is known as * [Scientific Pitch Notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation). * @typedef {Note} */ Note: 'note', /** * One millisecond is a thousandth of a second. * @typedef {Milliseconds} */ Milliseconds: 'milliseconds', /** * A string representing a duration relative to a measure. * <ul> * <li>"4n" = quarter note</li> * <li>"2m" = two measures</li> * <li>"8t" = eighth-note triplet</li> * </ul> * @typedef {Notation} */ Notation: 'notation' }; /////////////////////////////////////////////////////////////////////////// // MATCHING TESTS /////////////////////////////////////////////////////////////////////////// /** * Test if a function is "now-relative", i.e. starts with "+". * * @param {String} str The string to test * @return {boolean} * @method isNowRelative * @lends Tone.prototype.isNowRelative */ Tone.prototype.isNowRelative = function () { var nowRelative = new RegExp(/^\s*\+(.)+/i); return function (note) { return nowRelative.test(note); }; }(); /** * Tests if a string is in Ticks notation. * * @param {String} str The string to test * @return {boolean} * @method isTicks * @lends Tone.prototype.isTicks */ Tone.prototype.isTicks = function () { var tickFormat = new RegExp(/^\d+i$/i); return function (note) { return tickFormat.test(note); }; }(); /** * Tests if a string is musical notation. * i.e.: * <ul> * <li>4n = quarter note</li> * <li>2m = two measures</li> * <li>8t = eighth-note triplet</li> * </ul> * * @param {String} str The string to test * @return {boolean} * @method isNotation * @lends Tone.prototype.isNotation */ Tone.prototype.isNotation = function () { var notationFormat = new RegExp(/^[0-9]+[mnt]$/i); return function (note) { return notationFormat.test(note); }; }(); /** * Test if a string is in the transportTime format. * "Bars:Beats:Sixteenths" * @param {String} transportTime * @return {boolean} * @method isTransportTime * @lends Tone.prototype.isTransportTime */ Tone.prototype.isTransportTime = function () { var transportTimeFormat = new RegExp(/^(\d+(\.\d+)?\:){1,2}(\d+(\.\d+)?)?$/i); return function (transportTime) { return transportTimeFormat.test(transportTime); }; }(); /** * Test if a string is in Scientific Pitch Notation: i.e. "C4". * @param {String} note The note to test * @return {boolean} true if it's in the form of a note * @method isNote * @lends Tone.prototype.isNote * @function */ Tone.prototype.isNote = function () { var noteFormat = new RegExp(/^[a-g]{1}(b|#|x|bb)?-?[0-9]+$/i); return function (note) { return noteFormat.test(note); }; }(); /** * Test if the input is in the format of number + hz * i.e.: 10hz * * @param {String} freq * @return {boolean} * @function */ Tone.prototype.isFrequency = function () { var freqFormat = new RegExp(/^\d*\.?\d+hz$/i); return function (freq) { return freqFormat.test(freq); }; }(); /////////////////////////////////////////////////////////////////////////// // TO SECOND CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * @private * @return {Object} The Transport's BPM if the Transport exists, * otherwise returns reasonable defaults. */ function getTransportBpm() { if (Tone.Transport && Tone.Transport.bpm) { return Tone.Transport.bpm.value; } else { return 120; } } /** * @private * @return {Object} The Transport's Time Signature if the Transport exists, * otherwise returns reasonable defaults. */ function getTransportTimeSignature() { if (Tone.Transport && Tone.Transport.timeSignature) { return Tone.Transport.timeSignature; } else { return 4; } } /** * * convert notation format strings to seconds * * @param {String} notation * @param {BPM=} bpm * @param {number=} timeSignature * @return {number} * */ Tone.prototype.notationToSeconds = function (notation, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var beatTime = 60 / bpm; //special case: 1n = 1m if (notation === '1n') { notation = '1m'; } var subdivision = parseInt(notation, 10); var beats = 0; if (subdivision === 0) { beats = 0; } var lastLetter = notation.slice(-1); if (lastLetter === 't') { beats = 4 / subdivision * 2 / 3; } else if (lastLetter === 'n') { beats = 4 / subdivision; } else if (lastLetter === 'm') { beats = subdivision * timeSignature; } else { beats = 0; } return beatTime * beats; }; /** * convert transportTime into seconds. * * ie: 4:2:3 == 4 measures + 2 quarters + 3 sixteenths * * @param {TransportTime} transportTime * @param {BPM=} bpm * @param {number=} timeSignature * @return {number} seconds */ Tone.prototype.transportTimeToSeconds = function (transportTime, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var measures = 0; var quarters = 0; var sixteenths = 0; var split = transportTime.split(':'); if (split.length === 2) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); } else if (split.length === 1) { quarters = parseFloat(split[0]); } else if (split.length === 3) { measures = parseFloat(split[0]); quarters = parseFloat(split[1]); sixteenths = parseFloat(split[2]); } var beats = measures * timeSignature + quarters + sixteenths / 4; return beats * (60 / bpm); }; /** * Convert ticks into seconds * @param {Ticks} ticks * @param {BPM=} bpm * @return {number} seconds */ Tone.prototype.ticksToSeconds = function (ticks, bpm) { if (this.isUndef(Tone.Transport)) { return 0; } ticks = parseFloat(ticks); bpm = this.defaultArg(bpm, getTransportBpm()); var tickTime = 60 / bpm / Tone.Transport.PPQ; return tickTime * ticks; }; /** * Convert a frequency into seconds. * Accepts numbers and strings: i.e. "10hz" or * 10 both return 0.1. * * @param {Frequency} freq * @return {number} */ Tone.prototype.frequencyToSeconds = function (freq) { return 1 / parseFloat(freq); }; /** * Convert a sample count to seconds. * @param {number} samples * @return {number} */ Tone.prototype.samplesToSeconds = function (samples) { return samples / this.context.sampleRate; }; /** * Convert from seconds to samples. * @param {number} seconds * @return {number} The number of samples */ Tone.prototype.secondsToSamples = function (seconds) { return seconds * this.context.sampleRate; }; /////////////////////////////////////////////////////////////////////////// // FROM SECOND CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Convert seconds to transportTime in the form * "measures:quarters:sixteenths" * * @param {Number} seconds * @param {BPM=} bpm * @param {Number=} timeSignature * @return {TransportTime} */ Tone.prototype.secondsToTransportTime = function (seconds, bpm, timeSignature) { bpm = this.defaultArg(bpm, getTransportBpm()); timeSignature = this.defaultArg(timeSignature, getTransportTimeSignature()); var quarterTime = 60 / bpm; var quarters = seconds / quarterTime; var measures = Math.floor(quarters / timeSignature); var sixteenths = quarters % 1 * 4; quarters = Math.floor(quarters) % timeSignature; var progress = [ measures, quarters, sixteenths ]; return progress.join(':'); }; /** * Convert a number in seconds to a frequency. * @param {number} seconds * @return {number} */ Tone.prototype.secondsToFrequency = function (seconds) { return 1 / seconds; }; /////////////////////////////////////////////////////////////////////////// // GENERALIZED CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Convert seconds to the closest transportTime in the form * measures:quarters:sixteenths * * @method toTransportTime * * @param {Time} time * @param {BPM=} bpm * @param {number=} timeSignature * @return {TransportTime} * * @lends Tone.prototype.toTransportTime */ Tone.prototype.toTransportTime = function (time, bpm, timeSignature) { var seconds = this.toSeconds(time); return this.secondsToTransportTime(seconds, bpm, timeSignature); }; /** * Convert a frequency representation into a number. * * @param {Frequency} freq * @param {number=} now if passed in, this number will be * used for all 'now' relative timings * @return {number} the frequency in hertz */ Tone.prototype.toFrequency = function (freq, now) { if (this.isFrequency(freq)) { return parseFloat(freq); } else if (this.isNotation(freq) || this.isTransportTime(freq)) { return this.secondsToFrequency(this.toSeconds(freq, now)); } else if (this.isNote(freq)) { return this.noteToFrequency(freq); } else { return freq; } }; /** * Convert the time representation into ticks. * Now-Relative timing will be relative to the current * Tone.Transport.ticks. * @param {Time} time * @return {Ticks} */ Tone.prototype.toTicks = function (time) { if (this.isUndef(Tone.Transport)) { return 0; } var bpm = Tone.Transport.bpm.value; //get the seconds var plusNow = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusNow = Tone.Transport.ticks; } else if (this.isUndef(time)) { return Tone.Transport.ticks; } var seconds = this.toSeconds(time); var quarter = 60 / bpm; var quarters = seconds / quarter; var tickNum = quarters * Tone.Transport.PPQ; //align the tick value return Math.round(tickNum + plusNow); }; /** * convert a time into samples * * @param {Time} time * @return {number} */ Tone.prototype.toSamples = function (time) { var seconds = this.toSeconds(time); return Math.round(seconds * this.context.sampleRate); }; /** * Convert Time into seconds. * * Unlike the method which it overrides, this takes into account * transporttime and musical notation. * * Time : 1.40 * Notation: 4n|1m|2t * TransportTime: 2:4:1 (measure:quarters:sixteens) * Now Relative: +3n * Math: 3n+16n or even complicated expressions ((3n*2)/6 + 1) * * @override * @param {Time} time * @param {number=} now if passed in, this number will be * used for all 'now' relative timings * @return {number} */ Tone.prototype.toSeconds = function (time, now) { now = this.defaultArg(now, this.now()); if (this.isNumber(time)) { return time; //assuming that it's seconds } else if (this.isString(time)) { var plusTime = 0; if (this.isNowRelative(time)) { time = time.replace('+', ''); plusTime = now; } var betweenParens = time.match(/\(([^)(]+)\)/g); if (betweenParens) { //evaluate the expressions between the parenthesis for (var j = 0; j < betweenParens.length; j++) { //remove the parens var symbol = betweenParens[j].replace(/[\(\)]/g, ''); var symbolVal = this.toSeconds(symbol); time = time.replace(betweenParens[j], symbolVal); } } //test if it is quantized if (time.indexOf('@') !== -1) { var quantizationSplit = time.split('@'); if (!this.isUndef(Tone.Transport)) { var toQuantize = quantizationSplit[0].trim(); //if there's no argument it should be evaluated as the current time if (toQuantize === '') { toQuantize = undefined; } //if it's now-relative, it should be evaluated by `quantize` if (plusTime > 0) { toQuantize = '+' + toQuantize; plusTime = 0; } var subdivision = quantizationSplit[1].trim(); time = Tone.Transport.quantize(toQuantize, subdivision); } else { throw new Error('quantization requires Tone.Transport'); } } else { var components = time.split(/[\(\)\-\+\/\*]/); if (components.length > 1) { var originalTime = time; for (var i = 0; i < components.length; i++) { var symb = components[i].trim(); if (symb !== '') { var val = this.toSeconds(symb); time = time.replace(symb, val); } } try { //eval is evil time = eval(time); // jshint ignore:line } catch (e) { throw new EvalError('cannot evaluate Time: ' + originalTime); } } else if (this.isNotation(time)) { time = this.notationToSeconds(time); } else if (this.isTransportTime(time)) { time = this.transportTimeToSeconds(time); } else if (this.isFrequency(time)) { time = this.frequencyToSeconds(time); } else if (this.isTicks(time)) { time = this.ticksToSeconds(time); } else { time = parseFloat(time); } } return time + plusTime; } else { return now; } }; /** * Convert a Time to Notation. Values will be thresholded to the nearest 128th note. * @param {Time} time * @param {BPM=} bpm * @param {number=} timeSignature * @return {Notation} */ Tone.prototype.toNotation = function (time, bpm, timeSignature) { var testNotations = [ '1m', '2n', '4n', '8n', '16n', '32n', '64n', '128n' ]; var retNotation = toNotationHelper.call(this, time, bpm, timeSignature, testNotations); //try the same thing but with tripelets var testTripletNotations = [ '1m', '2n', '2t', '4n', '4t', '8n', '8t', '16n', '16t', '32n', '32t', '64n', '64t', '128n' ]; var retTripletNotation = toNotationHelper.call(this, time, bpm, timeSignature, testTripletNotations); //choose the simpler expression of the two if (retTripletNotation.split('+').length < retNotation.split('+').length) { return retTripletNotation; } else { return retNotation; } }; /** * Helper method for Tone.toNotation * @private */ function toNotationHelper(time, bpm, timeSignature, testNotations) { var seconds = this.toSeconds(time); var threshold = this.notationToSeconds(testNotations[testNotations.length - 1], bpm, timeSignature); var retNotation = ''; for (var i = 0; i < testNotations.length; i++) { var notationTime = this.notationToSeconds(testNotations[i], bpm, timeSignature); //account for floating point errors (i.e. round up if the value is 0.999999) var multiple = seconds / notationTime; var floatingPointError = 0.000001; if (1 - multiple % 1 < floatingPointError) { multiple += floatingPointError; } multiple = Math.floor(multiple); if (multiple > 0) { if (multiple === 1) { retNotation += testNotations[i]; } else { retNotation += multiple.toString() + '*' + testNotations[i]; } seconds -= multiple * notationTime; if (seconds < threshold) { break; } else { retNotation += ' + '; } } } if (retNotation === '') { retNotation = '0'; } return retNotation; } /** * Convert the given value from the type specified by units * into a number. * @param {*} val the value to convert * @return {Number} the number which the value should be set to */ Tone.prototype.fromUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; /** * Convert a number to the specified units. * @param {number} val the value to convert * @return {number} */ Tone.prototype.toUnits = function (val, units) { if (this.convert || this.isUndef(this.convert)) { switch (units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; /////////////////////////////////////////////////////////////////////////// // FREQUENCY CONVERSIONS /////////////////////////////////////////////////////////////////////////// /** * Note to scale index * @type {Object} */ var noteToScaleIndex = { 'cbb': -2, 'cb': -1, 'c': 0, 'c#': 1, 'cx': 2, 'dbb': 0, 'db': 1, 'd': 2, 'd#': 3, 'dx': 4, 'ebb': 2, 'eb': 3, 'e': 4, 'e#': 5, 'ex': 6, 'fbb': 3, 'fb': 4, 'f': 5, 'f#': 6, 'fx': 7, 'gbb': 5, 'gb': 6, 'g': 7, 'g#': 8, 'gx': 9, 'abb': 7, 'ab': 8, 'a': 9, 'a#': 10, 'ax': 11, 'bbb': 9, 'bb': 10, 'b': 11, 'b#': 12, 'bx': 13 }; /** * scale index to note (sharps) * @type {Array} */ var scaleIndexToNote = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ]; /** * The [concert pitch](https://en.wikipedia.org/wiki/Concert_pitch, * A4's values in Hertz. * @type {Frequency} * @static */ Tone.A4 = 440; /** * Convert a note name to frequency. * @param {String} note * @return {number} * @example * var freq = tone.noteToFrequency("A4"); //returns 440 */ Tone.prototype.noteToFrequency = function (note) { //break apart the note by frequency and octave var parts = note.split(/(-?\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; var noteNumber = index + (parseInt(octave, 10) + 1) * 12; return this.midiToFrequency(noteNumber); } else { return 0; } }; /** * Convert a frequency to a note name (i.e. A4, C#5). * @param {number} freq * @return {String} */ Tone.prototype.frequencyToNote = function (freq) { var log = Math.log(freq / Tone.A4) / Math.LN2; var noteNumber = Math.round(12 * log) + 57; var octave = Math.floor(noteNumber / 12); if (octave < 0) { noteNumber += -12 * octave; } var noteName = scaleIndexToNote[noteNumber % 12]; return noteName + octave.toString(); }; /** * Convert an interval (in semitones) to a frequency ratio. * * @param {Interval} interval the number of semitones above the base note * @return {number} the frequency ratio * @example * tone.intervalToFrequencyRatio(0); // returns 1 * tone.intervalToFrequencyRatio(12); // returns 2 */ Tone.prototype.intervalToFrequencyRatio = function (interval) { return Math.pow(2, interval / 12); }; /** * Convert a midi note number into a note name. * * @param {MIDI} midiNumber the midi note number * @return {String} the note's name and octave * @example * tone.midiToNote(60); // returns "C3" */ Tone.prototype.midiToNote = function (midiNumber) { var octave = Math.floor(midiNumber / 12) - 1; var note = midiNumber % 12; return scaleIndexToNote[note] + octave; }; /** * Convert a note to it's midi value. * * @param {String} note the note name (i.e. "C3") * @return {MIDI} the midi value of that note * @example * tone.noteToMidi("C3"); // returns 60 */ Tone.prototype.noteToMidi = function (note) { //break apart the note by frequency and octave var parts = note.split(/(\d+)/); if (parts.length === 3) { var index = noteToScaleIndex[parts[0].toLowerCase()]; var octave = parts[1]; return index + (parseInt(octave, 10) + 1) * 12; } else { return 0; } }; /** * Convert a MIDI note to frequency value. * * @param {MIDI} midi The midi number to convert. * @return {Frequency} the corresponding frequency value * @example * tone.midiToFrequency(57); // returns 440 */ Tone.prototype.midiToFrequency = function (midi) { return Tone.A4 * Math.pow(2, (midi - 69) / 12); }; return Tone; }); Module(function (Tone) { /** * @class Tone.Param wraps the native Web Audio's AudioParam to provide * additional unit conversion functionality. It also * serves as a base-class for classes which have a single, * automatable parameter. * @extends {Tone} * @param {AudioParam} param The parameter to wrap. * @param {Tone.Type} units The units of the audio param. * @param {Boolean} convert If the param should be converted. */ Tone.Param = function () { var options = this.optionsObject(arguments, [ 'param', 'units', 'convert' ], Tone.Param.defaults); /** * The native parameter to control * @type {AudioParam} * @private */ this._param = this.input = options.param; /** * The units of the parameter * @type {Tone.Type} */ this.units = options.units; /** * If the value should be converted or not * @type {Boolean} */ this.convert = options.convert; /** * True if the signal value is being overridden by * a connected signal. * @readOnly * @type {boolean} * @private */ this.overridden = false; if (!this.isUndef(options.value)) { this.value = options.value; } }; Tone.extend(Tone.Param); /** * Defaults * @type {Object} * @const */ Tone.Param.defaults = { 'units': Tone.Type.Default, 'convert': true, 'param': undefined }; /** * The current value of the parameter. * @memberOf Tone.Param# * @type {Number} * @name value */ Object.defineProperty(Tone.Param.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._param.value = convertedVal; } }); /** * Convert the given value from the type specified by Tone.Param.units * into the destination value (such as Gain or Frequency). * @private * @param {*} val the value to convert * @return {number} the number which the value should be set to */ Tone.Param.prototype._fromUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Time: return this.toSeconds(val); case Tone.Type.Frequency: return this.toFrequency(val); case Tone.Type.Decibels: return this.dbToGain(val); case Tone.Type.NormalRange: return Math.min(Math.max(val, 0), 1); case Tone.Type.AudioRange: return Math.min(Math.max(val, -1), 1); case Tone.Type.Positive: return Math.max(val, 0); default: return val; } } else { return val; } }; /** * Convert the parameters value into the units specified by Tone.Param.units. * @private * @param {number} val the value to convert * @return {number} */ Tone.Param.prototype._toUnits = function (val) { if (this.convert || this.isUndef(this.convert)) { switch (this.units) { case Tone.Type.Decibels: return this.gainToDb(val); default: return val; } } else { return val; } }; /** * the minimum output value * @type {Number} * @private */ Tone.Param.prototype._minOutput = 0.00001; /** * Schedules a parameter value change at the given time. * @param {*} value The value to set the signal. * @param {Time} time The time when the change should occur. * @returns {Tone.Param} this * @example * //set the frequency to "G4" in exactly 1 second from now. * freq.setValueAtTime("G4", "+1"); */ Tone.Param.prototype.setValueAtTime = function (value, time) { value = this._fromUnits(value); this._param.setValueAtTime(value, this.toSeconds(time)); return this; }; /** * Creates a schedule point with the current value at the current time. * This is useful for creating an automation anchor point in order to * schedule changes from the current value. * * @param {number=} now (Optionally) pass the now value in. * @returns {Tone.Param} this */ Tone.Param.prototype.setRampPoint = function (now) { now = this.defaultArg(now, this.now()); var currentVal = this._param.value; this._param.setValueAtTime(currentVal, now); return this; }; /** * Schedules a linear continuous change in parameter value from the * previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.Param} this */ Tone.Param.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); this._param.linearRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; /** * Schedules an exponential continuous change in parameter value from * the previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.Param} this */ Tone.Param.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); this._param.exponentialRampToValueAtTime(value, this.toSeconds(endTime)); return this; }; /** * Schedules an exponential continuous change in parameter value from * the current time and current value to the given value over the * duration of the rampTime. * * @param {number} value The value to ramp to. * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //exponentially ramp to the value 2 over 4 seconds. * signal.exponentialRampToValue(2, 4); */ Tone.Param.prototype.exponentialRampToValue = function (value, rampTime) { var now = this.now(); // exponentialRampToValueAt cannot ever ramp from 0, apparently. // More info: https://bugzilla.mozilla.org/show_bug.cgi?id=1125600#c2 var currentVal = this.value; this.setValueAtTime(Math.max(currentVal, this._minOutput), now); this.exponentialRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; /** * Schedules an linear continuous change in parameter value from * the current time and current value to the given value over the * duration of the rampTime. * * @param {number} value The value to ramp to. * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //linearly ramp to the value 4 over 3 seconds. * signal.linearRampToValue(4, 3); */ Tone.Param.prototype.linearRampToValue = function (value, rampTime) { var now = this.now(); this.setRampPoint(now); this.linearRampToValueAtTime(value, now + this.toSeconds(rampTime)); return this; }; /** * Start exponentially approaching the target value at the given time with * a rate having the given time constant. * @param {number} value * @param {Time} startTime * @param {number} timeConstant * @returns {Tone.Param} this */ Tone.Param.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); // The value will never be able to approach without timeConstant > 0. // http://www.w3.org/TR/webaudio/#dfn-setTargetAtTime, where the equation // is described. 0 results in a division by 0. value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); this._param.setTargetAtTime(value, this.toSeconds(startTime), timeConstant); return this; }; /** * Sets an array of arbitrary parameter values starting at the given time * for the given duration. * * @param {Array} values * @param {Time} startTime * @param {Time} duration * @returns {Tone.Param} this */ Tone.Param.prototype.setValueCurveAtTime = function (values, startTime, duration) { for (var i = 0; i < values.length; i++) { values[i] = this._fromUnits(values[i]); } this._param.setValueCurveAtTime(values, this.toSeconds(startTime), this.toSeconds(duration)); return this; }; /** * Cancels all scheduled parameter changes with times greater than or * equal to startTime. * * @param {Time} startTime * @returns {Tone.Param} this */ Tone.Param.prototype.cancelScheduledValues = function (startTime) { this._param.cancelScheduledValues(this.toSeconds(startTime)); return this; }; /** * Ramps to the given value over the duration of the rampTime. * Automatically selects the best ramp type (exponential or linear) * depending on the `units` of the signal * * @param {number} value * @param {Time} rampTime the time that it takes the * value to ramp from it's current value * @returns {Tone.Param} this * @example * //ramp to the value either linearly or exponentially * //depending on the "units" value of the signal * signal.rampTo(0, 10); */ Tone.Param.prototype.rampTo = function (value, rampTime) { rampTime = this.defaultArg(rampTime, 0); if (this.units === Tone.Type.Frequency || this.units === Tone.Type.BPM) { this.exponentialRampToValue(value, rampTime); } else { this.linearRampToValue(value, rampTime); } return this; }; /** * Clean up * @returns {Tone.Param} this */ Tone.Param.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param = null; return this; }; return Tone.Param; }); Module(function (Tone) { /** * @class A thin wrapper around the Native Web Audio GainNode. * The GainNode is a basic building block of the Web Audio * API and is useful for routing audio and adjusting gains. * @extends {Tone} * @param {Number=} gain The initial gain of the GainNode * @param {Tone.Type=} units The units of the gain parameter. */ Tone.Gain = function () { var options = this.optionsObject(arguments, [ 'gain', 'units' ], Tone.Gain.defaults); /** * The GainNode * @type {GainNode} * @private */ this.input = this.output = this._gainNode = this.context.createGain(); /** * The gain parameter of the gain node. * @type {AudioParam} * @signal */ this.gain = new Tone.Param({ 'param': this._gainNode.gain, 'units': options.units, 'value': options.gain, 'convert': options.convert }); this._readOnly('gain'); }; Tone.extend(Tone.Gain); /** * The defaults * @const * @type {Object} */ Tone.Gain.defaults = { 'gain': 1, 'convert': true }; /** * Clean up. * @return {Tone.Gain} this */ Tone.Gain.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._gainNode.disconnect(); this._gainNode = null; this._writable('gain'); this.gain.dispose(); this.gain = null; }; return Tone.Gain; }); Module(function (Tone) { /** * @class A signal is an audio-rate value. Tone.Signal is a core component of the library. * Unlike a number, Signals can be scheduled with sample-level accuracy. Tone.Signal * has all of the methods available to native Web Audio * [AudioParam](http://webaudio.github.io/web-audio-api/#the-audioparam-interface) * as well as additional conveniences. Read more about working with signals * [here](https://github.com/Tonejs/Tone.js/wiki/Signals). * * @constructor * @extends {Tone.Param} * @param {Number|AudioParam} [value] Initial value of the signal. If an AudioParam * is passed in, that parameter will be wrapped * and controlled by the Signal. * @param {string} [units=Number] unit The units the signal is in. * @example * var signal = new Tone.Signal(10); */ Tone.Signal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); /** * The node where the constant signal value is scaled. * @type {GainNode} * @private */ this.output = this._gain = this.context.createGain(); options.param = this._gain.gain; Tone.Param.call(this, options); /** * The node where the value is set. * @type {Tone.Param} * @private */ this.input = this._param = this._gain.gain; //connect the const output to the node output Tone.Signal._constant.chain(this._gain); }; Tone.extend(Tone.Signal, Tone.Param); /** * The default values * @type {Object} * @static * @const */ Tone.Signal.defaults = { 'value': 0, 'units': Tone.Type.Default, 'convert': true }; /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.SignalBase} this * @method */ Tone.Signal.prototype.connect = Tone.SignalBase.prototype.connect; /** * dispose and disconnect * @returns {Tone.Signal} this */ Tone.Signal.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._param = null; this._gain.disconnect(); this._gain = null; return this; }; /////////////////////////////////////////////////////////////////////////// // STATIC /////////////////////////////////////////////////////////////////////////// /** * Generates a constant output of 1. * @static * @private * @const * @type {AudioBufferSourceNode} */ Tone.Signal._constant = null; /** * initializer function */ Tone._initAudioContext(function (audioContext) { var buffer = audioContext.createBuffer(1, 128, audioContext.sampleRate); var arr = buffer.getChannelData(0); for (var i = 0; i < arr.length; i++) { arr[i] = 1; } Tone.Signal._constant = audioContext.createBufferSource(); Tone.Signal._constant.channelCount = 1; Tone.Signal._constant.channelCountMode = 'explicit'; Tone.Signal._constant.buffer = buffer; Tone.Signal._constant.loop = true; Tone.Signal._constant.start(0); Tone.Signal._constant.noGC(); }); return Tone.Signal; }); Module(function (Tone) { /** * @class A Timeline class for scheduling and maintaining state * along a timeline. All events must have a "time" property. * Internally, events are stored in time order for fast * retrieval. * @extends {Tone} * @param {Positive} [memory=Infinity] The number of previous events that are retained. */ Tone.Timeline = function () { var options = this.optionsObject(arguments, ['memory'], Tone.Timeline.defaults); /** * The array of scheduled timeline events * @type {Array} * @private */ this._timeline = []; /** * An array of items to remove from the list. * @type {Array} * @private */ this._toRemove = []; /** * Flag if the tieline is mid iteration * @private * @type {Boolean} */ this._iterating = false; /** * The memory of the timeline, i.e. * how many events in the past it will retain * @type {Positive} */ this.memory = options.memory; }; Tone.extend(Tone.Timeline); /** * the default parameters * @static * @const */ Tone.Timeline.defaults = { 'memory': Infinity }; /** * The number of items in the timeline. * @type {Number} * @memberOf Tone.Timeline# * @name length * @readOnly */ Object.defineProperty(Tone.Timeline.prototype, 'length', { get: function () { return this._timeline.length; } }); /** * Insert an event object onto the timeline. Events must have a "time" attribute. * @param {Object} event The event object to insert into the * timeline. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.addEvent = function (event) { //the event needs to have a time attribute if (this.isUndef(event.time)) { throw new Error('events must have a time attribute'); } event.time = this.toSeconds(event.time); if (this._timeline.length) { var index = this._search(event.time); this._timeline.splice(index + 1, 0, event); } else { this._timeline.push(event); } //if the length is more than the memory, remove the previous ones if (this.length > this.memory) { var diff = this.length - this.memory; this._timeline.splice(0, diff); } return this; }; /** * Remove an event from the timeline. * @param {Object} event The event object to remove from the list. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.removeEvent = function (event) { if (this._iterating) { this._toRemove.push(event); } else { var index = this._timeline.indexOf(event); if (index !== -1) { this._timeline.splice(index, 1); } } return this; }; /** * Get the event whose time is less than or equal to the given time. * @param {Number} time The time to query. * @returns {Object} The event object set after that time. */ Tone.Timeline.prototype.getEvent = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index !== -1) { return this._timeline[index]; } else { return null; } }; /** * Get the event which is scheduled after the given time. * @param {Number} time The time to query. * @returns {Object} The event object after the given time */ Tone.Timeline.prototype.getEventAfter = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index + 1 < this._timeline.length) { return this._timeline[index + 1]; } else { return null; } }; /** * Get the event before the event at the given time. * @param {Number} time The time to query. * @returns {Object} The event object before the given time */ Tone.Timeline.prototype.getEventBefore = function (time) { time = this.toSeconds(time); var index = this._search(time); if (index - 1 >= 0) { return this._timeline[index - 1]; } else { return null; } }; /** * Cancel events after the given time * @param {Time} time The time to query. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.cancel = function (after) { if (this._timeline.length > 1) { after = this.toSeconds(after); var index = this._search(after); if (index >= 0) { this._timeline = this._timeline.slice(0, index); } else { this._timeline = []; } } else if (this._timeline.length === 1) { //the first item's time if (this._timeline[0].time >= after) { this._timeline = []; } } return this; }; /** * Cancel events before or equal to the given time. * @param {Time} time The time to cancel before. * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.cancelBefore = function (time) { if (this._timeline.length) { time = this.toSeconds(time); var index = this._search(time); if (index >= 0) { this._timeline = this._timeline.slice(index + 1); } } return this; }; /** * Does a binary serach on the timeline array and returns the * event which is after or equal to the time. * @param {Number} time * @return {Number} the index in the timeline array * @private */ Tone.Timeline.prototype._search = function (time) { var beginning = 0; var len = this._timeline.length; var end = len; // continue searching while [imin,imax] is not empty while (beginning <= end && beginning < len) { // calculate the midpoint for roughly equal partition var midPoint = Math.floor(beginning + (end - beginning) / 2); var event = this._timeline[midPoint]; if (event.time === time) { //choose the last one that has the same time for (var i = midPoint; i < this._timeline.length; i++) { var testEvent = this._timeline[i]; if (testEvent.time === time) { midPoint = i; } } return midPoint; } else if (event.time > time) { //search lower end = midPoint - 1; } else if (event.time < time) { //search upper beginning = midPoint + 1; } } return beginning - 1; }; /** * Internal iterator. Applies extra safety checks for * removing items from the array. * @param {Function} callback * @param {Number=} lowerBound * @param {Number=} upperBound * @private */ Tone.Timeline.prototype._iterate = function (callback, lowerBound, upperBound) { this._iterating = true; lowerBound = this.defaultArg(lowerBound, 0); upperBound = this.defaultArg(upperBound, this._timeline.length - 1); for (var i = lowerBound; i <= upperBound; i++) { callback(this._timeline[i]); } this._iterating = false; if (this._toRemove.length > 0) { for (var j = 0; j < this._toRemove.length; j++) { var index = this._timeline.indexOf(this._toRemove[j]); if (index !== -1) { this._timeline.splice(index, 1); } } this._toRemove = []; } }; /** * Iterate over everything in the array * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEach = function (callback) { this._iterate(callback); return this; }; /** * Iterate over everything in the array at or before the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachBefore = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(callback, 0, upperBound); } return this; }; /** * Iterate over everything in the array after the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachAfter = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var lowerBound = this._search(time); this._iterate(callback, lowerBound + 1); return this; }; /** * Iterate over everything in the array at or after the given time. Similar to * forEachAfter, but includes the item(s) at the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachFrom = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var lowerBound = this._search(time); //work backwards until the event time is less than time while (lowerBound >= 0 && this._timeline[lowerBound].time >= time) { lowerBound--; } this._iterate(callback, lowerBound + 1); return this; }; /** * Iterate over everything in the array at the given time * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.Timeline} this */ Tone.Timeline.prototype.forEachAtTime = function (time, callback) { //iterate over the items in reverse so that removing an item doesn't break things time = this.toSeconds(time); var upperBound = this._search(time); if (upperBound !== -1) { this._iterate(function (event) { if (event.time === time) { callback(event); } }, 0, upperBound); } return this; }; /** * Clean up. * @return {Tone.Timeline} this */ Tone.Timeline.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._timeline = null; this._toRemove = null; }; return Tone.Timeline; }); Module(function (Tone) { /** * @class A signal which adds the method getValueAtTime. * Code and inspiration from https://github.com/jsantell/web-audio-automation-timeline * @extends {Tone.Param} * @param {Number=} value The initial value of the signal * @param {String=} units The conversion units of the signal. */ Tone.TimelineSignal = function () { var options = this.optionsObject(arguments, [ 'value', 'units' ], Tone.Signal.defaults); //constructors Tone.Signal.apply(this, options); options.param = this._param; Tone.Param.call(this, options); /** * The scheduled events * @type {Tone.Timeline} * @private */ this._events = new Tone.Timeline(10); /** * The initial scheduled value * @type {Number} * @private */ this._initial = this._fromUnits(this._param.value); }; Tone.extend(Tone.TimelineSignal, Tone.Param); /** * The event types of a schedulable signal. * @enum {String} */ Tone.TimelineSignal.Type = { Linear: 'linear', Exponential: 'exponential', Target: 'target', Set: 'set' }; /** * The current value of the signal. * @memberOf Tone.TimelineSignal# * @type {Number} * @name value */ Object.defineProperty(Tone.TimelineSignal.prototype, 'value', { get: function () { return this._toUnits(this._param.value); }, set: function (value) { var convertedVal = this._fromUnits(value); this._initial = convertedVal; this._param.value = convertedVal; } }); /////////////////////////////////////////////////////////////////////////// // SCHEDULING /////////////////////////////////////////////////////////////////////////// /** * Schedules a parameter value change at the given time. * @param {*} value The value to set the signal. * @param {Time} time The time when the change should occur. * @returns {Tone.TimelineSignal} this * @example * //set the frequency to "G4" in exactly 1 second from now. * freq.setValueAtTime("G4", "+1"); */ Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) { value = this._fromUnits(value); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Set, 'value': value, 'time': startTime }); //invoke the original event this._param.setValueAtTime(value, startTime); return this; }; /** * Schedules a linear continuous change in parameter value from the * previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Linear, 'value': value, 'time': endTime }); this._param.linearRampToValueAtTime(value, endTime); return this; }; /** * Schedules an exponential continuous change in parameter value from * the previous scheduled parameter value to the given value. * * @param {number} value * @param {Time} endTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); endTime = this.toSeconds(endTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Exponential, 'value': value, 'time': endTime }); this._param.exponentialRampToValueAtTime(value, endTime); return this; }; /** * Start exponentially approaching the target value at the given time with * a rate having the given time constant. * @param {number} value * @param {Time} startTime * @param {number} timeConstant * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) { value = this._fromUnits(value); value = Math.max(this._minOutput, value); timeConstant = Math.max(this._minOutput, timeConstant); startTime = this.toSeconds(startTime); this._events.addEvent({ 'type': Tone.TimelineSignal.Type.Target, 'value': value, 'time': startTime, 'constant': timeConstant }); this._param.setTargetAtTime(value, startTime, timeConstant); return this; }; /** * Cancels all scheduled parameter changes with times greater than or * equal to startTime. * * @param {Time} startTime * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) { this._events.cancel(after); this._param.cancelScheduledValues(this.toSeconds(after)); return this; }; /** * Sets the computed value at the given time. This provides * a point from which a linear or exponential curve * can be scheduled after. Will cancel events after * the given time and shorten the currently scheduled * linear or exponential ramp so that it ends at `time` . * This is to avoid discontinuities and clicks in envelopes. * @param {Time} time When to set the ramp point * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.setRampPoint = function (time) { time = this.toSeconds(time); //get the value at the given time var val = this.getValueAtTime(time); //reschedule the next event to end at the given time var after = this._searchAfter(time); if (after) { //cancel the next event(s) this.cancelScheduledValues(time); if (after.type === Tone.TimelineSignal.Type.Linear) { this.linearRampToValueAtTime(val, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { this.exponentialRampToValueAtTime(val, time); } } this.setValueAtTime(val, time); return this; }; /** * Do a linear ramp to the given value between the start and finish times. * @param {Number} value The value to ramp to. * @param {Time} start The beginning anchor point to do the linear ramp * @param {Time} finish The ending anchor point by which the value of * the signal will equal the given value. * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.linearRampToValueAtTime(value, finish); return this; }; /** * Do a exponential ramp to the given value between the start and finish times. * @param {Number} value The value to ramp to. * @param {Time} start The beginning anchor point to do the exponential ramp * @param {Time} finish The ending anchor point by which the value of * the signal will equal the given value. * @returns {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) { this.setRampPoint(start); this.exponentialRampToValueAtTime(value, finish); return this; }; /////////////////////////////////////////////////////////////////////////// // GETTING SCHEDULED VALUES /////////////////////////////////////////////////////////////////////////// /** * Returns the value before or equal to the given time * @param {Number} time The time to query * @return {Object} The event at or before the given time. * @private */ Tone.TimelineSignal.prototype._searchBefore = function (time) { return this._events.getEvent(time); }; /** * The event after the given time * @param {Number} time The time to query. * @return {Object} The next event after the given time * @private */ Tone.TimelineSignal.prototype._searchAfter = function (time) { return this._events.getEventAfter(time); }; /** * Get the scheduled value at the given time. This will * return the unconverted (raw) value. * @param {Number} time The time in seconds. * @return {Number} The scheduled value at the given time. */ Tone.TimelineSignal.prototype.getValueAtTime = function (time) { var after = this._searchAfter(time); var before = this._searchBefore(time); var value = this._initial; //if it was set by if (before === null) { value = this._initial; } else if (before.type === Tone.TimelineSignal.Type.Target) { var previous = this._events.getEventBefore(before.time); var previouVal; if (previous === null) { previouVal = this._initial; } else { previouVal = previous.value; } value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time); } else if (after === null) { value = before.value; } else if (after.type === Tone.TimelineSignal.Type.Linear) { value = this._linearInterpolate(before.time, before.value, after.time, after.value, time); } else if (after.type === Tone.TimelineSignal.Type.Exponential) { value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time); } else { value = before.value; } return value; }; /** * When signals connect to other signals or AudioParams, * they take over the output value of that signal or AudioParam. * For all other nodes, the behavior is the same as a default <code>connect</code>. * * @override * @param {AudioParam|AudioNode|Tone.Signal|Tone} node * @param {number} [outputNumber=0] The output number to connect from. * @param {number} [inputNumber=0] The input number to connect to. * @returns {Tone.TimelineSignal} this * @method */ Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect; /////////////////////////////////////////////////////////////////////////// // AUTOMATION CURVE CALCULATIONS // MIT License, copyright (c) 2014 Jordan Santell /////////////////////////////////////////////////////////////////////////// /** * Calculates the the value along the curve produced by setTargetAtTime * @private */ Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) { return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant); }; /** * Calculates the the value along the curve produced by linearRampToValueAtTime * @private */ Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) { return v0 + (v1 - v0) * ((t - t0) / (t1 - t0)); }; /** * Calculates the the value along the curve produced by exponentialRampToValueAtTime * @private */ Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) { v0 = Math.max(this._minOutput, v0); return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0)); }; /** * Clean up. * @return {Tone.TimelineSignal} this */ Tone.TimelineSignal.prototype.dispose = function () { Tone.Signal.prototype.dispose.call(this); Tone.Param.prototype.dispose.call(this); this._events.dispose(); this._events = null; }; return Tone.TimelineSignal; }); Module(function (Tone) { /** * @class Pow applies an exponent to the incoming signal. The incoming signal * must be AudioRange. * * @extends {Tone.SignalBase} * @constructor * @param {Positive} exp The exponent to apply to the incoming signal, must be at least 2. * @example * var pow = new Tone.Pow(2); * var sig = new Tone.Signal(0.5).connect(pow); * //output of pow is 0.25. */ Tone.Pow = function (exp) { /** * the exponent * @private * @type {number} */ this._exp = this.defaultArg(exp, 1); /** * @type {WaveShaperNode} * @private */ this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192); }; Tone.extend(Tone.Pow, Tone.SignalBase); /** * The value of the exponent. * @memberOf Tone.Pow# * @type {number} * @name value */ Object.defineProperty(Tone.Pow.prototype, 'value', { get: function () { return this._exp; }, set: function (exp) { this._exp = exp; this._expScaler.setMap(this._expFunc(this._exp)); } }); /** * the function which maps the waveshaper * @param {number} exp * @return {function} * @private */ Tone.Pow.prototype._expFunc = function (exp) { return function (val) { return Math.pow(Math.abs(val), exp); }; }; /** * Clean up. * @returns {Tone.Pow} this */ Tone.Pow.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._expScaler.dispose(); this._expScaler = null; return this; }; return Tone.Pow; }); Module(function (Tone) { /** * @class Tone.Envelope is an [ADSR](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope) * envelope generator. Tone.Envelope outputs a signal which * can be connected to an AudioParam or Tone.Signal. * <img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/ADSR_parameter.svg"> * * @constructor * @extends {Tone} * @param {Time} [attack] The amount of time it takes for the envelope to go from * 0 to it's maximum value. * @param {Time} [decay] The period of time after the attack that it takes for the envelope * to fall to the sustain value. * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until * the release is triggered. * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. * @example * //an amplitude envelope * var gainNode = Tone.context.createGain(); * var env = new Tone.Envelope({ * "attack" : 0.1, * "decay" : 0.2, * "sustain" : 1, * "release" : 0.8, * }); * env.connect(gainNode.gain); */ Tone.Envelope = function () { //get all of the defaults var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); /** * When triggerAttack is called, the attack time is the amount of * time it takes for the envelope to reach it's maximum value. * @type {Time} */ this.attack = options.attack; /** * After the attack portion of the envelope, the value will fall * over the duration of the decay time to it's sustain value. * @type {Time} */ this.decay = options.decay; /** * The sustain value is the value * which the envelope rests at after triggerAttack is * called, but before triggerRelease is invoked. * @type {NormalRange} */ this.sustain = options.sustain; /** * After triggerRelease is called, the envelope's * value will fall to it's miminum value over the * duration of the release time. * @type {Time} */ this.release = options.release; /** * the next time the envelope is at standby * @type {number} * @private */ this._attackCurve = Tone.Envelope.Type.Linear; /** * the next time the envelope is at standby * @type {number} * @private */ this._releaseCurve = Tone.Envelope.Type.Exponential; /** * the minimum output value * @type {number} * @private */ this._minOutput = 0.00001; /** * the signal * @type {Tone.TimelineSignal} * @private */ this._sig = this.output = new Tone.TimelineSignal(); this._sig.setValueAtTime(this._minOutput, 0); //set the attackCurve initially this.attackCurve = options.attackCurve; this.releaseCurve = options.releaseCurve; }; Tone.extend(Tone.Envelope); /** * the default parameters * @static * @const */ Tone.Envelope.defaults = { 'attack': 0.01, 'decay': 0.1, 'sustain': 0.5, 'release': 1, 'attackCurve': 'linear', 'releaseCurve': 'exponential' }; /** * the envelope time multipler * @type {number} * @private */ Tone.Envelope.prototype._timeMult = 0.25; /** * Read the current value of the envelope. Useful for * syncronizing visual output to the envelope. * @memberOf Tone.Envelope# * @type {Number} * @name value * @readOnly */ Object.defineProperty(Tone.Envelope.prototype, 'value', { get: function () { return this._sig.value; } }); /** * The slope of the attack. Either "linear" or "exponential". * @memberOf Tone.Envelope# * @type {string} * @name attackCurve * @example * env.attackCurve = "linear"; */ Object.defineProperty(Tone.Envelope.prototype, 'attackCurve', { get: function () { return this._attackCurve; }, set: function (type) { if (type === Tone.Envelope.Type.Linear || type === Tone.Envelope.Type.Exponential) { this._attackCurve = type; } else { throw Error('attackCurve must be either "linear" or "exponential". Invalid type: ', type); } } }); /** * The slope of the Release. Either "linear" or "exponential". * @memberOf Tone.Envelope# * @type {string} * @name releaseCurve * @example * env.releaseCurve = "linear"; */ Object.defineProperty(Tone.Envelope.prototype, 'releaseCurve', { get: function () { return this._releaseCurve; }, set: function (type) { if (type === Tone.Envelope.Type.Linear || type === Tone.Envelope.Type.Exponential) { this._releaseCurve = type; } else { throw Error('releaseCurve must be either "linear" or "exponential". Invalid type: ', type); } } }); /** * Trigger the attack/decay portion of the ADSR envelope. * @param {Time} [time=now] When the attack should start. * @param {NormalRange} [velocity=1] The velocity of the envelope scales the vales. * number between 0-1 * @returns {Tone.Envelope} this * @example * //trigger the attack 0.5 seconds from now with a velocity of 0.2 * env.triggerAttack("+0.5", 0.2); */ Tone.Envelope.prototype.triggerAttack = function (time, velocity) { //to seconds var now = this.now() + this.blockTime; time = this.toSeconds(time, now); var attack = this.toSeconds(this.attack) + time; var decay = this.toSeconds(this.decay); velocity = this.defaultArg(velocity, 1); //attack if (this._attackCurve === Tone.Envelope.Type.Linear) { this._sig.linearRampToValueBetween(velocity, time, attack); } else { this._sig.exponentialRampToValueBetween(velocity, time, attack); } //decay this._sig.setValueAtTime(velocity, attack); this._sig.exponentialRampToValueAtTime(this.sustain * velocity, attack + decay); return this; }; /** * Triggers the release of the envelope. * @param {Time} [time=now] When the release portion of the envelope should start. * @returns {Tone.Envelope} this * @example * //trigger release immediately * env.triggerRelease(); */ Tone.Envelope.prototype.triggerRelease = function (time) { var now = this.now() + this.blockTime; time = this.toSeconds(time, now); var release = this.toSeconds(this.release); if (this._releaseCurve === Tone.Envelope.Type.Linear) { this._sig.linearRampToValueBetween(this._minOutput, time, time + release); } else { this._sig.exponentialRampToValueBetween(this._minOutput, time, release + time); } return this; }; /** * triggerAttackRelease is shorthand for triggerAttack, then waiting * some duration, then triggerRelease. * @param {Time} duration The duration of the sustain. * @param {Time} [time=now] When the attack should be triggered. * @param {number} [velocity=1] The velocity of the envelope. * @returns {Tone.Envelope} this * @example * //trigger the attack and then the release after 0.6 seconds. * env.triggerAttackRelease(0.6); */ Tone.Envelope.prototype.triggerAttackRelease = function (duration, time, velocity) { time = this.toSeconds(time); this.triggerAttack(time, velocity); this.triggerRelease(time + this.toSeconds(duration)); return this; }; /** * Borrows the connect method from Tone.Signal. * @function * @private */ Tone.Envelope.prototype.connect = Tone.Signal.prototype.connect; /** * Disconnect and dispose. * @returns {Tone.Envelope} this */ Tone.Envelope.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sig.dispose(); this._sig = null; return this; }; /** * The phase of the envelope. * @enum {string} */ Tone.Envelope.Phase = { Attack: 'attack', Decay: 'decay', Sustain: 'sustain', Release: 'release', Standby: 'standby' }; /** * The phase of the envelope. * @enum {string} */ Tone.Envelope.Type = { Linear: 'linear', Exponential: 'exponential' }; return Tone.Envelope; }); Module(function (Tone) { /** * @class Tone.AmplitudeEnvelope is a Tone.Envelope connected to a gain node. * Unlike Tone.Envelope, which outputs the envelope's value, Tone.AmplitudeEnvelope accepts * an audio signal as the input and will apply the envelope to the amplitude * of the signal. Read more about ADSR Envelopes on [Wikipedia](https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope). * * @constructor * @extends {Tone.Envelope} * @param {Time|Object} [attack] The amount of time it takes for the envelope to go from * 0 to it's maximum value. * @param {Time} [decay] The period of time after the attack that it takes for the envelope * to fall to the sustain value. * @param {NormalRange} [sustain] The percent of the maximum value that the envelope rests at until * the release is triggered. * @param {Time} [release] The amount of time after the release is triggered it takes to reach 0. * @example * var ampEnv = new Tone.AmplitudeEnvelope({ * "attack": 0.1, * "decay": 0.2, * "sustain": 1.0, * "release": 0.8 * }).toMaster(); * //create an oscillator and connect it * var osc = new Tone.Oscillator().connect(ampEnv).start(); * //trigger the envelopes attack and release "8t" apart * ampEnv.triggerAttackRelease("8t"); */ Tone.AmplitudeEnvelope = function () { Tone.Envelope.apply(this, arguments); /** * the input node * @type {GainNode} * @private */ this.input = this.output = new Tone.Gain(); this._sig.connect(this.output.gain); }; Tone.extend(Tone.AmplitudeEnvelope, Tone.Envelope); /** * Clean up * @return {Tone.AmplitudeEnvelope} this */ Tone.AmplitudeEnvelope.prototype.dispose = function () { this.input.dispose(); this.input = null; Tone.Envelope.prototype.dispose.call(this); return this; }; return Tone.AmplitudeEnvelope; }); Module(function (Tone) { /** * @class Wrapper around the native Web Audio's * [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode). * Extracts FFT or Waveform data from the incoming signal. * @extends {Tone} * @param {Number=} size The size of the FFT. Value must be a power of * two in the range 32 to 32768. * @param {String=} type The return type of the analysis, either "fft", or "waveform". */ Tone.Analyser = function () { var options = this.optionsObject(arguments, [ 'size', 'type' ], Tone.Analyser.defaults); /** * The analyser node. * @private * @type {AnalyserNode} */ this._analyser = this.input = this.context.createAnalyser(); /** * The analysis type * @type {String} * @private */ this._type = options.type; /** * The return type of the analysis * @type {String} * @private */ this._returnType = options.returnType; /** * The buffer that the FFT data is written to * @type {TypedArray} * @private */ this._buffer = null; //set the values initially this.size = options.size; this.type = options.type; this.returnType = options.returnType; this.minDecibels = options.minDecibels; this.maxDecibels = options.maxDecibels; }; Tone.extend(Tone.Analyser); /** * The default values. * @type {Object} * @const */ Tone.Analyser.defaults = { 'size': 2048, 'returnType': 'byte', 'type': 'fft', 'smoothing': 0.8, 'maxDecibels': -30, 'minDecibels': -100 }; /** * Possible return types of Tone.Analyser.value * @enum {String} */ Tone.Analyser.Type = { Waveform: 'waveform', FFT: 'fft' }; /** * Possible return types of Tone.Analyser.value * @enum {String} */ Tone.Analyser.ReturnType = { Byte: 'byte', Float: 'float' }; /** * Run the analysis given the current settings and return the * result as a TypedArray. * @returns {TypedArray} */ Tone.Analyser.prototype.analyse = function () { if (this._type === Tone.Analyser.Type.FFT) { if (this._returnType === Tone.Analyser.ReturnType.Byte) { this._analyser.getByteFrequencyData(this._buffer); } else { this._analyser.getFloatFrequencyData(this._buffer); } } else if (this._type === Tone.Analyser.Type.Waveform) { if (this._returnType === Tone.Analyser.ReturnType.Byte) { this._analyser.getByteTimeDomainData(this._buffer); } else { this._analyser.getFloatTimeDomainData(this._buffer); } } return this._buffer; }; /** * The size of analysis. This must be a power of two in the range 32 to 32768. * @memberOf Tone.Analyser# * @type {Number} * @name size */ Object.defineProperty(Tone.Analyser.prototype, 'size', { get: function () { return this._analyser.frequencyBinCount; }, set: function (size) { this._analyser.fftSize = size * 2; this.type = this._type; } }); /** * The return type of Tone.Analyser.value, either "byte" or "float". * When the type is set to "byte" the range of values returned in the array * are between 0-255, when set to "float" the values are between 0-1. * @memberOf Tone.Analyser# * @type {String} * @name type */ Object.defineProperty(Tone.Analyser.prototype, 'returnType', { get: function () { return this._returnType; }, set: function (type) { if (type === Tone.Analyser.ReturnType.Byte) { this._buffer = new Uint8Array(this._analyser.frequencyBinCount); } else if (type === Tone.Analyser.ReturnType.Float) { this._buffer = new Float32Array(this._analyser.frequencyBinCount); } else { throw new Error('Invalid Return Type: ' + type); } this._returnType = type; } }); /** * The analysis function returned by Tone.Analyser.value, either "fft" or "waveform". * @memberOf Tone.Analyser# * @type {String} * @name type */ Object.defineProperty(Tone.Analyser.prototype, 'type', { get: function () { return this._type; }, set: function (type) { if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT) { throw new Error('Invalid Type: ' + type); } this._type = type; } }); /** * 0 represents no time averaging with the last analysis frame. * @memberOf Tone.Analyser# * @type {NormalRange} * @name smoothing */ Object.defineProperty(Tone.Analyser.prototype, 'smoothing', { get: function () { return this._analyser.smoothingTimeConstant; }, set: function (val) { this._analyser.smoothingTimeConstant = val; } }); /** * The smallest decibel value which is analysed by the FFT. * @memberOf Tone.Analyser# * @type {Decibels} * @name minDecibels */ Object.defineProperty(Tone.Analyser.prototype, 'minDecibels', { get: function () { return this._analyser.minDecibels; }, set: function (val) { this._analyser.minDecibels = val; } }); /** * The largest decibel value which is analysed by the FFT. * @memberOf Tone.Analyser# * @type {Decibels} * @name maxDecibels */ Object.defineProperty(Tone.Analyser.prototype, 'maxDecibels', { get: function () { return this._analyser.maxDecibels; }, set: function (val) { this._analyser.maxDecibels = val; } }); /** * Clean up. * @return {Tone.Analyser} this */ Tone.Analyser.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._analyser.disconnect(); this._analyser = null; this._buffer = null; }; return Tone.Analyser; }); Module(function (Tone) { /** * @class Tone.Compressor is a thin wrapper around the Web Audio * [DynamicsCompressorNode](http://webaudio.github.io/web-audio-api/#the-dynamicscompressornode-interface). * Compression reduces the volume of loud sounds or amplifies quiet sounds * by narrowing or "compressing" an audio signal's dynamic range. * Read more on [Wikipedia](https://en.wikipedia.org/wiki/Dynamic_range_compression). * * @extends {Tone} * @constructor * @param {Decibels|Object} [threshold] The value above which the compression starts to be applied. * @param {Positive} [ratio] The gain reduction ratio. * @example * var comp = new Tone.Compressor(-30, 3); */ Tone.Compressor = function () { var options = this.optionsObject(arguments, [ 'threshold', 'ratio' ], Tone.Compressor.defaults); /** * the compressor node * @type {DynamicsCompressorNode} * @private */ this._compressor = this.input = this.output = this.context.createDynamicsCompressor(); /** * the threshold vaue * @type {Decibels} * @signal */ this.threshold = this._compressor.threshold; /** * The attack parameter * @type {Time} * @signal */ this.attack = new Tone.Param(this._compressor.attack, Tone.Type.Time); /** * The release parameter * @type {Time} * @signal */ this.release = new Tone.Param(this._compressor.release, Tone.Type.Time); /** * The knee parameter * @type {Decibels} * @signal */ this.knee = this._compressor.knee; /** * The ratio value * @type {Number} * @signal */ this.ratio = this._compressor.ratio; //set the defaults this._readOnly([ 'knee', 'release', 'attack', 'ratio', 'threshold' ]); this.set(options); }; Tone.extend(Tone.Compressor); /** * @static * @const * @type {Object} */ Tone.Compressor.defaults = { 'ratio': 12, 'threshold': -24, 'release': 0.25, 'attack': 0.003, 'knee': 30 }; /** * clean up * @returns {Tone.Compressor} this */ Tone.Compressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'knee', 'release', 'attack', 'ratio', 'threshold' ]); this._compressor.disconnect(); this._compressor = null; this.attack.dispose(); this.attack = null; this.release.dispose(); this.release = null; this.threshold = null; this.ratio = null; this.knee = null; return this; }; return Tone.Compressor; }); Module(function (Tone) { /** * @class Add a signal and a number or two signals. When no value is * passed into the constructor, Tone.Add will sum <code>input[0]</code> * and <code>input[1]</code>. If a value is passed into the constructor, * the it will be added to the input. * * @constructor * @extends {Tone.Signal} * @param {number=} value If no value is provided, Tone.Add will sum the first * and second inputs. * @example * var signal = new Tone.Signal(2); * var add = new Tone.Add(2); * signal.connect(add); * //the output of add equals 4 * @example * //if constructed with no arguments * //it will add the first and second inputs * var add = new Tone.Add(); * var sig0 = new Tone.Signal(3).connect(add, 0, 0); * var sig1 = new Tone.Signal(4).connect(add, 0, 1); * //the output of add equals 7. */ Tone.Add = function (value) { Tone.call(this, 2, 0); /** * the summing node * @type {GainNode} * @private */ this._sum = this.input[0] = this.input[1] = this.output = this.context.createGain(); /** * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); this._param.connect(this._sum); }; Tone.extend(Tone.Add, Tone.Signal); /** * Clean up. * @returns {Tone.Add} this */ Tone.Add.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sum.disconnect(); this._sum = null; this._param.dispose(); this._param = null; return this; }; return Tone.Add; }); Module(function (Tone) { /** * @class Multiply two incoming signals. Or, if a number is given in the constructor, * multiplies the incoming signal by that value. * * @constructor * @extends {Tone.Signal} * @param {number=} value Constant value to multiple. If no value is provided, * it will return the product of the first and second inputs * @example * var mult = new Tone.Multiply(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(mult, 0, 0); * sigB.connect(mult, 0, 1); * //output of mult is 12. * @example * var mult = new Tone.Multiply(10); * var sig = new Tone.Signal(2).connect(mult); * //the output of mult is 20. */ Tone.Multiply = function (value) { Tone.call(this, 2, 0); /** * the input node is the same as the output node * it is also the GainNode which handles the scaling of incoming signal * * @type {GainNode} * @private */ this._mult = this.input[0] = this.output = this.context.createGain(); /** * the scaling parameter * @type {AudioParam} * @private */ this._param = this.input[1] = this.output.gain; this._param.value = this.defaultArg(value, 0); }; Tone.extend(Tone.Multiply, Tone.Signal); /** * clean up * @returns {Tone.Multiply} this */ Tone.Multiply.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._mult.disconnect(); this._mult = null; this._param = null; return this; }; return Tone.Multiply; }); Module(function (Tone) { /** * @class Negate the incoming signal. i.e. an input signal of 10 will output -10 * * @constructor * @extends {Tone.SignalBase} * @example * var neg = new Tone.Negate(); * var sig = new Tone.Signal(-2).connect(neg); * //output of neg is positive 2. */ Tone.Negate = function () { /** * negation is done by multiplying by -1 * @type {Tone.Multiply} * @private */ this._multiply = this.input = this.output = new Tone.Multiply(-1); }; Tone.extend(Tone.Negate, Tone.SignalBase); /** * clean up * @returns {Tone.Negate} this */ Tone.Negate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._multiply.dispose(); this._multiply = null; return this; }; return Tone.Negate; }); Module(function (Tone) { /** * @class Subtract the signal connected to <code>input[1]</code> from the signal connected * to <code>input[0]</code>. If an argument is provided in the constructor, the * signals <code>.value</code> will be subtracted from the incoming signal. * * @extends {Tone.Signal} * @constructor * @param {number=} value The value to subtract from the incoming signal. If the value * is omitted, it will subtract the second signal from the first. * @example * var sub = new Tone.Subtract(1); * var sig = new Tone.Signal(4).connect(sub); * //the output of sub is 3. * @example * var sub = new Tone.Subtract(); * var sigA = new Tone.Signal(10); * var sigB = new Tone.Signal(2.5); * sigA.connect(sub, 0, 0); * sigB.connect(sub, 0, 1); * //output of sub is 7.5 */ Tone.Subtract = function (value) { Tone.call(this, 2, 0); /** * the summing node * @type {GainNode} * @private */ this._sum = this.input[0] = this.output = this.context.createGain(); /** * negate the input of the second input before connecting it * to the summing node. * @type {Tone.Negate} * @private */ this._neg = new Tone.Negate(); /** * the node where the value is set * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); this._param.chain(this._neg, this._sum); }; Tone.extend(Tone.Subtract, Tone.Signal); /** * Clean up. * @returns {Tone.SignalBase} this */ Tone.Subtract.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._neg.dispose(); this._neg = null; this._sum.disconnect(); this._sum = null; this._param.dispose(); this._param = null; return this; }; return Tone.Subtract; }); Module(function (Tone) { /** * @class GreaterThanZero outputs 1 when the input is strictly greater than zero * * @constructor * @extends {Tone.SignalBase} * @example * var gt0 = new Tone.GreaterThanZero(); * var sig = new Tone.Signal(0.01).connect(gt0); * //the output of gt0 is 1. * sig.value = 0; * //the output of gt0 is 0. */ Tone.GreaterThanZero = function () { /** * @type {Tone.WaveShaper} * @private */ this._thresh = this.output = new Tone.WaveShaper(function (val) { if (val <= 0) { return 0; } else { return 1; } }); /** * scale the first thresholded signal by a large value. * this will help with values which are very close to 0 * @type {Tone.Multiply} * @private */ this._scale = this.input = new Tone.Multiply(10000); //connections this._scale.connect(this._thresh); }; Tone.extend(Tone.GreaterThanZero, Tone.SignalBase); /** * dispose method * @returns {Tone.GreaterThanZero} this */ Tone.GreaterThanZero.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.GreaterThanZero; }); Module(function (Tone) { /** * @class EqualZero outputs 1 when the input is equal to * 0 and outputs 0 otherwise. * * @constructor * @extends {Tone.SignalBase} * @example * var eq0 = new Tone.EqualZero(); * var sig = new Tone.Signal(0).connect(eq0); * //the output of eq0 is 1. */ Tone.EqualZero = function () { /** * scale the incoming signal by a large factor * @private * @type {Tone.Multiply} */ this._scale = this.input = new Tone.Multiply(10000); /** * @type {Tone.WaveShaper} * @private */ this._thresh = new Tone.WaveShaper(function (val) { if (val === 0) { return 1; } else { return 0; } }, 128); /** * threshold the output so that it's 0 or 1 * @type {Tone.GreaterThanZero} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //connections this._scale.chain(this._thresh, this._gtz); }; Tone.extend(Tone.EqualZero, Tone.SignalBase); /** * Clean up. * @returns {Tone.EqualZero} this */ Tone.EqualZero.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._gtz.dispose(); this._gtz = null; this._scale.dispose(); this._scale = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.EqualZero; }); Module(function (Tone) { /** * @class Output 1 if the signal is equal to the value, otherwise outputs 0. * Can accept two signals if connected to inputs 0 and 1. * * @constructor * @extends {Tone.SignalBase} * @param {number=} value The number to compare the incoming signal to * @example * var eq = new Tone.Equal(3); * var sig = new Tone.Signal(3).connect(eq); * //the output of eq is 1. */ Tone.Equal = function (value) { Tone.call(this, 2, 0); /** * subtract the value from the incoming signal * * @type {Tone.Add} * @private */ this._sub = this.input[0] = new Tone.Subtract(value); /** * @type {Tone.EqualZero} * @private */ this._equals = this.output = new Tone.EqualZero(); this._sub.connect(this._equals); this.input[1] = this._sub.input[1]; }; Tone.extend(Tone.Equal, Tone.SignalBase); /** * The value to compare to the incoming signal. * @memberOf Tone.Equal# * @type {number} * @name value */ Object.defineProperty(Tone.Equal.prototype, 'value', { get: function () { return this._sub.value; }, set: function (value) { this._sub.value = value; } }); /** * Clean up. * @returns {Tone.Equal} this */ Tone.Equal.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._equals.dispose(); this._equals = null; this._sub.dispose(); this._sub = null; return this; }; return Tone.Equal; }); Module(function (Tone) { /** * @class Select between any number of inputs, sending the one * selected by the gate signal to the output * * @constructor * @extends {Tone.SignalBase} * @param {number} [sourceCount=2] the number of inputs the switch accepts * @example * var sel = new Tone.Select(2); * var sigA = new Tone.Signal(10).connect(sel, 0, 0); * var sigB = new Tone.Signal(20).connect(sel, 0, 1); * sel.gate.value = 0; * //sel outputs 10 (the value of sigA); * sel.gate.value = 1; * //sel outputs 20 (the value of sigB); */ Tone.Select = function (sourceCount) { sourceCount = this.defaultArg(sourceCount, 2); Tone.call(this, sourceCount, 1); /** * the control signal * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); //make all the inputs and connect them for (var i = 0; i < sourceCount; i++) { var switchGate = new SelectGate(i); this.input[i] = switchGate; this.gate.connect(switchGate.selecter); switchGate.connect(this.output); } }; Tone.extend(Tone.Select, Tone.SignalBase); /** * Open a specific input and close the others. * @param {number} which The gate to open. * @param {Time} [time=now] The time when the switch will open * @returns {Tone.Select} this * @example * //open input 1 in a half second from now * sel.select(1, "+0.5"); */ Tone.Select.prototype.select = function (which, time) { //make sure it's an integer which = Math.floor(which); this.gate.setValueAtTime(which, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Select} this */ Tone.Select.prototype.dispose = function () { this._writable('gate'); this.gate.dispose(); this.gate = null; for (var i = 0; i < this.input.length; i++) { this.input[i].dispose(); this.input[i] = null; } Tone.prototype.dispose.call(this); return this; }; ////////////START HELPER//////////// /** * helper class for Tone.Select representing a single gate * @constructor * @extends {Tone} * @private */ var SelectGate = function (num) { /** * the selector * @type {Tone.Equal} */ this.selecter = new Tone.Equal(num); /** * the gate * @type {GainNode} */ this.gate = this.input = this.output = this.context.createGain(); //connect the selecter to the gate gain this.selecter.connect(this.gate.gain); }; Tone.extend(SelectGate); /** * clean up * @private */ SelectGate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.selecter.dispose(); this.gate.disconnect(); this.selecter = null; this.gate = null; }; ////////////END HELPER//////////// //return Tone.Select return Tone.Select; }); Module(function (Tone) { /** * @class IfThenElse has three inputs. When the first input (if) is true (i.e. === 1), * then it will pass the second input (then) through to the output, otherwise, * if it's not true (i.e. === 0) then it will pass the third input (else) * through to the output. * * @extends {Tone.SignalBase} * @constructor * @example * var ifThenElse = new Tone.IfThenElse(); * var ifSignal = new Tone.Signal(1).connect(ifThenElse.if); * var pwmOsc = new Tone.PWMOscillator().connect(ifThenElse.then); * var pulseOsc = new Tone.PulseOscillator().connect(ifThenElse.else); * //ifThenElse outputs pwmOsc * signal.value = 0; * //now ifThenElse outputs pulseOsc */ Tone.IfThenElse = function () { Tone.call(this, 3, 0); /** * the selector node which is responsible for the routing * @type {Tone.Select} * @private */ this._selector = this.output = new Tone.Select(2); //the input mapping this.if = this.input[0] = this._selector.gate; this.then = this.input[1] = this._selector.input[1]; this.else = this.input[2] = this._selector.input[0]; }; Tone.extend(Tone.IfThenElse, Tone.SignalBase); /** * clean up * @returns {Tone.IfThenElse} this */ Tone.IfThenElse.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._selector.dispose(); this._selector = null; this.if = null; this.then = null; this.else = null; return this; }; return Tone.IfThenElse; }); Module(function (Tone) { /** * @class [OR](https://en.wikipedia.org/wiki/OR_gate) * the inputs together. True if at least one of the inputs is true. * * @extends {Tone.SignalBase} * @constructor * @param {number} [inputCount=2] the input count * @example * var or = new Tone.OR(2); * var sigA = new Tone.Signal(0)connect(or, 0, 0); * var sigB = new Tone.Signal(1)connect(or, 0, 1); * //output of or is 1 because at least * //one of the inputs is equal to 1. */ Tone.OR = function (inputCount) { inputCount = this.defaultArg(inputCount, 2); Tone.call(this, inputCount, 0); /** * a private summing node * @type {GainNode} * @private */ this._sum = this.context.createGain(); /** * @type {Tone.Equal} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //make each of the inputs an alias for (var i = 0; i < inputCount; i++) { this.input[i] = this._sum; } this._sum.connect(this._gtz); }; Tone.extend(Tone.OR, Tone.SignalBase); /** * clean up * @returns {Tone.OR} this */ Tone.OR.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._gtz.dispose(); this._gtz = null; this._sum.disconnect(); this._sum = null; return this; }; return Tone.OR; }); Module(function (Tone) { /** * @class [AND](https://en.wikipedia.org/wiki/Logical_conjunction) * returns 1 when all the inputs are equal to 1 and returns 0 otherwise. * * @extends {Tone.SignalBase} * @constructor * @param {number} [inputCount=2] the number of inputs. NOTE: all inputs are * connected to the single AND input node * @example * var and = new Tone.AND(2); * var sigA = new Tone.Signal(0).connect(and, 0, 0); * var sigB = new Tone.Signal(1).connect(and, 0, 1); * //the output of and is 0. */ Tone.AND = function (inputCount) { inputCount = this.defaultArg(inputCount, 2); Tone.call(this, inputCount, 0); /** * @type {Tone.Equal} * @private */ this._equals = this.output = new Tone.Equal(inputCount); //make each of the inputs an alias for (var i = 0; i < inputCount; i++) { this.input[i] = this._equals; } }; Tone.extend(Tone.AND, Tone.SignalBase); /** * clean up * @returns {Tone.AND} this */ Tone.AND.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._equals.dispose(); this._equals = null; return this; }; return Tone.AND; }); Module(function (Tone) { /** * @class Just an alias for Tone.EqualZero, but has the same effect as a NOT operator. * Outputs 1 when input equals 0. * * @constructor * @extends {Tone.SignalBase} * @example * var not = new Tone.NOT(); * var sig = new Tone.Signal(1).connect(not); * //output of not equals 0. * sig.value = 0; * //output of not equals 1. */ Tone.NOT = Tone.EqualZero; return Tone.NOT; }); Module(function (Tone) { /** * @class Output 1 if the signal is greater than the value, otherwise outputs 0. * can compare two signals or a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number} [value=0] the value to compare to the incoming signal * @example * var gt = new Tone.GreaterThan(2); * var sig = new Tone.Signal(4).connect(gt); * //output of gt is equal 1. */ Tone.GreaterThan = function (value) { Tone.call(this, 2, 0); /** * subtract the amount from the incoming signal * @type {Tone.Subtract} * @private */ this._param = this.input[0] = new Tone.Subtract(value); this.input[1] = this._param.input[1]; /** * compare that amount to zero * @type {Tone.GreaterThanZero} * @private */ this._gtz = this.output = new Tone.GreaterThanZero(); //connect this._param.connect(this._gtz); }; Tone.extend(Tone.GreaterThan, Tone.Signal); /** * dispose method * @returns {Tone.GreaterThan} this */ Tone.GreaterThan.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._param = null; this._gtz.dispose(); this._gtz = null; return this; }; return Tone.GreaterThan; }); Module(function (Tone) { /** * @class Output 1 if the signal is less than the value, otherwise outputs 0. * Can compare two signals or a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number=} value The value to compare to the incoming signal. * If no value is provided, it will compare * <code>input[0]</code> and <code>input[1]</code> * @example * var lt = new Tone.LessThan(2); * var sig = new Tone.Signal(-1).connect(lt); * //if (sig < 2) lt outputs 1 */ Tone.LessThan = function (value) { Tone.call(this, 2, 0); /** * negate the incoming signal * @type {Tone.Negate} * @private */ this._neg = this.input[0] = new Tone.Negate(); /** * input < value === -input > -value * @type {Tone.GreaterThan} * @private */ this._gt = this.output = new Tone.GreaterThan(); /** * negate the signal coming from the second input * @private * @type {Tone.Negate} */ this._rhNeg = new Tone.Negate(); /** * the node where the value is set * @private * @type {Tone.Signal} */ this._param = this.input[1] = new Tone.Signal(value); //connect this._neg.connect(this._gt); this._param.connect(this._rhNeg); this._rhNeg.connect(this._gt, 0, 1); }; Tone.extend(Tone.LessThan, Tone.Signal); /** * Clean up. * @returns {Tone.LessThan} this */ Tone.LessThan.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._neg.dispose(); this._neg = null; this._gt.dispose(); this._gt = null; this._rhNeg.dispose(); this._rhNeg = null; this._param.dispose(); this._param = null; return this; }; return Tone.LessThan; }); Module(function (Tone) { /** * @class Return the absolute value of an incoming signal. * * @constructor * @extends {Tone.SignalBase} * @example * var signal = new Tone.Signal(-1); * var abs = new Tone.Abs(); * signal.connect(abs); * //the output of abs is 1. */ Tone.Abs = function () { Tone.call(this, 1, 0); /** * @type {Tone.LessThan} * @private */ this._ltz = new Tone.LessThan(0); /** * @type {Tone.Select} * @private */ this._switch = this.output = new Tone.Select(2); /** * @type {Tone.Negate} * @private */ this._negate = new Tone.Negate(); //two signal paths, positive and negative this.input.connect(this._switch, 0, 0); this.input.connect(this._negate); this._negate.connect(this._switch, 0, 1); //the control signal this.input.chain(this._ltz, this._switch.gate); }; Tone.extend(Tone.Abs, Tone.SignalBase); /** * dispose method * @returns {Tone.Abs} this */ Tone.Abs.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._switch.dispose(); this._switch = null; this._ltz.dispose(); this._ltz = null; this._negate.dispose(); this._negate = null; return this; }; return Tone.Abs; }); Module(function (Tone) { /** * @class Outputs the greater of two signals. If a number is provided in the constructor * it will use that instead of the signal. * * @constructor * @extends {Tone.Signal} * @param {number=} max Max value if provided. if not provided, it will use the * signal value from input 1. * @example * var max = new Tone.Max(2); * var sig = new Tone.Signal(3).connect(max); * //max outputs 3 * sig.value = 1; * //max outputs 2 * @example * var max = new Tone.Max(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(max, 0, 0); * sigB.connect(max, 0, 1); * //output of max is 4. */ Tone.Max = function (max) { Tone.call(this, 2, 0); this.input[0] = this.context.createGain(); /** * the max signal * @type {Tone.Signal} * @private */ this._param = this.input[1] = new Tone.Signal(max); /** * @type {Tone.Select} * @private */ this._ifThenElse = this.output = new Tone.IfThenElse(); /** * @type {Tone.Select} * @private */ this._gt = new Tone.GreaterThan(); //connections this.input[0].chain(this._gt, this._ifThenElse.if); this.input[0].connect(this._ifThenElse.then); this._param.connect(this._ifThenElse.else); this._param.connect(this._gt, 0, 1); }; Tone.extend(Tone.Max, Tone.Signal); /** * Clean up. * @returns {Tone.Max} this */ Tone.Max.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._ifThenElse.dispose(); this._gt.dispose(); this._param = null; this._ifThenElse = null; this._gt = null; return this; }; return Tone.Max; }); Module(function (Tone) { /** * @class Outputs the lesser of two signals. If a number is given * in the constructor, it will use a signal and a number. * * @constructor * @extends {Tone.Signal} * @param {number} min The minimum to compare to the incoming signal * @example * var min = new Tone.Min(2); * var sig = new Tone.Signal(3).connect(min); * //min outputs 2 * sig.value = 1; * //min outputs 1 * @example * var min = new Tone.Min(); * var sigA = new Tone.Signal(3); * var sigB = new Tone.Signal(4); * sigA.connect(min, 0, 0); * sigB.connect(min, 0, 1); * //output of min is 3. */ Tone.Min = function (min) { Tone.call(this, 2, 0); this.input[0] = this.context.createGain(); /** * @type {Tone.Select} * @private */ this._ifThenElse = this.output = new Tone.IfThenElse(); /** * @type {Tone.Select} * @private */ this._lt = new Tone.LessThan(); /** * the min signal * @type {Tone.Signal} * @private */ this._param = this.input[1] = new Tone.Signal(min); //connections this.input[0].chain(this._lt, this._ifThenElse.if); this.input[0].connect(this._ifThenElse.then); this._param.connect(this._ifThenElse.else); this._param.connect(this._lt, 0, 1); }; Tone.extend(Tone.Min, Tone.Signal); /** * clean up * @returns {Tone.Min} this */ Tone.Min.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._param.dispose(); this._ifThenElse.dispose(); this._lt.dispose(); this._param = null; this._ifThenElse = null; this._lt = null; return this; }; return Tone.Min; }); Module(function (Tone) { /** * @class Signal-rate modulo operator. Only works in AudioRange [-1, 1] and for modulus * values in the NormalRange. * * @constructor * @extends {Tone.SignalBase} * @param {NormalRange} modulus The modulus to apply. * @example * var mod = new Tone.Modulo(0.2) * var sig = new Tone.Signal(0.5).connect(mod); * //mod outputs 0.1 */ Tone.Modulo = function (modulus) { Tone.call(this, 1, 1); /** * A waveshaper gets the integer multiple of * the input signal and the modulus. * @private * @type {Tone.WaveShaper} */ this._shaper = new Tone.WaveShaper(Math.pow(2, 16)); /** * the integer multiple is multiplied by the modulus * @type {Tone.Multiply} * @private */ this._multiply = new Tone.Multiply(); /** * and subtracted from the input signal * @type {Tone.Subtract} * @private */ this._subtract = this.output = new Tone.Subtract(); /** * the modulus signal * @type {Tone.Signal} * @private */ this._modSignal = new Tone.Signal(modulus); //connections this.input.fan(this._shaper, this._subtract); this._modSignal.connect(this._multiply, 0, 0); this._shaper.connect(this._multiply, 0, 1); this._multiply.connect(this._subtract, 0, 1); this._setWaveShaper(modulus); }; Tone.extend(Tone.Modulo, Tone.SignalBase); /** * @param {number} mod the modulus to apply * @private */ Tone.Modulo.prototype._setWaveShaper = function (mod) { this._shaper.setMap(function (val) { var multiple = Math.floor((val + 0.0001) / mod); return multiple; }); }; /** * The modulus value. * @memberOf Tone.Modulo# * @type {NormalRange} * @name value */ Object.defineProperty(Tone.Modulo.prototype, 'value', { get: function () { return this._modSignal.value; }, set: function (mod) { this._modSignal.value = mod; this._setWaveShaper(mod); } }); /** * clean up * @returns {Tone.Modulo} this */ Tone.Modulo.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; this._multiply.dispose(); this._multiply = null; this._subtract.dispose(); this._subtract = null; this._modSignal.dispose(); this._modSignal = null; return this; }; return Tone.Modulo; }); Module(function (Tone) { /** * @class AudioToGain converts an input in AudioRange [-1,1] to NormalRange [0,1]. * See Tone.GainToAudio. * * @extends {Tone.SignalBase} * @constructor * @example * var a2g = new Tone.AudioToGain(); */ Tone.AudioToGain = function () { /** * @type {WaveShaperNode} * @private */ this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { return (x + 1) / 2; }); }; Tone.extend(Tone.AudioToGain, Tone.SignalBase); /** * clean up * @returns {Tone.AudioToGain} this */ Tone.AudioToGain.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._norm.dispose(); this._norm = null; return this; }; return Tone.AudioToGain; }); Module(function (Tone) { /** * @class Evaluate an expression at audio rate. <br><br> * Parsing code modified from https://code.google.com/p/tapdigit/ * Copyright 2011 2012 Ariya Hidayat, New BSD License * * @extends {Tone.SignalBase} * @constructor * @param {string} expr the expression to generate * @example * //adds the signals from input[0] and input[1]. * var expr = new Tone.Expr("$0 + $1"); */ Tone.Expr = function () { var expr = this._replacements(Array.prototype.slice.call(arguments)); var inputCount = this._parseInputs(expr); /** * hold onto all of the nodes for disposal * @type {Array} * @private */ this._nodes = []; /** * The inputs. The length is determined by the expression. * @type {Array} */ this.input = new Array(inputCount); //create a gain for each input for (var i = 0; i < inputCount; i++) { this.input[i] = this.context.createGain(); } //parse the syntax tree var tree = this._parseTree(expr); //evaluate the results var result; try { result = this._eval(tree); } catch (e) { this._disposeNodes(); throw new Error('Could evaluate expression: ' + expr); } /** * The output node is the result of the expression * @type {Tone} */ this.output = result; }; Tone.extend(Tone.Expr, Tone.SignalBase); //some helpers to cut down the amount of code function applyBinary(Constructor, args, self) { var op = new Constructor(); self._eval(args[0]).connect(op, 0, 0); self._eval(args[1]).connect(op, 0, 1); return op; } function applyUnary(Constructor, args, self) { var op = new Constructor(); self._eval(args[0]).connect(op, 0, 0); return op; } function getNumber(arg) { return arg ? parseFloat(arg) : undefined; } function literalNumber(arg) { return arg && arg.args ? parseFloat(arg.args) : undefined; } /* * the Expressions that Tone.Expr can parse. * * each expression belongs to a group and contains a regexp * for selecting the operator as well as that operators method * * @type {Object} * @private */ Tone.Expr._Expressions = { //values 'value': { 'signal': { regexp: /^\d+\.\d+|^\d+/, method: function (arg) { var sig = new Tone.Signal(getNumber(arg)); return sig; } }, 'input': { regexp: /^\$\d/, method: function (arg, self) { return self.input[getNumber(arg.substr(1))]; } } }, //syntactic glue 'glue': { '(': { regexp: /^\(/ }, ')': { regexp: /^\)/ }, ',': { regexp: /^,/ } }, //functions 'func': { 'abs': { regexp: /^abs/, method: applyUnary.bind(this, Tone.Abs) }, 'min': { regexp: /^min/, method: applyBinary.bind(this, Tone.Min) }, 'max': { regexp: /^max/, method: applyBinary.bind(this, Tone.Max) }, 'if': { regexp: /^if/, method: function (args, self) { var op = new Tone.IfThenElse(); self._eval(args[0]).connect(op.if); self._eval(args[1]).connect(op.then); self._eval(args[2]).connect(op.else); return op; } }, 'gt0': { regexp: /^gt0/, method: applyUnary.bind(this, Tone.GreaterThanZero) }, 'eq0': { regexp: /^eq0/, method: applyUnary.bind(this, Tone.EqualZero) }, 'mod': { regexp: /^mod/, method: function (args, self) { var modulus = literalNumber(args[1]); var op = new Tone.Modulo(modulus); self._eval(args[0]).connect(op); return op; } }, 'pow': { regexp: /^pow/, method: function (args, self) { var exp = literalNumber(args[1]); var op = new Tone.Pow(exp); self._eval(args[0]).connect(op); return op; } }, 'a2g': { regexp: /^a2g/, method: function (args, self) { var op = new Tone.AudioToGain(); self._eval(args[0]).connect(op); return op; } } }, //binary expressions 'binary': { '+': { regexp: /^\+/, precedence: 1, method: applyBinary.bind(this, Tone.Add) }, '-': { regexp: /^\-/, precedence: 1, method: function (args, self) { //both unary and binary op if (args.length === 1) { return applyUnary(Tone.Negate, args, self); } else { return applyBinary(Tone.Subtract, args, self); } } }, '*': { regexp: /^\*/, precedence: 0, method: applyBinary.bind(this, Tone.Multiply) }, '>': { regexp: /^\>/, precedence: 2, method: applyBinary.bind(this, Tone.GreaterThan) }, '<': { regexp: /^</, precedence: 2, method: applyBinary.bind(this, Tone.LessThan) }, '==': { regexp: /^==/, precedence: 3, method: applyBinary.bind(this, Tone.Equal) }, '&&': { regexp: /^&&/, precedence: 4, method: applyBinary.bind(this, Tone.AND) }, '||': { regexp: /^\|\|/, precedence: 5, method: applyBinary.bind(this, Tone.OR) } }, //unary expressions 'unary': { '-': { regexp: /^\-/, method: applyUnary.bind(this, Tone.Negate) }, '!': { regexp: /^\!/, method: applyUnary.bind(this, Tone.NOT) } } }; /** * @param {string} expr the expression string * @return {number} the input count * @private */ Tone.Expr.prototype._parseInputs = function (expr) { var inputArray = expr.match(/\$\d/g); var inputMax = 0; if (inputArray !== null) { for (var i = 0; i < inputArray.length; i++) { var inputNum = parseInt(inputArray[i].substr(1)) + 1; inputMax = Math.max(inputMax, inputNum); } } return inputMax; }; /** * @param {Array} args an array of arguments * @return {string} the results of the replacements being replaced * @private */ Tone.Expr.prototype._replacements = function (args) { var expr = args.shift(); for (var i = 0; i < args.length; i++) { expr = expr.replace(/\%/i, args[i]); } return expr; }; /** * tokenize the expression based on the Expressions object * @param {string} expr * @return {Object} returns two methods on the tokenized list, next and peek * @private */ Tone.Expr.prototype._tokenize = function (expr) { var position = -1; var tokens = []; while (expr.length > 0) { expr = expr.trim(); var token = getNextToken(expr); tokens.push(token); expr = expr.substr(token.value.length); } function getNextToken(expr) { for (var type in Tone.Expr._Expressions) { var group = Tone.Expr._Expressions[type]; for (var opName in group) { var op = group[opName]; var reg = op.regexp; var match = expr.match(reg); if (match !== null) { return { type: type, value: match[0], method: op.method }; } } } throw new SyntaxError('Unexpected token ' + expr); } return { next: function () { return tokens[++position]; }, peek: function () { return tokens[position + 1]; } }; }; /** * recursively parse the string expression into a syntax tree * * @param {string} expr * @return {Object} * @private */ Tone.Expr.prototype._parseTree = function (expr) { var lexer = this._tokenize(expr); var isUndef = this.isUndef.bind(this); function matchSyntax(token, syn) { return !isUndef(token) && token.type === 'glue' && token.value === syn; } function matchGroup(token, groupName, prec) { var ret = false; var group = Tone.Expr._Expressions[groupName]; if (!isUndef(token)) { for (var opName in group) { var op = group[opName]; if (op.regexp.test(token.value)) { if (!isUndef(prec)) { if (op.precedence === prec) { return true; } } else { return true; } } } } return ret; } function parseExpression(precedence) { if (isUndef(precedence)) { precedence = 5; } var expr; if (precedence < 0) { expr = parseUnary(); } else { expr = parseExpression(precedence - 1); } var token = lexer.peek(); while (matchGroup(token, 'binary', precedence)) { token = lexer.next(); expr = { operator: token.value, method: token.method, args: [ expr, parseExpression(precedence) ] }; token = lexer.peek(); } return expr; } function parseUnary() { var token, expr; token = lexer.peek(); if (matchGroup(token, 'unary')) { token = lexer.next(); expr = parseUnary(); return { operator: token.value, method: token.method, args: [expr] }; } return parsePrimary(); } function parsePrimary() { var token, expr; token = lexer.peek(); if (isUndef(token)) { throw new SyntaxError('Unexpected termination of expression'); } if (token.type === 'func') { token = lexer.next(); return parseFunctionCall(token); } if (token.type === 'value') { token = lexer.next(); return { method: token.method, args: token.value }; } if (matchSyntax(token, '(')) { lexer.next(); expr = parseExpression(); token = lexer.next(); if (!matchSyntax(token, ')')) { throw new SyntaxError('Expected )'); } return expr; } throw new SyntaxError('Parse error, cannot process token ' + token.value); } function parseFunctionCall(func) { var token, args = []; token = lexer.next(); if (!matchSyntax(token, '(')) { throw new SyntaxError('Expected ( in a function call "' + func.value + '"'); } token = lexer.peek(); if (!matchSyntax(token, ')')) { args = parseArgumentList(); } token = lexer.next(); if (!matchSyntax(token, ')')) { throw new SyntaxError('Expected ) in a function call "' + func.value + '"'); } return { method: func.method, args: args, name: name }; } function parseArgumentList() { var token, expr, args = []; while (true) { expr = parseExpression(); if (isUndef(expr)) { // TODO maybe throw exception? break; } args.push(expr); token = lexer.peek(); if (!matchSyntax(token, ',')) { break; } lexer.next(); } return args; } return parseExpression(); }; /** * recursively evaluate the expression tree * @param {Object} tree * @return {AudioNode} the resulting audio node from the expression * @private */ Tone.Expr.prototype._eval = function (tree) { if (!this.isUndef(tree)) { var node = tree.method(tree.args, this); this._nodes.push(node); return node; } }; /** * dispose all the nodes * @private */ Tone.Expr.prototype._disposeNodes = function () { for (var i = 0; i < this._nodes.length; i++) { var node = this._nodes[i]; if (this.isFunction(node.dispose)) { node.dispose(); } else if (this.isFunction(node.disconnect)) { node.disconnect(); } node = null; this._nodes[i] = null; } this._nodes = null; }; /** * clean up */ Tone.Expr.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._disposeNodes(); }; return Tone.Expr; }); Module(function (Tone) { /** * @class Convert an incoming signal between 0, 1 to an equal power gain scale. * * @extends {Tone.SignalBase} * @constructor * @example * var eqPowGain = new Tone.EqualPowerGain(); */ Tone.EqualPowerGain = function () { /** * @type {Tone.WaveShaper} * @private */ this._eqPower = this.input = this.output = new Tone.WaveShaper(function (val) { if (Math.abs(val) < 0.001) { //should output 0 when input is 0 return 0; } else { return this.equalPowerScale(val); } }.bind(this), 4096); }; Tone.extend(Tone.EqualPowerGain, Tone.SignalBase); /** * clean up * @returns {Tone.EqualPowerGain} this */ Tone.EqualPowerGain.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._eqPower.dispose(); this._eqPower = null; return this; }; return Tone.EqualPowerGain; }); Module(function (Tone) { /** * @class Tone.Crossfade provides equal power fading between two inputs. * More on crossfading technique [here](https://en.wikipedia.org/wiki/Fade_(audio_engineering)#Crossfading). * * @constructor * @extends {Tone} * @param {NormalRange} [initialFade=0.5] * @example * var crossFade = new Tone.CrossFade(0.5); * //connect effect A to crossfade from * //effect output 0 to crossfade input 0 * effectA.connect(crossFade, 0, 0); * //connect effect B to crossfade from * //effect output 0 to crossfade input 1 * effectB.connect(crossFade, 0, 1); * crossFade.fade.value = 0; * // ^ only effectA is output * crossFade.fade.value = 1; * // ^ only effectB is output * crossFade.fade.value = 0.5; * // ^ the two signals are mixed equally. */ Tone.CrossFade = function (initialFade) { Tone.call(this, 2, 1); /** * Alias for <code>input[0]</code>. * @type {GainNode} */ this.a = this.input[0] = this.context.createGain(); /** * Alias for <code>input[1]</code>. * @type {GainNode} */ this.b = this.input[1] = this.context.createGain(); /** * The mix between the two inputs. A fade value of 0 * will output 100% <code>input[0]</code> and * a value of 1 will output 100% <code>input[1]</code>. * @type {NormalRange} * @signal */ this.fade = new Tone.Signal(this.defaultArg(initialFade, 0.5), Tone.Type.NormalRange); /** * equal power gain cross fade * @private * @type {Tone.EqualPowerGain} */ this._equalPowerA = new Tone.EqualPowerGain(); /** * equal power gain cross fade * @private * @type {Tone.EqualPowerGain} */ this._equalPowerB = new Tone.EqualPowerGain(); /** * invert the incoming signal * @private * @type {Tone} */ this._invert = new Tone.Expr('1 - $0'); //connections this.a.connect(this.output); this.b.connect(this.output); this.fade.chain(this._equalPowerB, this.b.gain); this.fade.chain(this._invert, this._equalPowerA, this.a.gain); this._readOnly('fade'); }; Tone.extend(Tone.CrossFade); /** * clean up * @returns {Tone.CrossFade} this */ Tone.CrossFade.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('fade'); this._equalPowerA.dispose(); this._equalPowerA = null; this._equalPowerB.dispose(); this._equalPowerB = null; this.fade.dispose(); this.fade = null; this._invert.dispose(); this._invert = null; this.a.disconnect(); this.a = null; this.b.disconnect(); this.b = null; return this; }; return Tone.CrossFade; }); Module(function (Tone) { /** * @class Tone.Filter is a filter which allows for all of the same native methods * as the [BiquadFilterNode](http://webaudio.github.io/web-audio-api/#the-biquadfilternode-interface). * Tone.Filter has the added ability to set the filter rolloff at -12 * (default), -24 and -48. * * @constructor * @extends {Tone} * @param {Frequency|Object} [frequency] The cutoff frequency of the filter. * @param {string=} type The type of filter. * @param {number=} rolloff The drop in decibels per octave after the cutoff frequency. * 3 choices: -12, -24, and -48 * @example * var filter = new Tone.Filter(200, "highpass"); */ Tone.Filter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'frequency', 'type', 'rolloff' ], Tone.Filter.defaults); /** * the filter(s) * @type {Array} * @private */ this._filters = []; /** * The cutoff frequency of the filter. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune parameter * @type {Cents} * @signal */ this.detune = new Tone.Signal(0, Tone.Type.Cents); /** * The gain of the filter, only used in certain filter types * @type {Number} * @signal */ this.gain = new Tone.Signal({ 'value': options.gain, 'convert': false }); /** * The Q or Quality of the filter * @type {Positive} * @signal */ this.Q = new Tone.Signal(options.Q); /** * the type of the filter * @type {string} * @private */ this._type = options.type; /** * the rolloff value of the filter * @type {number} * @private */ this._rolloff = options.rolloff; //set the rolloff; this.rolloff = options.rolloff; this._readOnly([ 'detune', 'frequency', 'gain', 'Q' ]); }; Tone.extend(Tone.Filter); /** * the default parameters * * @static * @type {Object} */ Tone.Filter.defaults = { 'type': 'lowpass', 'frequency': 350, 'rolloff': -12, 'Q': 1, 'gain': 0 }; /** * The type of the filter. Types: "lowpass", "highpass", * "bandpass", "lowshelf", "highshelf", "notch", "allpass", or "peaking". * @memberOf Tone.Filter# * @type {string} * @name type */ Object.defineProperty(Tone.Filter.prototype, 'type', { get: function () { return this._type; }, set: function (type) { var types = [ 'lowpass', 'highpass', 'bandpass', 'lowshelf', 'highshelf', 'notch', 'allpass', 'peaking' ]; if (types.indexOf(type) === -1) { throw new Error('Tone.Filter does not have filter type ' + type); } this._type = type; for (var i = 0; i < this._filters.length; i++) { this._filters[i].type = type; } } }); /** * The rolloff of the filter which is the drop in db * per octave. Implemented internally by cascading filters. * Only accepts the values -12, -24, -48 and -96. * @memberOf Tone.Filter# * @type {number} * @name rolloff */ Object.defineProperty(Tone.Filter.prototype, 'rolloff', { get: function () { return this._rolloff; }, set: function (rolloff) { rolloff = parseInt(rolloff, 10); var possibilities = [ -12, -24, -48, -96 ]; var cascadingCount = possibilities.indexOf(rolloff); //check the rolloff is valid if (cascadingCount === -1) { throw new Error('Filter rolloff can only be -12, -24, -48 or -96'); } cascadingCount += 1; this._rolloff = rolloff; //first disconnect the filters and throw them away this.input.disconnect(); for (var i = 0; i < this._filters.length; i++) { this._filters[i].disconnect(); this._filters[i] = null; } this._filters = new Array(cascadingCount); for (var count = 0; count < cascadingCount; count++) { var filter = this.context.createBiquadFilter(); filter.type = this._type; this.frequency.connect(filter.frequency); this.detune.connect(filter.detune); this.Q.connect(filter.Q); this.gain.connect(filter.gain); this._filters[count] = filter; } //connect them up var connectionChain = [this.input].concat(this._filters).concat([this.output]); this.connectSeries.apply(this, connectionChain); } }); /** * Clean up. * @return {Tone.Filter} this */ Tone.Filter.prototype.dispose = function () { Tone.prototype.dispose.call(this); for (var i = 0; i < this._filters.length; i++) { this._filters[i].disconnect(); this._filters[i] = null; } this._filters = null; this._writable([ 'detune', 'frequency', 'gain', 'Q' ]); this.frequency.dispose(); this.Q.dispose(); this.frequency = null; this.Q = null; this.detune.dispose(); this.detune = null; this.gain.dispose(); this.gain = null; return this; }; return Tone.Filter; }); Module(function (Tone) { /** * @class Split the incoming signal into three bands (low, mid, high) * with two crossover frequency controls. * * @extends {Tone} * @constructor * @param {Frequency|Object} [lowFrequency] the low/mid crossover frequency * @param {Frequency} [highFrequency] the mid/high crossover frequency */ Tone.MultibandSplit = function () { var options = this.optionsObject(arguments, [ 'lowFrequency', 'highFrequency' ], Tone.MultibandSplit.defaults); /** * the input * @type {GainNode} * @private */ this.input = this.context.createGain(); /** * the outputs * @type {Array} * @private */ this.output = new Array(3); /** * The low band. Alias for <code>output[0]</code> * @type {Tone.Filter} */ this.low = this.output[0] = new Tone.Filter(0, 'lowpass'); /** * the lower filter of the mid band * @type {Tone.Filter} * @private */ this._lowMidFilter = new Tone.Filter(0, 'highpass'); /** * The mid band output. Alias for <code>output[1]</code> * @type {Tone.Filter} */ this.mid = this.output[1] = new Tone.Filter(0, 'lowpass'); /** * The high band output. Alias for <code>output[2]</code> * @type {Tone.Filter} */ this.high = this.output[2] = new Tone.Filter(0, 'highpass'); /** * The low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = new Tone.Signal(options.lowFrequency, Tone.Type.Frequency); /** * The mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = new Tone.Signal(options.highFrequency, Tone.Type.Frequency); /** * The quality of all the filters * @type {Number} * @signal */ this.Q = new Tone.Signal(options.Q); this.input.fan(this.low, this.high); this.input.chain(this._lowMidFilter, this.mid); //the frequency control signal this.lowFrequency.connect(this.low.frequency); this.lowFrequency.connect(this._lowMidFilter.frequency); this.highFrequency.connect(this.mid.frequency); this.highFrequency.connect(this.high.frequency); //the Q value this.Q.connect(this.low.Q); this.Q.connect(this._lowMidFilter.Q); this.Q.connect(this.mid.Q); this.Q.connect(this.high.Q); this._readOnly([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); }; Tone.extend(Tone.MultibandSplit); /** * @private * @static * @type {Object} */ Tone.MultibandSplit.defaults = { 'lowFrequency': 400, 'highFrequency': 2500, 'Q': 1 }; /** * Clean up. * @returns {Tone.MultibandSplit} this */ Tone.MultibandSplit.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); this.low.dispose(); this.low = null; this._lowMidFilter.dispose(); this._lowMidFilter = null; this.mid.dispose(); this.mid = null; this.high.dispose(); this.high = null; this.lowFrequency.dispose(); this.lowFrequency = null; this.highFrequency.dispose(); this.highFrequency = null; this.Q.dispose(); this.Q = null; return this; }; return Tone.MultibandSplit; }); Module(function (Tone) { /** * @class Tone.EQ3 is a three band EQ with control over low, mid, and high gain as * well as the low and high crossover frequencies. * * @constructor * @extends {Tone} * * @param {Decibels|Object} [lowLevel] The gain applied to the lows. * @param {Decibels} [midLevel] The gain applied to the mid. * @param {Decibels} [highLevel] The gain applied to the high. * @example * var eq = new Tone.EQ3(-10, 3, -20); */ Tone.EQ3 = function () { var options = this.optionsObject(arguments, [ 'low', 'mid', 'high' ], Tone.EQ3.defaults); /** * the output node * @type {GainNode} * @private */ this.output = this.context.createGain(); /** * the multiband split * @type {Tone.MultibandSplit} * @private */ this._multibandSplit = this.input = new Tone.MultibandSplit({ 'lowFrequency': options.lowFrequency, 'highFrequency': options.highFrequency }); /** * The gain for the lower signals * @type {Tone.Gain} * @private */ this._lowGain = new Tone.Gain(options.low, Tone.Type.Decibels); /** * The gain for the mid signals * @type {Tone.Gain} * @private */ this._midGain = new Tone.Gain(options.mid, Tone.Type.Decibels); /** * The gain in decibels of the high part * @type {Tone.Gain} * @private */ this._highGain = new Tone.Gain(options.high, Tone.Type.Decibels); /** * The gain in decibels of the low part * @type {Decibels} * @signal */ this.low = this._lowGain.gain; /** * The gain in decibels of the mid part * @type {Decibels} * @signal */ this.mid = this._midGain.gain; /** * The gain in decibels of the high part * @type {Decibels} * @signal */ this.high = this._highGain.gain; /** * The Q value for all of the filters. * @type {Positive} * @signal */ this.Q = this._multibandSplit.Q; /** * The low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = this._multibandSplit.lowFrequency; /** * The mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = this._multibandSplit.highFrequency; //the frequency bands this._multibandSplit.low.chain(this._lowGain, this.output); this._multibandSplit.mid.chain(this._midGain, this.output); this._multibandSplit.high.chain(this._highGain, this.output); this._readOnly([ 'low', 'mid', 'high', 'lowFrequency', 'highFrequency' ]); }; Tone.extend(Tone.EQ3); /** * the default values */ Tone.EQ3.defaults = { 'low': 0, 'mid': 0, 'high': 0, 'lowFrequency': 400, 'highFrequency': 2500 }; /** * clean up * @returns {Tone.EQ3} this */ Tone.EQ3.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'low', 'mid', 'high', 'lowFrequency', 'highFrequency' ]); this._multibandSplit.dispose(); this._multibandSplit = null; this.lowFrequency = null; this.highFrequency = null; this._lowGain.dispose(); this._lowGain = null; this._midGain.dispose(); this._midGain = null; this._highGain.dispose(); this._highGain = null; this.low = null; this.mid = null; this.high = null; this.Q = null; return this; }; return Tone.EQ3; }); Module(function (Tone) { /** * @class Performs a linear scaling on an input signal. * Scales a NormalRange input to between * outputMin and outputMax. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputMin=0] The output value when the input is 0. * @param {number} [outputMax=1] The output value when the input is 1. * @example * var scale = new Tone.Scale(50, 100); * var signal = new Tone.Signal(0.5).connect(scale); * //the output of scale equals 75 */ Tone.Scale = function (outputMin, outputMax) { /** * @private * @type {number} */ this._outputMin = this.defaultArg(outputMin, 0); /** * @private * @type {number} */ this._outputMax = this.defaultArg(outputMax, 1); /** * @private * @type {Tone.Multiply} * @private */ this._scale = this.input = new Tone.Multiply(1); /** * @private * @type {Tone.Add} * @private */ this._add = this.output = new Tone.Add(0); this._scale.connect(this._add); this._setRange(); }; Tone.extend(Tone.Scale, Tone.SignalBase); /** * The minimum output value. This number is output when * the value input value is 0. * @memberOf Tone.Scale# * @type {number} * @name min */ Object.defineProperty(Tone.Scale.prototype, 'min', { get: function () { return this._outputMin; }, set: function (min) { this._outputMin = min; this._setRange(); } }); /** * The maximum output value. This number is output when * the value input value is 1. * @memberOf Tone.Scale# * @type {number} * @name max */ Object.defineProperty(Tone.Scale.prototype, 'max', { get: function () { return this._outputMax; }, set: function (max) { this._outputMax = max; this._setRange(); } }); /** * set the values * @private */ Tone.Scale.prototype._setRange = function () { this._add.value = this._outputMin; this._scale.value = this._outputMax - this._outputMin; }; /** * Clean up. * @returns {Tone.Scale} this */ Tone.Scale.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._add.dispose(); this._add = null; this._scale.dispose(); this._scale = null; return this; }; return Tone.Scale; }); Module(function (Tone) { /** * @class Performs an exponential scaling on an input signal. * Scales a NormalRange value [0,1] exponentially * to the output range of outputMin to outputMax. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputMin=0] The output value when the input is 0. * @param {number} [outputMax=1] The output value when the input is 1. * @param {number} [exponent=2] The exponent which scales the incoming signal. * @example * var scaleExp = new Tone.ScaleExp(0, 100, 2); * var signal = new Tone.Signal(0.5).connect(scaleExp); */ Tone.ScaleExp = function (outputMin, outputMax, exponent) { /** * scale the input to the output range * @type {Tone.Scale} * @private */ this._scale = this.output = new Tone.Scale(outputMin, outputMax); /** * @private * @type {Tone.Pow} * @private */ this._exp = this.input = new Tone.Pow(this.defaultArg(exponent, 2)); this._exp.connect(this._scale); }; Tone.extend(Tone.ScaleExp, Tone.SignalBase); /** * Instead of interpolating linearly between the <code>min</code> and * <code>max</code> values, setting the exponent will interpolate between * the two values with an exponential curve. * @memberOf Tone.ScaleExp# * @type {number} * @name exponent */ Object.defineProperty(Tone.ScaleExp.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * The minimum output value. This number is output when * the value input value is 0. * @memberOf Tone.ScaleExp# * @type {number} * @name min */ Object.defineProperty(Tone.ScaleExp.prototype, 'min', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = min; } }); /** * The maximum output value. This number is output when * the value input value is 1. * @memberOf Tone.ScaleExp# * @type {number} * @name max */ Object.defineProperty(Tone.ScaleExp.prototype, 'max', { get: function () { return this._scale.max; }, set: function (max) { this._scale.max = max; } }); /** * Clean up. * @returns {Tone.ScaleExp} this */ Tone.ScaleExp.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._exp.dispose(); this._exp = null; return this; }; return Tone.ScaleExp; }); Module(function (Tone) { /** * @class Comb filters are basic building blocks for physical modeling. Read more * about comb filters on [CCRMA's website](https://ccrma.stanford.edu/~jos/pasp/Feedback_Comb_Filters.html). * * @extends {Tone} * @constructor * @param {Time|Object} [delayTime] The delay time of the filter. * @param {NormalRange=} resonance The amount of feedback the filter has. */ Tone.FeedbackCombFilter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'delayTime', 'resonance' ], Tone.FeedbackCombFilter.defaults); /** * the delay node * @type {DelayNode} * @private */ this._delay = this.input = this.output = this.context.createDelay(1); /** * The amount of delay of the comb filter. * @type {Time} * @signal */ this.delayTime = new Tone.Param({ 'param': this._delay.delayTime, 'value': options.delayTime, 'units': Tone.Type.Time }); /** * the feedback node * @type {GainNode} * @private */ this._feedback = this.context.createGain(); /** * The amount of feedback of the delayed signal. * @type {NormalRange} * @signal */ this.resonance = new Tone.Param({ 'param': this._feedback.gain, 'value': options.resonance, 'units': Tone.Type.NormalRange }); this._delay.chain(this._feedback, this._delay); this._readOnly([ 'resonance', 'delayTime' ]); }; Tone.extend(Tone.FeedbackCombFilter); /** * the default parameters * @static * @const * @type {Object} */ Tone.FeedbackCombFilter.defaults = { 'delayTime': 0.1, 'resonance': 0.5 }; /** * clean up * @returns {Tone.FeedbackCombFilter} this */ Tone.FeedbackCombFilter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'resonance', 'delayTime' ]); this._delay.disconnect(); this._delay = null; this.delayTime.dispose(); this.delayTime = null; this.resonance.dispose(); this.resonance = null; this._feedback.disconnect(); this._feedback = null; return this; }; return Tone.FeedbackCombFilter; }); Module(function (Tone) { /** * @class Tone.Follower is a crude envelope follower which will follow * the amplitude of an incoming signal. * Take care with small (< 0.02) attack or decay values * as follower has some ripple which is exaggerated * at these values. Read more about envelope followers (also known * as envelope detectors) on [Wikipedia](https://en.wikipedia.org/wiki/Envelope_detector). * * @constructor * @extends {Tone} * @param {Time|Object} [attack] The rate at which the follower rises. * @param {Time=} release The rate at which the folower falls. * @example * var follower = new Tone.Follower(0.2, 0.4); */ Tone.Follower = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'attack', 'release' ], Tone.Follower.defaults); /** * @type {Tone.Abs} * @private */ this._abs = new Tone.Abs(); /** * the lowpass filter which smooths the input * @type {BiquadFilterNode} * @private */ this._filter = this.context.createBiquadFilter(); this._filter.type = 'lowpass'; this._filter.frequency.value = 0; this._filter.Q.value = -100; /** * @type {WaveShaperNode} * @private */ this._frequencyValues = new Tone.WaveShaper(); /** * @type {Tone.Subtract} * @private */ this._sub = new Tone.Subtract(); /** * @type {DelayNode} * @private */ this._delay = this.context.createDelay(); this._delay.delayTime.value = this.blockTime; /** * this keeps it far from 0, even for very small differences * @type {Tone.Multiply} * @private */ this._mult = new Tone.Multiply(10000); /** * @private * @type {number} */ this._attack = options.attack; /** * @private * @type {number} */ this._release = options.release; //the smoothed signal to get the values this.input.chain(this._abs, this._filter, this.output); //the difference path this._abs.connect(this._sub, 0, 1); this._filter.chain(this._delay, this._sub); //threshold the difference and use the thresh to set the frequency this._sub.chain(this._mult, this._frequencyValues, this._filter.frequency); //set the attack and release values in the table this._setAttackRelease(this._attack, this._release); }; Tone.extend(Tone.Follower); /** * @static * @type {Object} */ Tone.Follower.defaults = { 'attack': 0.05, 'release': 0.5 }; /** * sets the attack and release times in the wave shaper * @param {Time} attack * @param {Time} release * @private */ Tone.Follower.prototype._setAttackRelease = function (attack, release) { var minTime = this.blockTime; attack = this.secondsToFrequency(this.toSeconds(attack)); release = this.secondsToFrequency(this.toSeconds(release)); attack = Math.max(attack, minTime); release = Math.max(release, minTime); this._frequencyValues.setMap(function (val) { if (val <= 0) { return attack; } else { return release; } }); }; /** * The attack time. * @memberOf Tone.Follower# * @type {Time} * @name attack */ Object.defineProperty(Tone.Follower.prototype, 'attack', { get: function () { return this._attack; }, set: function (attack) { this._attack = attack; this._setAttackRelease(this._attack, this._release); } }); /** * The release time. * @memberOf Tone.Follower# * @type {Time} * @name release */ Object.defineProperty(Tone.Follower.prototype, 'release', { get: function () { return this._release; }, set: function (release) { this._release = release; this._setAttackRelease(this._attack, this._release); } }); /** * Borrows the connect method from Signal so that the output can be used * as a Tone.Signal control signal. * @function */ Tone.Follower.prototype.connect = Tone.Signal.prototype.connect; /** * dispose * @returns {Tone.Follower} this */ Tone.Follower.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._filter.disconnect(); this._filter = null; this._frequencyValues.disconnect(); this._frequencyValues = null; this._delay.disconnect(); this._delay = null; this._sub.disconnect(); this._sub = null; this._abs.dispose(); this._abs = null; this._mult.dispose(); this._mult = null; this._curve = null; return this; }; return Tone.Follower; }); Module(function (Tone) { /** * @class Tone.ScaledEnvelop is an envelope which can be scaled * to any range. It's useful for applying an envelope * to a frequency or any other non-NormalRange signal * parameter. * * @extends {Tone.Envelope} * @constructor * @param {Time|Object} [attack] the attack time in seconds * @param {Time} [decay] the decay time in seconds * @param {number} [sustain] a percentage (0-1) of the full amplitude * @param {Time} [release] the release time in seconds * @example * var scaledEnv = new Tone.ScaledEnvelope({ * "attack" : 0.2, * "min" : 200, * "max" : 2000 * }); * scaledEnv.connect(oscillator.frequency); */ Tone.ScaledEnvelope = function () { //get all of the defaults var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); Tone.Envelope.call(this, options); options = this.defaultArg(options, Tone.ScaledEnvelope.defaults); /** * scale the incoming signal by an exponent * @type {Tone.Pow} * @private */ this._exp = this.output = new Tone.Pow(options.exponent); /** * scale the signal to the desired range * @type {Tone.Multiply} * @private */ this._scale = this.output = new Tone.Scale(options.min, options.max); this._sig.chain(this._exp, this._scale); }; Tone.extend(Tone.ScaledEnvelope, Tone.Envelope); /** * the default parameters * @static */ Tone.ScaledEnvelope.defaults = { 'min': 0, 'max': 1, 'exponent': 1 }; /** * The envelope's min output value. This is the value which it * starts at. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name min */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'min', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = min; } }); /** * The envelope's max output value. In other words, the value * at the peak of the attack portion of the envelope. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name max */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'max', { get: function () { return this._scale.max; }, set: function (max) { this._scale.max = max; } }); /** * The envelope's exponent value. * @memberOf Tone.ScaledEnvelope# * @type {number} * @name exponent */ Object.defineProperty(Tone.ScaledEnvelope.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * clean up * @returns {Tone.ScaledEnvelope} this */ Tone.ScaledEnvelope.prototype.dispose = function () { Tone.Envelope.prototype.dispose.call(this); this._scale.dispose(); this._scale = null; this._exp.dispose(); this._exp = null; return this; }; return Tone.ScaledEnvelope; }); Module(function (Tone) { /** * @class Tone.FrequencyEnvelope is a Tone.ScaledEnvelope, but instead of `min` and `max` * it's got a `baseFrequency` and `octaves` parameter. * * @extends {Tone.Envelope} * @constructor * @param {Time|Object} [attack] the attack time in seconds * @param {Time} [decay] the decay time in seconds * @param {number} [sustain] a percentage (0-1) of the full amplitude * @param {Time} [release] the release time in seconds * @example * var env = new Tone.FrequencyEnvelope({ * "attack" : 0.2, * "baseFrequency" : "C2", * "octaves" : 4 * }); * scaledEnv.connect(oscillator.frequency); */ Tone.FrequencyEnvelope = function () { var options = this.optionsObject(arguments, [ 'attack', 'decay', 'sustain', 'release' ], Tone.Envelope.defaults); Tone.ScaledEnvelope.call(this, options); options = this.defaultArg(options, Tone.FrequencyEnvelope.defaults); /** * Stores the octave value * @type {Positive} * @private */ this._octaves = options.octaves; //setup this.baseFrequency = options.baseFrequency; this.octaves = options.octaves; }; Tone.extend(Tone.FrequencyEnvelope, Tone.Envelope); /** * the default parameters * @static */ Tone.FrequencyEnvelope.defaults = { 'baseFrequency': 200, 'octaves': 4, 'exponent': 2 }; /** * The envelope's mininum output value. This is the value which it * starts at. * @memberOf Tone.FrequencyEnvelope# * @type {Frequency} * @name baseFrequency */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'baseFrequency', { get: function () { return this._scale.min; }, set: function (min) { this._scale.min = this.toFrequency(min); } }); /** * The number of octaves above the baseFrequency that the * envelope will scale to. * @memberOf Tone.FrequencyEnvelope# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; this._scale.max = this.baseFrequency * Math.pow(2, octaves); } }); /** * The envelope's exponent value. * @memberOf Tone.FrequencyEnvelope# * @type {number} * @name exponent */ Object.defineProperty(Tone.FrequencyEnvelope.prototype, 'exponent', { get: function () { return this._exp.value; }, set: function (exp) { this._exp.value = exp; } }); /** * clean up * @returns {Tone.FrequencyEnvelope} this */ Tone.FrequencyEnvelope.prototype.dispose = function () { Tone.ScaledEnvelope.prototype.dispose.call(this); return this; }; return Tone.FrequencyEnvelope; }); Module(function (Tone) { /** * @class Tone.Gate only passes a signal through when the incoming * signal exceeds a specified threshold. To do this, Gate uses * a Tone.Follower to follow the amplitude of the incoming signal. * A common implementation of this class is a [Noise Gate](https://en.wikipedia.org/wiki/Noise_gate). * * @constructor * @extends {Tone} * @param {Decibels|Object} [threshold] The threshold above which the gate will open. * @param {Time=} attack The follower's attack time * @param {Time=} release The follower's release time * @example * var gate = new Tone.Gate(-30, 0.2, 0.3).toMaster(); * var mic = new Tone.Microphone().connect(gate); * //the gate will only pass through the incoming * //signal when it's louder than -30db */ Tone.Gate = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'threshold', 'attack', 'release' ], Tone.Gate.defaults); /** * @type {Tone.Follower} * @private */ this._follower = new Tone.Follower(options.attack, options.release); /** * @type {Tone.GreaterThan} * @private */ this._gt = new Tone.GreaterThan(this.dbToGain(options.threshold)); //the connections this.input.connect(this.output); //the control signal this.input.chain(this._gt, this._follower, this.output.gain); }; Tone.extend(Tone.Gate); /** * @const * @static * @type {Object} */ Tone.Gate.defaults = { 'attack': 0.1, 'release': 0.1, 'threshold': -40 }; /** * The threshold of the gate in decibels * @memberOf Tone.Gate# * @type {Decibels} * @name threshold */ Object.defineProperty(Tone.Gate.prototype, 'threshold', { get: function () { return this.gainToDb(this._gt.value); }, set: function (thresh) { this._gt.value = this.dbToGain(thresh); } }); /** * The attack speed of the gate * @memberOf Tone.Gate# * @type {Time} * @name attack */ Object.defineProperty(Tone.Gate.prototype, 'attack', { get: function () { return this._follower.attack; }, set: function (attackTime) { this._follower.attack = attackTime; } }); /** * The release speed of the gate * @memberOf Tone.Gate# * @type {Time} * @name release */ Object.defineProperty(Tone.Gate.prototype, 'release', { get: function () { return this._follower.release; }, set: function (releaseTime) { this._follower.release = releaseTime; } }); /** * Clean up. * @returns {Tone.Gate} this */ Tone.Gate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._follower.dispose(); this._gt.dispose(); this._follower = null; this._gt = null; return this; }; return Tone.Gate; }); Module(function (Tone) { /** * @class A Timeline State. Provides the methods: <code>setStateAtTime("state", time)</code> * and <code>getStateAtTime(time)</code>. * * @extends {Tone.Timeline} * @param {String} initial The initial state of the TimelineState. * Defaults to <code>undefined</code> */ Tone.TimelineState = function (initial) { Tone.Timeline.call(this); /** * The initial state * @private * @type {String} */ this._initial = initial; }; Tone.extend(Tone.TimelineState, Tone.Timeline); /** * Returns the scheduled state scheduled before or at * the given time. * @param {Time} time The time to query. * @return {String} The name of the state input in setStateAtTime. */ Tone.TimelineState.prototype.getStateAtTime = function (time) { var event = this.getEvent(time); if (event !== null) { return event.state; } else { return this._initial; } }; /** * Returns the scheduled state scheduled before or at * the given time. * @param {String} state The name of the state to set. * @param {Time} time The time to query. */ Tone.TimelineState.prototype.setStateAtTime = function (state, time) { this.addEvent({ 'state': state, 'time': this.toSeconds(time) }); }; return Tone.TimelineState; }); Module(function (Tone) { /** * @class A sample accurate clock which provides a callback at the given rate. * While the callback is not sample-accurate (it is still susceptible to * loose JS timing), the time passed in as the argument to the callback * is precise. For most applications, it is better to use Tone.Transport * instead of the Clock by itself since you can synchronize multiple callbacks. * * @constructor * @extends {Tone} * @param {function} callback The callback to be invoked with the time of the audio event * @param {Frequency} frequency The rate of the callback * @example * //the callback will be invoked approximately once a second * //and will print the time exactly once a second apart. * var clock = new Tone.Clock(function(time){ * console.log(time); * }, 1); */ Tone.Clock = function () { var options = this.optionsObject(arguments, [ 'callback', 'frequency' ], Tone.Clock.defaults); /** * The callback function to invoke at the scheduled tick. * @type {Function} */ this.callback = options.callback; /** * The time which the clock will schedule events in advance * of the current time. Scheduling notes in advance improves * performance and decreases the chance for clicks caused * by scheduling events in the past. If set to "auto", * this value will be automatically computed based on the * rate of requestAnimationFrame (0.016 seconds). Larger values * will yeild better performance, but at the cost of latency. * Values less than 0.016 are not recommended. * @type {Number|String} */ this._lookAhead = 'auto'; /** * The lookahead value which was automatically * computed using a time-based averaging. * @type {Number} * @private */ this._computedLookAhead = 1 / 60; /** * The value afterwhich events are thrown out * @type {Number} * @private */ this._threshold = 0.5; /** * The next time the callback is scheduled. * @type {Number} * @private */ this._nextTick = -1; /** * The last time the callback was invoked * @type {Number} * @private */ this._lastUpdate = 0; /** * The id of the requestAnimationFrame * @type {Number} * @private */ this._loopID = -1; /** * The rate the callback function should be invoked. * @type {BPM} * @signal */ this.frequency = new Tone.TimelineSignal(options.frequency, Tone.Type.Frequency); /** * The number of times the callback was invoked. Starts counting at 0 * and increments after the callback was invoked. * @type {Ticks} * @readOnly */ this.ticks = 0; /** * The state timeline * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * A pre-binded loop function to save a tiny bit of overhead * of rebinding the function on every frame. * @type {Function} * @private */ this._boundLoop = this._loop.bind(this); this._readOnly('frequency'); //start the loop this._loop(); }; Tone.extend(Tone.Clock); /** * The defaults * @const * @type {Object} */ Tone.Clock.defaults = { 'callback': Tone.noOp, 'frequency': 1, 'lookAhead': 'auto' }; /** * Returns the playback state of the source, either "started", "stopped" or "paused". * @type {Tone.State} * @readOnly * @memberOf Tone.Clock# * @name state */ Object.defineProperty(Tone.Clock.prototype, 'state', { get: function () { return this._state.getStateAtTime(this.now()); } }); /** * The time which the clock will schedule events in advance * of the current time. Scheduling notes in advance improves * performance and decreases the chance for clicks caused * by scheduling events in the past. If set to "auto", * this value will be automatically computed based on the * rate of requestAnimationFrame (0.016 seconds). Larger values * will yeild better performance, but at the cost of latency. * Values less than 0.016 are not recommended. * @type {Number|String} * @memberOf Tone.Clock# * @name lookAhead */ Object.defineProperty(Tone.Clock.prototype, 'lookAhead', { get: function () { return this._lookAhead; }, set: function (val) { if (val === 'auto') { this._lookAhead = 'auto'; } else { this._lookAhead = this.toSeconds(val); } } }); /** * Start the clock at the given time. Optionally pass in an offset * of where to start the tick counter from. * @param {Time} time The time the clock should start * @param {Ticks=} offset Where the tick counter starts counting from. * @return {Tone.Clock} this */ Tone.Clock.prototype.start = function (time, offset) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Started) { this._state.addEvent({ 'state': Tone.State.Started, 'time': time, 'offset': offset }); } return this; }; /** * Stop the clock. Stopping the clock resets the tick counter to 0. * @param {Time} [time=now] The time when the clock should stop. * @returns {Tone.Clock} this * @example * clock.stop(); */ Tone.Clock.prototype.stop = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Stopped) { this._state.setStateAtTime(Tone.State.Stopped, time); } return this; }; /** * Pause the clock. Pausing does not reset the tick counter. * @param {Time} [time=now] The time when the clock should stop. * @returns {Tone.Clock} this */ Tone.Clock.prototype.pause = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Paused, time); } return this; }; /** * The scheduling loop. * @param {Number} time The current page time starting from 0 * when the page was loaded. * @private */ Tone.Clock.prototype._loop = function (time) { this._loopID = requestAnimationFrame(this._boundLoop); //compute the look ahead if (this._lookAhead === 'auto') { if (!this.isUndef(time)) { var diff = (time - this._lastUpdate) / 1000; this._lastUpdate = time; //throw away large differences if (diff < this._threshold) { //averaging this._computedLookAhead = (9 * this._computedLookAhead + diff) / 10; } } } else { this._computedLookAhead = this._lookAhead; } //get the frequency value to compute the value of the next loop var now = this.now(); //if it's started var lookAhead = this._computedLookAhead * 2; var event = this._state.getEvent(now + lookAhead); var state = Tone.State.Stopped; if (event) { state = event.state; //if it was stopped and now started if (this._nextTick === -1 && state === Tone.State.Started) { this._nextTick = event.time; if (!this.isUndef(event.offset)) { this.ticks = event.offset; } } } if (state === Tone.State.Started) { while (now + lookAhead > this._nextTick) { //catch up if (now > this._nextTick + this._threshold) { this._nextTick = now; } var tickTime = this._nextTick; this._nextTick += 1 / this.frequency.getValueAtTime(this._nextTick); this.callback(tickTime); this.ticks++; } } else if (state === Tone.State.Stopped) { this._nextTick = -1; this.ticks = 0; } }; /** * Returns the scheduled state at the given time. * @param {Time} time The time to query. * @return {String} The name of the state input in setStateAtTime. * @example * clock.start("+0.1"); * clock.getStateAtTime("+0.1"); //returns "started" */ Tone.Clock.prototype.getStateAtTime = function (time) { return this._state.getStateAtTime(time); }; /** * Clean up * @returns {Tone.Clock} this */ Tone.Clock.prototype.dispose = function () { cancelAnimationFrame(this._loopID); Tone.TimelineState.prototype.dispose.call(this); this._writable('frequency'); this.frequency.dispose(); this.frequency = null; this._boundLoop = Tone.noOp; this._nextTick = Infinity; this.callback = null; this._state.dispose(); this._state = null; }; return Tone.Clock; }); Module(function (Tone) { /** * @class Tone.Emitter gives classes which extend it * the ability to listen for and trigger events. * Inspiration and reference from Jerome Etienne's [MicroEvent](https://github.com/jeromeetienne/microevent.js). * MIT (c) 2011 Jerome Etienne. * * @extends {Tone} */ Tone.Emitter = function () { /** * Contains all of the events. * @private * @type {Object} */ this._events = {}; }; Tone.extend(Tone.Emitter); /** * Bind a callback to a specific event. * @param {String} event The name of the event to listen for. * @param {Function} callback The callback to invoke when the * event is triggered * @return {Tone.Emitter} this */ Tone.Emitter.prototype.on = function (event, callback) { //split the event var events = event.split(/\W+/); for (var i = 0; i < events.length; i++) { var eventName = events[i]; if (!this._events.hasOwnProperty(eventName)) { this._events[eventName] = []; } this._events[eventName].push(callback); } return this; }; /** * Remove the event listener. * @param {String} event The event to stop listening to. * @param {Function=} callback The callback which was bound to * the event with Tone.Emitter.on. * If no callback is given, all callbacks * events are removed. * @return {Tone.Emitter} this */ Tone.Emitter.prototype.off = function (event, callback) { var events = event.split(/\W+/); for (var ev = 0; ev < events.length; ev++) { event = events[ev]; if (this._events.hasOwnProperty(event)) { if (Tone.prototype.isUndef(callback)) { this._events[event] = []; } else { var eventList = this._events[event]; for (var i = 0; i < eventList.length; i++) { if (eventList[i] === callback) { eventList.splice(i, 1); } } } } } return this; }; /** * Invoke all of the callbacks bound to the event * with any arguments passed in. * @param {String} event The name of the event. * @param {*...} args The arguments to pass to the functions listening. * @return {Tone.Emitter} this */ Tone.Emitter.prototype.trigger = function (event) { if (this._events) { var args = Array.prototype.slice.call(arguments, 1); if (this._events.hasOwnProperty(event)) { var eventList = this._events[event]; for (var i = 0, len = eventList.length; i < len; i++) { eventList[i].apply(this, args); } } } return this; }; /** * Add Emitter functions (on/off/trigger) to the object * @param {Object|Function} object The object or class to extend. */ Tone.Emitter.mixin = function (object) { var functions = [ 'on', 'off', 'trigger' ]; object._events = {}; for (var i = 0; i < functions.length; i++) { var func = functions[i]; var emitterFunc = Tone.Emitter.prototype[func]; object[func] = emitterFunc; } }; /** * Clean up * @return {Tone.Emitter} this */ Tone.Emitter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._events = null; return this; }; return Tone.Emitter; }); Module(function (Tone) { /** * @class Similar to Tone.Timeline, but all events represent * intervals with both "time" and "duration" times. The * events are placed in a tree structure optimized * for querying an intersection point with the timeline * events. Internally uses an [Interval Tree](https://en.wikipedia.org/wiki/Interval_tree) * to represent the data. * @extends {Tone} */ Tone.IntervalTimeline = function () { /** * The root node of the inteval tree * @type {IntervalNode} * @private */ this._root = null; /** * Keep track of the length of the timeline. * @type {Number} * @private */ this._length = 0; }; Tone.extend(Tone.IntervalTimeline); /** * The event to add to the timeline. All events must * have a time and duration value * @param {Object} event The event to add to the timeline * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.addEvent = function (event) { if (this.isUndef(event.time) || this.isUndef(event.duration)) { throw new Error('events must have time and duration parameters'); } var node = new IntervalNode(event.time, event.time + event.duration, event); if (this._root === null) { this._root = node; } else { this._root.insert(node); } this._length++; // Restructure tree to be balanced while (node !== null) { node.updateHeight(); node.updateMax(); this._rebalance(node); node = node.parent; } return this; }; /** * Remove an event from the timeline. * @param {Object} event The event to remove from the timeline * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.removeEvent = function (event) { if (this._root !== null) { var results = []; this._root.search(event.time, results); for (var i = 0; i < results.length; i++) { var node = results[i]; if (node.event === event) { this._removeNode(node); this._length--; break; } } } return this; }; /** * The number of items in the timeline. * @type {Number} * @memberOf Tone.IntervalTimeline# * @name length * @readOnly */ Object.defineProperty(Tone.IntervalTimeline.prototype, 'length', { get: function () { return this._length; } }); /** * Remove events whose time time is after the given time * @param {Time} time The time to query. * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.cancel = function (after) { after = this.toSeconds(after); this.forEachAfter(after, function (event) { this.removeEvent(event); }.bind(this)); return this; }; /** * Set the root node as the given node * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._setRoot = function (node) { this._root = node; if (this._root !== null) { this._root.parent = null; } }; /** * Replace the references to the node in the node's parent * with the replacement node. * @param {IntervalNode} node * @param {IntervalNode} replacement * @private */ Tone.IntervalTimeline.prototype._replaceNodeInParent = function (node, replacement) { if (node.parent !== null) { if (node.isLeftChild()) { node.parent.left = replacement; } else { node.parent.right = replacement; } this._rebalance(node.parent); } else { this._setRoot(replacement); } }; /** * Remove the node from the tree and replace it with * a successor which follows the schema. * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._removeNode = function (node) { if (node.left === null && node.right === null) { this._replaceNodeInParent(node, null); } else if (node.right === null) { this._replaceNodeInParent(node, node.left); } else if (node.left === null) { this._replaceNodeInParent(node, node.right); } else { var balance = node.getBalance(); var replacement, temp; if (balance > 0) { if (node.left.right === null) { replacement = node.left; replacement.right = node.right; temp = replacement; } else { replacement = node.left.right; while (replacement.right !== null) { replacement = replacement.right; } replacement.parent.right = replacement.left; temp = replacement.parent; replacement.left = node.left; replacement.right = node.right; } } else { if (node.right.left === null) { replacement = node.right; replacement.left = node.left; temp = replacement; } else { replacement = node.right.left; while (replacement.left !== null) { replacement = replacement.left; } replacement.parent = replacement.parent; replacement.parent.left = replacement.right; temp = replacement.parent; replacement.left = node.left; replacement.right = node.right; } } if (node.parent !== null) { if (node.isLeftChild()) { node.parent.left = replacement; } else { node.parent.right = replacement; } } else { this._setRoot(replacement); } // this._replaceNodeInParent(node, replacement); this._rebalance(temp); } node.dispose(); }; /** * Rotate the tree to the left * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rotateLeft = function (node) { var parent = node.parent; var isLeftChild = node.isLeftChild(); // Make node.right the new root of this sub tree (instead of node) var pivotNode = node.right; node.right = pivotNode.left; pivotNode.left = node; if (parent !== null) { if (isLeftChild) { parent.left = pivotNode; } else { parent.right = pivotNode; } } else { this._setRoot(pivotNode); } }; /** * Rotate the tree to the right * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rotateRight = function (node) { var parent = node.parent; var isLeftChild = node.isLeftChild(); // Make node.left the new root of this sub tree (instead of node) var pivotNode = node.left; node.left = pivotNode.right; pivotNode.right = node; if (parent !== null) { if (isLeftChild) { parent.left = pivotNode; } else { parent.right = pivotNode; } } else { this._setRoot(pivotNode); } }; /** * Balance the BST * @param {IntervalNode} node * @private */ Tone.IntervalTimeline.prototype._rebalance = function (node) { var balance = node.getBalance(); if (balance > 1) { if (node.left.getBalance() < 0) { this._rotateLeft(node.left); } else { this._rotateRight(node); } } else if (balance < -1) { if (node.right.getBalance() > 0) { this._rotateRight(node.right); } else { this._rotateLeft(node); } } }; /** * Get an event whose time and duration span the give time. Will * return the match whose "time" value is closest to the given time. * @param {Object} event The event to add to the timeline * @return {Object} The event which spans the desired time */ Tone.IntervalTimeline.prototype.getEvent = function (time) { if (this._root !== null) { var results = []; this._root.search(time, results); if (results.length > 0) { var max = results[0]; for (var i = 1; i < results.length; i++) { if (results[i].low > max.low) { max = results[i]; } } return max.event; } } return null; }; /** * Iterate over everything in the timeline. * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEach = function (callback) { if (this._root !== null) { var allNodes = []; if (this._root !== null) { this._root.traverse(function (node) { allNodes.push(node); }); } for (var i = 0; i < allNodes.length; i++) { var ev = allNodes[i].event; if (ev) { callback(ev); } } } return this; }; /** * Iterate over everything in the array in which the given time * overlaps with the time and duration time of the event. * @param {Time} time The time to check if items are overlapping * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEachOverlap = function (time, callback) { time = this.toSeconds(time); if (this._root !== null) { var results = []; this._root.search(time, results); for (var i = results.length - 1; i >= 0; i--) { var ev = results[i].event; if (ev) { callback(ev); } } } return this; }; /** * Iterate over everything in the array in which the time is greater * than the given time. * @param {Time} time The time to check if items are before * @param {Function} callback The callback to invoke with every item * @returns {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.forEachAfter = function (time, callback) { time = this.toSeconds(time); if (this._root !== null) { var results = []; this._root.searchAfter(time, results); for (var i = results.length - 1; i >= 0; i--) { var ev = results[i].event; if (ev) { callback(ev); } } } return this; }; /** * Clean up * @return {Tone.IntervalTimeline} this */ Tone.IntervalTimeline.prototype.dispose = function () { var allNodes = []; if (this._root !== null) { this._root.traverse(function (node) { allNodes.push(node); }); } for (var i = 0; i < allNodes.length; i++) { allNodes[i].dispose(); } allNodes = null; this._root = null; return this; }; /////////////////////////////////////////////////////////////////////////// // INTERVAL NODE HELPER /////////////////////////////////////////////////////////////////////////// /** * Represents a node in the binary search tree, with the addition * of a "high" value which keeps track of the highest value of * its children. * References: * https://brooknovak.wordpress.com/2013/12/07/augmented-interval-tree-in-c/ * http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf * @param {Number} low * @param {Number} high * @private */ var IntervalNode = function (low, high, event) { //the event container this.event = event; //the low value this.low = low; //the high value this.high = high; //the high value for this and all child nodes this.max = this.high; //the nodes to the left this._left = null; //the nodes to the right this._right = null; //the parent node this.parent = null; //the number of child nodes this.height = 0; }; /** * Insert a node into the correct spot in the tree * @param {IntervalNode} node */ IntervalNode.prototype.insert = function (node) { if (node.low <= this.low) { if (this.left === null) { this.left = node; } else { this.left.insert(node); } } else { if (this.right === null) { this.right = node; } else { this.right.insert(node); } } }; /** * Search the tree for nodes which overlap * with the given point * @param {Number} point The point to query * @param {Array} results The array to put the results */ IntervalNode.prototype.search = function (point, results) { // If p is to the right of the rightmost point of any interval // in this node and all children, there won't be any matches. if (point > this.max) { return; } // Search left children if (this.left !== null) { this.left.search(point, results); } // Check this node if (this.low <= point && this.high >= point) { results.push(this); } // If p is to the left of the time of this interval, // then it can't be in any child to the right. if (this.low > point) { return; } // Search right children if (this.right !== null) { this.right.search(point, results); } }; /** * Search the tree for nodes which are less * than the given point * @param {Number} point The point to query * @param {Array} results The array to put the results */ IntervalNode.prototype.searchAfter = function (point, results) { // Check this node if (this.low >= point) { results.push(this); if (this.left !== null) { this.left.searchAfter(point, results); } } // search the right side if (this.right !== null) { this.right.searchAfter(point, results); } }; /** * Invoke the callback on this element and both it's branches * @param {Function} callback */ IntervalNode.prototype.traverse = function (callback) { callback(this); if (this.left !== null) { this.left.traverse(callback); } if (this.right !== null) { this.right.traverse(callback); } }; /** * Update the height of the node */ IntervalNode.prototype.updateHeight = function () { if (this.left !== null && this.right !== null) { this.height = Math.max(this.left.height, this.right.height) + 1; } else if (this.right !== null) { this.height = this.right.height + 1; } else if (this.left !== null) { this.height = this.left.height + 1; } else { this.height = 0; } }; /** * Update the height of the node */ IntervalNode.prototype.updateMax = function () { this.max = this.high; if (this.left !== null) { this.max = Math.max(this.max, this.left.max); } if (this.right !== null) { this.max = Math.max(this.max, this.right.max); } }; /** * The balance is how the leafs are distributed on the node * @return {Number} Negative numbers are balanced to the right */ IntervalNode.prototype.getBalance = function () { var balance = 0; if (this.left !== null && this.right !== null) { balance = this.left.height - this.right.height; } else if (this.left !== null) { balance = this.left.height + 1; } else if (this.right !== null) { balance = -(this.right.height + 1); } return balance; }; /** * @returns {Boolean} true if this node is the left child * of its parent */ IntervalNode.prototype.isLeftChild = function () { return this.parent !== null && this.parent.left === this; }; /** * get/set the left node * @type {IntervalNode} */ Object.defineProperty(IntervalNode.prototype, 'left', { get: function () { return this._left; }, set: function (node) { this._left = node; if (node !== null) { node.parent = this; } this.updateHeight(); this.updateMax(); } }); /** * get/set the right node * @type {IntervalNode} */ Object.defineProperty(IntervalNode.prototype, 'right', { get: function () { return this._right; }, set: function (node) { this._right = node; if (node !== null) { node.parent = this; } this.updateHeight(); this.updateMax(); } }); /** * null out references. */ IntervalNode.prototype.dispose = function () { this.parent = null; this._left = null; this._right = null; this.event = null; }; /////////////////////////////////////////////////////////////////////////// // END INTERVAL NODE HELPER /////////////////////////////////////////////////////////////////////////// return Tone.IntervalTimeline; }); Module(function (Tone) { /** * @class Transport for timing musical events. * Supports tempo curves and time changes. Unlike browser-based timing (setInterval, requestAnimationFrame) * Tone.Transport timing events pass in the exact time of the scheduled event * in the argument of the callback function. Pass that time value to the object * you're scheduling. <br><br> * A single transport is created for you when the library is initialized. * <br><br> * The transport emits the events: "start", "stop", "pause", and "loop" which are * called with the time of that event as the argument. * * @extends {Tone.Emitter} * @singleton * @example * //repeated event every 8th note * Tone.Transport.setInterval(function(time){ * //do something with the time * }, "8n"); * @example * //one time event 1 second in the future * Tone.Transport.setTimeout(function(time){ * //do something with the time * }, 1); * @example * //event fixed to the Transports timeline. * Tone.Transport.setTimeline(function(time){ * //do something with the time * }, "16:0:0"); */ Tone.Transport = function () { Tone.Emitter.call(this); /////////////////////////////////////////////////////////////////////// // LOOPING ////////////////////////////////////////////////////////////////////// /** * If the transport loops or not. * @type {boolean} */ this.loop = false; /** * The loop start position in ticks * @type {Ticks} * @private */ this._loopStart = 0; /** * The loop end position in ticks * @type {Ticks} * @private */ this._loopEnd = 0; /////////////////////////////////////////////////////////////////////// // CLOCK/TEMPO ////////////////////////////////////////////////////////////////////// /** * Pulses per quarter is the number of ticks per quarter note. * @private * @type {Number} */ this._ppq = TransportConstructor.defaults.PPQ; /** * watches the main oscillator for timing ticks * initially starts at 120bpm * @private * @type {Tone.Clock} */ this._clock = new Tone.Clock({ 'callback': this._processTick.bind(this), 'frequency': 0 }); /** * The Beats Per Minute of the Transport. * @type {BPM} * @signal * @example * Tone.Transport.bpm.value = 80; * //ramp the bpm to 120 over 10 seconds * Tone.Transport.bpm.rampTo(120, 10); */ this.bpm = this._clock.frequency; this.bpm._toUnits = this._toUnits.bind(this); this.bpm._fromUnits = this._fromUnits.bind(this); this.bpm.units = Tone.Type.BPM; this.bpm.value = TransportConstructor.defaults.bpm; this._readOnly('bpm'); /** * The time signature, or more accurately the numerator * of the time signature over a denominator of 4. * @type {Number} * @private */ this._timeSignature = TransportConstructor.defaults.timeSignature; /////////////////////////////////////////////////////////////////////// // TIMELINE EVENTS ////////////////////////////////////////////////////////////////////// /** * All the events in an object to keep track by ID * @type {Object} * @private */ this._scheduledEvents = {}; /** * The event ID counter * @type {Number} * @private */ this._eventID = 0; /** * The scheduled events. * @type {Tone.Timeline} * @private */ this._timeline = new Tone.Timeline(); /** * Repeated events * @type {Array} * @private */ this._repeatedEvents = new Tone.IntervalTimeline(); /** * Events that occur once * @type {Array} * @private */ this._onceEvents = new Tone.Timeline(); /** * All of the synced Signals * @private * @type {Array} */ this._syncedSignals = []; /////////////////////////////////////////////////////////////////////// // SWING ////////////////////////////////////////////////////////////////////// var swingSeconds = this.notationToSeconds(TransportConstructor.defaults.swingSubdivision, TransportConstructor.defaults.bpm, TransportConstructor.defaults.timeSignature); /** * The subdivision of the swing * @type {Ticks} * @private */ this._swingTicks = swingSeconds / (60 / TransportConstructor.defaults.bpm) * this._ppq; /** * The swing amount * @type {NormalRange} * @private */ this._swingAmount = 0; }; Tone.extend(Tone.Transport, Tone.Emitter); /** * the defaults * @type {Object} * @const * @static */ Tone.Transport.defaults = { 'bpm': 120, 'swing': 0, 'swingSubdivision': '16n', 'timeSignature': 4, 'loopStart': 0, 'loopEnd': '4m', 'PPQ': 48 }; /////////////////////////////////////////////////////////////////////////////// // TICKS /////////////////////////////////////////////////////////////////////////////// /** * called on every tick * @param {number} tickTime clock relative tick time * @private */ Tone.Transport.prototype._processTick = function (tickTime) { //handle swing if (this._swingAmount > 0 && this._clock.ticks % this._ppq !== 0 && //not on a downbeat this._clock.ticks % this._swingTicks === 0) { //add some swing tickTime += this.ticksToSeconds(this._swingTicks) * this._swingAmount; } //do the loop test if (this.loop) { if (this._clock.ticks === this._loopEnd) { this.ticks = this._loopStart; this.trigger('loop', tickTime); } } var ticks = this._clock.ticks; //fire the next tick events if their time has come this._timeline.forEachAtTime(ticks, function (event) { event.callback(tickTime); }); //process the repeated events this._repeatedEvents.forEachOverlap(ticks, function (event) { if ((ticks - event.time) % event.interval === 0) { event.callback(tickTime); } }); //process the single occurrence events this._onceEvents.forEachBefore(ticks, function (event) { event.callback(tickTime); }); //and clear the single occurrence timeline this._onceEvents.cancelBefore(ticks); }; /////////////////////////////////////////////////////////////////////////////// // SCHEDULABLE EVENTS /////////////////////////////////////////////////////////////////////////////// /** * Schedule an event along the timeline. * @param {Function} callback The callback to be invoked at the time. * @param {Time} time The time to invoke the callback at. * @return {Number} The id of the event which can be used for canceling the event. * @example * //trigger the callback when the Transport reaches the desired time * Tone.Transport.schedule(function(time){ * envelope.triggerAttack(time); * }, "128i"); */ Tone.Transport.prototype.schedule = function (callback, time) { var event = { 'time': this.toTicks(time), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._timeline }; this._timeline.addEvent(event); return id; }; /** * Schedule a repeated event along the timeline. The event will fire * at the `interval` starting at the `startTime` and for the specified * `duration`. * @param {Function} callback The callback to invoke. * @param {Time} interval The duration between successive * callbacks. * @param {Time=} startTime When along the timeline the events should * start being invoked. * @param {Time} [duration=Infinity] How long the event should repeat. * @return {Number} The ID of the scheduled event. Use this to cancel * the event. * @example * //a callback invoked every eighth note after the first measure * Tone.Transport.scheduleRepeat(callback, "8n", "1m"); */ Tone.Transport.prototype.scheduleRepeat = function (callback, interval, startTime, duration) { if (interval <= 0) { throw new Error('repeat events must have an interval larger than 0'); } var event = { 'time': this.toTicks(startTime), 'duration': this.toTicks(this.defaultArg(duration, Infinity)), 'interval': this.toTicks(interval), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._repeatedEvents }; this._repeatedEvents.addEvent(event); return id; }; /** * Schedule an event that will be removed after it is invoked. * Note that if the given time is less than the current transport time, * the event will be invoked immediately. * @param {Function} callback The callback to invoke once. * @param {Time} time The time the callback should be invoked. * @returns {Number} The ID of the scheduled event. */ Tone.Transport.prototype.scheduleOnce = function (callback, time) { var event = { 'time': this.toTicks(time), 'callback': callback }; var id = this._eventID++; this._scheduledEvents[id.toString()] = { 'event': event, 'timeline': this._onceEvents }; this._onceEvents.addEvent(event); return id; }; /** * Clear the passed in event id from the timeline * @param {Number} eventId The id of the event. * @returns {Tone.Transport} this */ Tone.Transport.prototype.clear = function (eventId) { if (this._scheduledEvents.hasOwnProperty(eventId)) { var item = this._scheduledEvents[eventId.toString()]; item.timeline.removeEvent(item.event); delete this._scheduledEvents[eventId.toString()]; } return this; }; /** * Remove scheduled events from the timeline after * the given time. Repeated events will be removed * if their startTime is after the given time * @param {Time} [after=0] Clear all events after * this time. * @returns {Tone.Transport} this */ Tone.Transport.prototype.cancel = function (after) { after = this.defaultArg(after, 0); after = this.toTicks(after); this._timeline.cancel(after); this._onceEvents.cancel(after); this._repeatedEvents.cancel(after); return this; }; /////////////////////////////////////////////////////////////////////////////// // QUANTIZATION /////////////////////////////////////////////////////////////////////////////// /** * Returns the time closest time (equal to or after the given time) that aligns * to the subidivision. * @param {Time} time The time value to quantize to the given subdivision * @param {String} [subdivision="4n"] The subdivision to quantize to. * @return {Number} the time in seconds until the next subdivision. * @example * Tone.Transport.bpm.value = 120; * Tone.Transport.quantize("3 * 4n", "1m"); //return 0.5 * //if the clock is started, it will return a value less than 0.5 */ Tone.Transport.prototype.quantize = function (time, subdivision) { subdivision = this.defaultArg(subdivision, '4n'); var tickTime = this.toTicks(time); subdivision = this.toTicks(subdivision); var remainingTicks = subdivision - tickTime % subdivision; if (remainingTicks === subdivision) { remainingTicks = 0; } var now = this.now(); if (this.state === Tone.State.Started) { now = this._clock._nextTick; } return this.toSeconds(time, now) + this.ticksToSeconds(remainingTicks); }; /////////////////////////////////////////////////////////////////////////////// // START/STOP/PAUSE /////////////////////////////////////////////////////////////////////////////// /** * Returns the playback state of the source, either "started", "stopped", or "paused" * @type {Tone.State} * @readOnly * @memberOf Tone.Transport# * @name state */ Object.defineProperty(Tone.Transport.prototype, 'state', { get: function () { return this._clock.getStateAtTime(this.now()); } }); /** * Start the transport and all sources synced to the transport. * @param {Time} [time=now] The time when the transport should start. * @param {Time=} offset The timeline offset to start the transport. * @returns {Tone.Transport} this * @example * //start the transport in one second starting at beginning of the 5th measure. * Tone.Transport.start("+1", "4:0:0"); */ Tone.Transport.prototype.start = function (time, offset) { time = this.toSeconds(time); if (!this.isUndef(offset)) { offset = this.toTicks(offset); } else { offset = this.defaultArg(offset, this._clock.ticks); } //start the clock this._clock.start(time, offset); this.trigger('start', time, this.ticksToSeconds(offset)); return this; }; /** * Stop the transport and all sources synced to the transport. * @param {Time} [time=now] The time when the transport should stop. * @returns {Tone.Transport} this * @example * Tone.Transport.stop(); */ Tone.Transport.prototype.stop = function (time) { time = this.toSeconds(time); this._clock.stop(time); this.trigger('stop', time); return this; }; /** * Pause the transport and all sources synced to the transport. * @param {Time} [time=now] * @returns {Tone.Transport} this */ Tone.Transport.prototype.pause = function (time) { time = this.toSeconds(time); this._clock.pause(time); this.trigger('pause', time); return this; }; /////////////////////////////////////////////////////////////////////////////// // SETTERS/GETTERS /////////////////////////////////////////////////////////////////////////////// /** * The time signature as just the numerator over 4. * For example 4/4 would be just 4 and 6/8 would be 3. * @memberOf Tone.Transport# * @type {Number|Array} * @name timeSignature * @example * //common time * Tone.Transport.timeSignature = 4; * // 7/8 * Tone.Transport.timeSignature = [7, 8]; * //this will be reduced to a single number * Tone.Transport.timeSignature; //returns 3.5 */ Object.defineProperty(Tone.Transport.prototype, 'timeSignature', { get: function () { return this._timeSignature; }, set: function (timeSig) { if (this.isArray(timeSig)) { timeSig = timeSig[0] / timeSig[1] * 4; } this._timeSignature = timeSig; } }); /** * When the Tone.Transport.loop = true, this is the starting position of the loop. * @memberOf Tone.Transport# * @type {Time} * @name loopStart */ Object.defineProperty(Tone.Transport.prototype, 'loopStart', { get: function () { return this.ticksToSeconds(this._loopStart); }, set: function (startPosition) { this._loopStart = this.toTicks(startPosition); } }); /** * When the Tone.Transport.loop = true, this is the ending position of the loop. * @memberOf Tone.Transport# * @type {Time} * @name loopEnd */ Object.defineProperty(Tone.Transport.prototype, 'loopEnd', { get: function () { return this.ticksToSeconds(this._loopEnd); }, set: function (endPosition) { this._loopEnd = this.toTicks(endPosition); } }); /** * Set the loop start and stop at the same time. * @param {Time} startPosition * @param {Time} endPosition * @returns {Tone.Transport} this * @example * //loop over the first measure * Tone.Transport.setLoopPoints(0, "1m"); * Tone.Transport.loop = true; */ Tone.Transport.prototype.setLoopPoints = function (startPosition, endPosition) { this.loopStart = startPosition; this.loopEnd = endPosition; return this; }; /** * The swing value. Between 0-1 where 1 equal to * the note + half the subdivision. * @memberOf Tone.Transport# * @type {NormalRange} * @name swing */ Object.defineProperty(Tone.Transport.prototype, 'swing', { get: function () { return this._swingAmount * 2; }, set: function (amount) { //scale the values to a normal range this._swingAmount = amount * 0.5; } }); /** * Set the subdivision which the swing will be applied to. * The default values is a 16th note. Value must be less * than a quarter note. * * @memberOf Tone.Transport# * @type {Time} * @name swingSubdivision */ Object.defineProperty(Tone.Transport.prototype, 'swingSubdivision', { get: function () { return this.toNotation(this._swingTicks + 'i'); }, set: function (subdivision) { this._swingTicks = this.toTicks(subdivision); } }); /** * The Transport's position in MEASURES:BEATS:SIXTEENTHS. * Setting the value will jump to that position right away. * * @memberOf Tone.Transport# * @type {TransportTime} * @name position */ Object.defineProperty(Tone.Transport.prototype, 'position', { get: function () { var quarters = this.ticks / this._ppq; var measures = Math.floor(quarters / this._timeSignature); var sixteenths = quarters % 1 * 4; //if the sixteenths aren't a whole number, fix their length if (sixteenths % 1 > 0) { sixteenths = sixteenths.toFixed(3); } quarters = Math.floor(quarters) % this._timeSignature; var progress = [ measures, quarters, sixteenths ]; return progress.join(':'); }, set: function (progress) { var ticks = this.toTicks(progress); this.ticks = ticks; } }); /** * The Transport's loop position as a normalized value. Always * returns 0 if the transport if loop is not true. * @memberOf Tone.Transport# * @name progress * @type {NormalRange} */ Object.defineProperty(Tone.Transport.prototype, 'progress', { get: function () { if (this.loop) { return (this.ticks - this._loopStart) / (this._loopEnd - this._loopStart); } else { return 0; } } }); /** * The transports current tick position. * * @memberOf Tone.Transport# * @type {Ticks} * @name ticks */ Object.defineProperty(Tone.Transport.prototype, 'ticks', { get: function () { return this._clock.ticks; }, set: function (t) { this._clock.ticks = t; } }); /** * Pulses Per Quarter note. This is the smallest resolution * the Transport timing supports. This should be set once * on initialization and not set again. Changing this value * after other objects have been created can cause problems. * * @memberOf Tone.Transport# * @type {Number} * @name PPQ */ Object.defineProperty(Tone.Transport.prototype, 'PPQ', { get: function () { return this._ppq; }, set: function (ppq) { this._ppq = ppq; this.bpm.value = this.bpm.value; } }); /** * Convert from BPM to frequency (factoring in PPQ) * @param {BPM} bpm The BPM value to convert to frequency * @return {Frequency} The BPM as a frequency with PPQ factored in. * @private */ Tone.Transport.prototype._fromUnits = function (bpm) { return 1 / (60 / bpm / this.PPQ); }; /** * Convert from frequency (with PPQ) into BPM * @param {Frequency} freq The clocks frequency to convert to BPM * @return {BPM} The frequency value as BPM. * @private */ Tone.Transport.prototype._toUnits = function (freq) { return freq / this.PPQ * 60; }; /////////////////////////////////////////////////////////////////////////////// // SYNCING /////////////////////////////////////////////////////////////////////////////// /** * Attaches the signal to the tempo control signal so that * any changes in the tempo will change the signal in the same * ratio. * * @param {Tone.Signal} signal * @param {number=} ratio Optionally pass in the ratio between * the two signals. Otherwise it will be computed * based on their current values. * @returns {Tone.Transport} this */ Tone.Transport.prototype.syncSignal = function (signal, ratio) { if (!ratio) { //get the sync ratio if (signal._param.value !== 0) { ratio = signal._param.value / this.bpm._param.value; } else { ratio = 0; } } var ratioSignal = new Tone.Gain(ratio); this.bpm.chain(ratioSignal, signal._param); this._syncedSignals.push({ 'ratio': ratioSignal, 'signal': signal, 'initial': signal._param.value }); signal._param.value = 0; return this; }; /** * Unsyncs a previously synced signal from the transport's control. * See Tone.Transport.syncSignal. * @param {Tone.Signal} signal * @returns {Tone.Transport} this */ Tone.Transport.prototype.unsyncSignal = function (signal) { for (var i = this._syncedSignals.length - 1; i >= 0; i--) { var syncedSignal = this._syncedSignals[i]; if (syncedSignal.signal === signal) { syncedSignal.ratio.dispose(); syncedSignal.signal._param.value = syncedSignal.initial; this._syncedSignals.splice(i, 1); } } return this; }; /** * Clean up. * @returns {Tone.Transport} this * @private */ Tone.Transport.prototype.dispose = function () { Tone.Emitter.prototype.dispose.call(this); this._clock.dispose(); this._clock = null; this._writable('bpm'); this.bpm = null; this._timeline.dispose(); this._timeline = null; this._onceEvents.dispose(); this._onceEvents = null; this._repeatedEvents.dispose(); this._repeatedEvents = null; return this; }; /////////////////////////////////////////////////////////////////////////////// // DEPRECATED FUNCTIONS // (will be removed in r7) /////////////////////////////////////////////////////////////////////////////// /** * @deprecated Use Tone.scheduleRepeat instead. * Set a callback for a recurring event. * @param {function} callback * @param {Time} interval * @return {number} the id of the interval * @example * //triggers a callback every 8th note with the exact time of the event * Tone.Transport.setInterval(function(time){ * envelope.triggerAttack(time); * }, "8n"); * @private */ Tone.Transport.prototype.setInterval = function (callback, interval) { console.warn('This method is deprecated. Use Tone.Transport.scheduleRepeat instead.'); return Tone.Transport.scheduleRepeat(callback, interval); }; /** * @deprecated Use Tone.cancel instead. * Stop and ongoing interval. * @param {number} intervalID The ID of interval to remove. The interval * ID is given as the return value in Tone.Transport.setInterval. * @return {boolean} true if the event was removed * @private */ Tone.Transport.prototype.clearInterval = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /** * @deprecated Use Tone.Note instead. * Set a timeout to occur after time from now. NB: the transport must be * running for this to be triggered. All timeout events are cleared when the * transport is stopped. * * @param {function} callback * @param {Time} time The time (from now) that the callback will be invoked. * @return {number} The id of the timeout. * @example * //trigger an event to happen 1 second from now * Tone.Transport.setTimeout(function(time){ * player.start(time); * }, 1) * @private */ Tone.Transport.prototype.setTimeout = function (callback, timeout) { console.warn('This method is deprecated. Use Tone.Transport.scheduleOnce instead.'); return Tone.Transport.scheduleOnce(callback, timeout); }; /** * @deprecated Use Tone.Note instead. * Clear a timeout using it's ID. * @param {number} intervalID The ID of timeout to remove. The timeout * ID is given as the return value in Tone.Transport.setTimeout. * @return {boolean} true if the timeout was removed * @private */ Tone.Transport.prototype.clearTimeout = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /** * @deprecated Use Tone.Note instead. * Timeline events are synced to the timeline of the Tone.Transport. * Unlike Timeout, Timeline events will restart after the * Tone.Transport has been stopped and restarted. * * @param {function} callback * @param {Time} time * @return {number} the id for clearing the transportTimeline event * @example * //trigger the start of a part on the 16th measure * Tone.Transport.setTimeline(function(time){ * part.start(time); * }, "16m"); * @private */ Tone.Transport.prototype.setTimeline = function (callback, time) { console.warn('This method is deprecated. Use Tone.Transport.schedule instead.'); return Tone.Transport.schedule(callback, time); }; /** * @deprecated Use Tone.Note instead. * Clear the timeline event. * @param {number} id * @return {boolean} true if it was removed * @private */ Tone.Transport.prototype.clearTimeline = function (id) { console.warn('This method is deprecated. Use Tone.Transport.clear instead.'); return Tone.Transport.clear(id); }; /////////////////////////////////////////////////////////////////////////////// // INITIALIZATION /////////////////////////////////////////////////////////////////////////////// var TransportConstructor = Tone.Transport; Tone._initAudioContext(function () { if (typeof Tone.Transport === 'function') { //a single transport object Tone.Transport = new Tone.Transport(); } else { //stop the clock Tone.Transport.stop(); //get the previous values var prevSettings = Tone.Transport.get(); //destory the old transport Tone.Transport.dispose(); //make new Transport insides TransportConstructor.call(Tone.Transport); //set the previous config Tone.Transport.set(prevSettings); } }); return Tone.Transport; }); Module(function (Tone) { /** * @class Tone.Volume is a simple volume node, useful for creating a volume fader. * * @extends {Tone} * @constructor * @param {Decibels} [volume=0] the initial volume * @example * var vol = new Tone.Volume(-12); * instrument.chain(vol, Tone.Master); */ Tone.Volume = function () { var options = this.optionsObject(arguments, ['volume'], Tone.Volume.defaults); /** * the output node * @type {GainNode} * @private */ this.output = this.input = new Tone.Gain(options.volume, Tone.Type.Decibels); /** * The volume control in decibels. * @type {Decibels} * @signal */ this.volume = this.output.gain; this._readOnly('volume'); }; Tone.extend(Tone.Volume); /** * Defaults * @type {Object} * @const * @static */ Tone.Volume.defaults = { 'volume': 0 }; /** * clean up * @returns {Tone.Volume} this */ Tone.Volume.prototype.dispose = function () { this.input.dispose(); Tone.prototype.dispose.call(this); this._writable('volume'); this.volume.dispose(); this.volume = null; return this; }; return Tone.Volume; }); Module(function (Tone) { /** * @class Base class for sources. Sources have start/stop methods * and the ability to be synced to the * start/stop of Tone.Transport. * * @constructor * @extends {Tone} * @example * //Multiple state change events can be chained together, * //but must be set in the correct order and with ascending times * * // OK * state.start().stop("+0.2"); * // AND * state.start().stop("+0.2").start("+0.4").stop("+0.7") * * // BAD * state.stop("+0.2").start(); * // OR * state.start("+0.3").stop("+0.2"); * */ Tone.Source = function (options) { //Sources only have an output and no input Tone.call(this); options = this.defaultArg(options, Tone.Source.defaults); /** * The output volume node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume of the output in decibels. * @type {Decibels} * @signal * @example * source.volume.value = -6; */ this.volume = this._volume.volume; this._readOnly('volume'); /** * Keep track of the scheduled state. * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * The synced `start` callback function from the transport * @type {Function} * @private */ this._syncStart = function (time, offset) { time = this.toSeconds(time); time += this.toSeconds(this._startDelay); this.start(time, offset); }.bind(this); /** * The synced `stop` callback function from the transport * @type {Function} * @private */ this._syncStop = this.stop.bind(this); /** * The offset from the start of the Transport `start` * @type {Time} * @private */ this._startDelay = 0; //make the output explicitly stereo this._volume.output.output.channelCount = 2; this._volume.output.output.channelCountMode = 'explicit'; }; Tone.extend(Tone.Source); /** * The default parameters * @static * @const * @type {Object} */ Tone.Source.defaults = { 'volume': 0 }; /** * Returns the playback state of the source, either "started" or "stopped". * @type {Tone.State} * @readOnly * @memberOf Tone.Source# * @name state */ Object.defineProperty(Tone.Source.prototype, 'state', { get: function () { return this._state.getStateAtTime(this.now()); } }); /** * Start the source at the specified time. If no time is given, * start the source now. * @param {Time} [time=now] When the source should be started. * @returns {Tone.Source} this * @example * source.start("+0.5"); //starts the source 0.5 seconds from now */ Tone.Source.prototype.start = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) !== Tone.State.Started || this.retrigger) { this._state.setStateAtTime(Tone.State.Started, time); if (this._start) { this._start.apply(this, arguments); } } return this; }; /** * Stop the source at the specified time. If no time is given, * stop the source now. * @param {Time} [time=now] When the source should be stopped. * @returns {Tone.Source} this * @example * source.stop(); // stops the source immediately */ Tone.Source.prototype.stop = function (time) { time = this.toSeconds(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, time); if (this._stop) { this._stop.apply(this, arguments); } } return this; }; /** * Sync the source to the Transport so that when the transport * is started, this source is started and when the transport is stopped * or paused, so is the source. * * @param {Time} [delay=0] Delay time before starting the source after the * Transport has started. * @returns {Tone.Source} this * @example * //sync the source to start 1 measure after the transport starts * source.sync("1m"); * //start the transport. the source will start 1 measure later. * Tone.Transport.start(); */ Tone.Source.prototype.sync = function (delay) { this._startDelay = this.defaultArg(delay, 0); Tone.Transport.on('start', this._syncStart); Tone.Transport.on('stop pause', this._syncStop); return this; }; /** * Unsync the source to the Transport. See Tone.Source.sync * @returns {Tone.Source} this */ Tone.Source.prototype.unsync = function () { this._startDelay = 0; Tone.Transport.off('start', this._syncStart); Tone.Transport.off('stop pause', this._syncStop); return this; }; /** * Clean up. * @return {Tone.Source} this */ Tone.Source.prototype.dispose = function () { this.stop(); Tone.prototype.dispose.call(this); this.unsync(); this._writable('volume'); this._volume.dispose(); this._volume = null; this.volume = null; this._state.dispose(); this._state = null; this._syncStart = null; this._syncStart = null; }; return Tone.Source; }); Module(function (Tone) { /** * @class Tone.Oscillator supports a number of features including * phase rotation, multiple oscillator types (see Tone.Oscillator.type), * and Transport syncing (see Tone.Oscillator.syncFrequency). * * @constructor * @extends {Tone.Source} * @param {Frequency} [frequency] Starting frequency * @param {string} [type] The oscillator type. Read more about type below. * @example * //make and start a 440hz sine tone * var osc = new Tone.Oscillator(440, "sine").toMaster().start(); */ Tone.Oscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'type' ], Tone.Oscillator.defaults); Tone.Source.call(this, options); /** * the main oscillator * @type {OscillatorNode} * @private */ this._oscillator = null; /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune control signal. * @type {Cents} * @signal */ this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); /** * the periodic wave * @type {PeriodicWave} * @private */ this._wave = null; /** * The partials of the oscillator * @type {Array} * @private */ this._partials = this.defaultArg(options.partials, [1]); /** * the phase of the oscillator * between 0 - 360 * @type {number} * @private */ this._phase = options.phase; /** * the type of the oscillator * @type {string} * @private */ this._type = null; //setup this.type = options.type; this.phase = this._phase; this._readOnly([ 'frequency', 'detune' ]); }; Tone.extend(Tone.Oscillator, Tone.Source); /** * the default parameters * @type {Object} */ Tone.Oscillator.defaults = { 'type': 'sine', 'frequency': 440, 'detune': 0, 'phase': 0, 'partials': [] }; /** * The Oscillator types * @enum {String} */ Tone.Oscillator.Type = { Sine: 'sine', Triangle: 'triangle', Sawtooth: 'sawtooth', Square: 'square', Custom: 'custom' }; /** * start the oscillator * @param {Time} [time=now] * @private */ Tone.Oscillator.prototype._start = function (time) { //new oscillator with previous values this._oscillator = this.context.createOscillator(); this._oscillator.setPeriodicWave(this._wave); //connect the control signal to the oscillator frequency & detune this._oscillator.connect(this.output); this.frequency.connect(this._oscillator.frequency); this.detune.connect(this._oscillator.detune); //start the oscillator this._oscillator.start(this.toSeconds(time)); }; /** * stop the oscillator * @private * @param {Time} [time=now] (optional) timing parameter * @returns {Tone.Oscillator} this */ Tone.Oscillator.prototype._stop = function (time) { if (this._oscillator) { this._oscillator.stop(this.toSeconds(time)); this._oscillator = null; } return this; }; /** * Sync the signal to the Transport's bpm. Any changes to the transports bpm, * will also affect the oscillators frequency. * @returns {Tone.Oscillator} this * @example * Tone.Transport.bpm.value = 120; * osc.frequency.value = 440; * //the ration between the bpm and the frequency will be maintained * osc.syncFrequency(); * Tone.Transport.bpm.value = 240; * // the frequency of the oscillator is doubled to 880 */ Tone.Oscillator.prototype.syncFrequency = function () { Tone.Transport.syncSignal(this.frequency); return this; }; /** * Unsync the oscillator's frequency from the Transport. * See Tone.Oscillator.syncFrequency * @returns {Tone.Oscillator} this */ Tone.Oscillator.prototype.unsyncFrequency = function () { Tone.Transport.unsyncSignal(this.frequency); return this; }; /** * The type of the oscillator: either sine, square, triangle, or sawtooth. Also capable of * setting the first x number of partials of the oscillator. For example: "sine4" would * set be the first 4 partials of the sine wave and "triangle8" would set the first * 8 partials of the triangle wave. * <br><br> * Uses PeriodicWave internally even for native types so that it can set the phase. * PeriodicWave equations are from the * [Webkit Web Audio implementation](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp&sq=package:chromium). * * @memberOf Tone.Oscillator# * @type {string} * @name type * @example * //set it to a square wave * osc.type = "square"; * @example * //set the first 6 partials of a sawtooth wave * osc.type = "sawtooth6"; */ Object.defineProperty(Tone.Oscillator.prototype, 'type', { get: function () { return this._type; }, set: function (type) { var coefs = this._getRealImaginary(type, this._phase); var periodicWave = this.context.createPeriodicWave(coefs[0], coefs[1]); this._wave = periodicWave; if (this._oscillator !== null) { this._oscillator.setPeriodicWave(this._wave); } this._type = type; } }); /** * Returns the real and imaginary components based * on the oscillator type. * @returns {Array} [real, imaginary] * @private */ Tone.Oscillator.prototype._getRealImaginary = function (type, phase) { var fftSize = 4096; var periodicWaveSize = fftSize / 2; var real = new Float32Array(periodicWaveSize); var imag = new Float32Array(periodicWaveSize); var partialCount = 1; if (type === Tone.Oscillator.Type.Custom) { partialCount = this._partials.length + 1; periodicWaveSize = partialCount; } else { var partial = /^(sine|triangle|square|sawtooth)(\d+)$/.exec(type); if (partial) { partialCount = parseInt(partial[2]) + 1; type = partial[1]; partialCount = Math.max(partialCount, 2); periodicWaveSize = partialCount; } } for (var n = 1; n < periodicWaveSize; ++n) { var piFactor = 2 / (n * Math.PI); var b; switch (type) { case Tone.Oscillator.Type.Sine: b = n <= partialCount ? 1 : 0; break; case Tone.Oscillator.Type.Square: b = n & 1 ? 2 * piFactor : 0; break; case Tone.Oscillator.Type.Sawtooth: b = piFactor * (n & 1 ? 1 : -1); break; case Tone.Oscillator.Type.Triangle: if (n & 1) { b = 2 * (piFactor * piFactor) * (n - 1 >> 1 & 1 ? -1 : 1); } else { b = 0; } break; case Tone.Oscillator.Type.Custom: b = this._partials[n - 1]; break; default: throw new Error('invalid oscillator type: ' + type); } if (b !== 0) { real[n] = -b * Math.sin(phase * n); imag[n] = b * Math.cos(phase * n); } else { real[n] = 0; imag[n] = 0; } } return [ real, imag ]; }; /** * Compute the inverse FFT for a given phase. * @param {Float32Array} real * @param {Float32Array} imag * @param {NormalRange} phase * @return {AudioRange} * @private */ Tone.Oscillator.prototype._inverseFFT = function (real, imag, phase) { var sum = 0; var len = real.length; for (var i = 0; i < len; i++) { sum += real[i] * Math.cos(i * phase) + imag[i] * Math.sin(i * phase); } return sum; }; /** * Returns the initial value of the oscillator. * @return {AudioRange} * @private */ Tone.Oscillator.prototype._getInitialValue = function () { var coefs = this._getRealImaginary(this._type, 0); var real = coefs[0]; var imag = coefs[1]; var maxValue = 0; var twoPi = Math.PI * 2; //check for peaks in 8 places for (var i = 0; i < 8; i++) { maxValue = Math.max(this._inverseFFT(real, imag, i / 8 * twoPi), maxValue); } return -this._inverseFFT(real, imag, this._phase) / maxValue; }; /** * The partials of the waveform. A partial represents * the amplitude at a harmonic. The first harmonic is the * fundamental frequency, the second is the octave and so on * following the harmonic series. * Setting this value will automatically set the type to "custom". * The value is an empty array when the type is not "custom". * @memberOf Tone.Oscillator# * @type {Array} * @name partials * @example * osc.partials = [1, 0.2, 0.01]; */ Object.defineProperty(Tone.Oscillator.prototype, 'partials', { get: function () { if (this._type !== Tone.Oscillator.Type.Custom) { return []; } else { return this._partials; } }, set: function (partials) { this._partials = partials; this.type = Tone.Oscillator.Type.Custom; } }); /** * The phase of the oscillator in degrees. * @memberOf Tone.Oscillator# * @type {Degrees} * @name phase * @example * osc.phase = 180; //flips the phase of the oscillator */ Object.defineProperty(Tone.Oscillator.prototype, 'phase', { get: function () { return this._phase * (180 / Math.PI); }, set: function (phase) { this._phase = phase * Math.PI / 180; //reset the type this.type = this._type; } }); /** * Dispose and disconnect. * @return {Tone.Oscillator} this */ Tone.Oscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._oscillator !== null) { this._oscillator.disconnect(); this._oscillator = null; } this._wave = null; this._writable([ 'frequency', 'detune' ]); this.frequency.dispose(); this.frequency = null; this.detune.dispose(); this.detune = null; this._partials = null; return this; }; return Tone.Oscillator; }); Module(function (Tone) { /** * @class LFO stands for low frequency oscillator. Tone.LFO produces an output signal * which can be attached to an AudioParam or Tone.Signal * in order to modulate that parameter with an oscillator. The LFO can * also be synced to the transport to start/stop and change when the tempo changes. * * @constructor * @extends {Tone.Oscillator} * @param {Frequency|Object} [frequency] The frequency of the oscillation. Typically, LFOs will be * in the frequency range of 0.1 to 10 hertz. * @param {number=} min The minimum output value of the LFO. * @param {number=} max The maximum value of the LFO. * @example * var lfo = new Tone.LFO("4n", 400, 4000); * lfo.connect(filter.frequency); */ Tone.LFO = function () { var options = this.optionsObject(arguments, [ 'frequency', 'min', 'max' ], Tone.LFO.defaults); /** * The oscillator. * @type {Tone.Oscillator} * @private */ this._oscillator = new Tone.Oscillator({ 'frequency': options.frequency, 'type': options.type }); /** * the lfo's frequency * @type {Frequency} * @signal */ this.frequency = this._oscillator.frequency; /** * The amplitude of the LFO, which controls the output range between * the min and max output. For example if the min is -10 and the max * is 10, setting the amplitude to 0.5 would make the LFO modulate * between -5 and 5. * @type {Number} * @signal */ this.amplitude = this._oscillator.volume; this.amplitude.units = Tone.Type.NormalRange; this.amplitude.value = options.amplitude; /** * The signal which is output when the LFO is stopped * @type {Tone.Signal} * @private */ this._stoppedSignal = new Tone.Signal(0, Tone.Type.AudioRange); /** * The value that the LFO outputs when it's stopped * @type {AudioRange} * @private */ this._stoppedValue = 0; /** * @type {Tone.AudioToGain} * @private */ this._a2g = new Tone.AudioToGain(); /** * @type {Tone.Scale} * @private */ this._scaler = this.output = new Tone.Scale(options.min, options.max); /** * the units of the LFO (used for converting) * @type {Tone.Type} * @private */ this._units = Tone.Type.Default; this.units = options.units; //connect it up this._oscillator.chain(this._a2g, this._scaler); this._stoppedSignal.connect(this._a2g); this._readOnly([ 'amplitude', 'frequency' ]); this.phase = options.phase; }; Tone.extend(Tone.LFO, Tone.Oscillator); /** * the default parameters * * @static * @const * @type {Object} */ Tone.LFO.defaults = { 'type': 'sine', 'min': 0, 'max': 1, 'phase': 0, 'frequency': '4n', 'amplitude': 1, 'units': Tone.Type.Default }; /** * Start the LFO. * @param {Time} [time=now] the time the LFO will start * @returns {Tone.LFO} this */ Tone.LFO.prototype.start = function (time) { time = this.toSeconds(time); this._stoppedSignal.setValueAtTime(0, time); this._oscillator.start(time); return this; }; /** * Stop the LFO. * @param {Time} [time=now] the time the LFO will stop * @returns {Tone.LFO} this */ Tone.LFO.prototype.stop = function (time) { time = this.toSeconds(time); this._stoppedSignal.setValueAtTime(this._stoppedValue, time); this._oscillator.stop(time); return this; }; /** * Sync the start/stop/pause to the transport * and the frequency to the bpm of the transport * * @param {Time} [delay=0] the time to delay the start of the * LFO from the start of the transport * @returns {Tone.LFO} this * @example * lfo.frequency.value = "8n"; * lfo.sync(); * //the rate of the LFO will always be an eighth note, * //even as the tempo changes */ Tone.LFO.prototype.sync = function (delay) { this._oscillator.sync(delay); this._oscillator.syncFrequency(); return this; }; /** * unsync the LFO from transport control * @returns {Tone.LFO} this */ Tone.LFO.prototype.unsync = function () { this._oscillator.unsync(); this._oscillator.unsyncFrequency(); return this; }; /** * The miniumum output of the LFO. * @memberOf Tone.LFO# * @type {number} * @name min */ Object.defineProperty(Tone.LFO.prototype, 'min', { get: function () { return this._toUnits(this._scaler.min); }, set: function (min) { min = this._fromUnits(min); this._scaler.min = min; } }); /** * The maximum output of the LFO. * @memberOf Tone.LFO# * @type {number} * @name max */ Object.defineProperty(Tone.LFO.prototype, 'max', { get: function () { return this._toUnits(this._scaler.max); }, set: function (max) { max = this._fromUnits(max); this._scaler.max = max; } }); /** * The type of the oscillator: sine, square, sawtooth, triangle. * @memberOf Tone.LFO# * @type {string} * @name type */ Object.defineProperty(Tone.LFO.prototype, 'type', { get: function () { return this._oscillator.type; }, set: function (type) { this._oscillator.type = type; this._stoppedValue = this._oscillator._getInitialValue(); this._stoppedSignal.value = this._stoppedValue; } }); /** * The phase of the LFO. * @memberOf Tone.LFO# * @type {number} * @name phase */ Object.defineProperty(Tone.LFO.prototype, 'phase', { get: function () { return this._oscillator.phase; }, set: function (phase) { this._oscillator.phase = phase; this._stoppedValue = this._oscillator._getInitialValue(); this._stoppedSignal.value = this._stoppedValue; } }); /** * The output units of the LFO. * @memberOf Tone.LFO# * @type {Tone.Type} * @name units */ Object.defineProperty(Tone.LFO.prototype, 'units', { get: function () { return this._units; }, set: function (val) { var currentMin = this.min; var currentMax = this.max; //convert the min and the max this._units = val; this.min = currentMin; this.max = currentMax; } }); /** * Returns the playback state of the source, either "started" or "stopped". * @type {Tone.State} * @readOnly * @memberOf Tone.LFO# * @name state */ Object.defineProperty(Tone.LFO.prototype, 'state', { get: function () { return this._oscillator.state; } }); /** * Connect the output of the LFO to an AudioParam, AudioNode, or Tone Node. * Tone.LFO will automatically convert to the destination units of the * will get the units from the connected node. * @param {Tone | AudioParam | AudioNode} node * @param {number} [outputNum=0] optionally which output to connect from * @param {number} [inputNum=0] optionally which input to connect to * @returns {Tone.LFO} this * @private */ Tone.LFO.prototype.connect = function (node) { if (node.constructor === Tone.Signal || node.constructor === Tone.Param || node.constructor === Tone.TimelineSignal) { this.convert = node.convert; this.units = node.units; } Tone.Signal.prototype.connect.apply(this, arguments); return this; }; /** * private method borrowed from Param converts * units from their destination value * @function * @private */ Tone.LFO.prototype._fromUnits = Tone.Param.prototype._fromUnits; /** * private method borrowed from Param converts * units to their destination value * @function * @private */ Tone.LFO.prototype._toUnits = Tone.Param.prototype._toUnits; /** * disconnect and dispose * @returns {Tone.LFO} this */ Tone.LFO.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'amplitude', 'frequency' ]); this._oscillator.dispose(); this._oscillator = null; this._stoppedSignal.dispose(); this._stoppedSignal = null; this._scaler.dispose(); this._scaler = null; this._a2g.dispose(); this._a2g = null; this.frequency = null; this.amplitude = null; return this; }; return Tone.LFO; }); Module(function (Tone) { /** * @class Tone.Limiter will limit the loudness of an incoming signal. * It is composed of a Tone.Compressor with a fast attack * and release. Limiters are commonly used to safeguard against * signal clipping. Unlike a compressor, limiters do not provide * smooth gain reduction and almost completely prevent * additional gain above the threshold. * * @extends {Tone} * @constructor * @param {number} threshold The theshold above which the limiting is applied. * @example * var limiter = new Tone.Limiter(-6); */ Tone.Limiter = function () { var options = this.optionsObject(arguments, ['threshold'], Tone.Limiter.defaults); /** * the compressor * @private * @type {Tone.Compressor} */ this._compressor = this.input = this.output = new Tone.Compressor({ 'attack': 0.001, 'decay': 0.001, 'threshold': options.threshold }); /** * The threshold of of the limiter * @type {Decibel} * @signal */ this.threshold = this._compressor.threshold; this._readOnly('threshold'); }; Tone.extend(Tone.Limiter); /** * The default value * @type {Object} * @const * @static */ Tone.Limiter.defaults = { 'threshold': -12 }; /** * Clean up. * @returns {Tone.Limiter} this */ Tone.Limiter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._compressor.dispose(); this._compressor = null; this._writable('threshold'); this.threshold = null; return this; }; return Tone.Limiter; }); Module(function (Tone) { /** * @class Tone.Lowpass is a lowpass feedback comb filter. It is similar to * Tone.FeedbackCombFilter, but includes a lowpass filter. * * @extends {Tone} * @constructor * @param {Time|Object} [delayTime] The delay time of the comb filter * @param {NormalRange=} resonance The resonance (feedback) of the comb filter * @param {Frequency=} dampening The cutoff of the lowpass filter dampens the * signal as it is fedback. */ Tone.LowpassCombFilter = function () { Tone.call(this); var options = this.optionsObject(arguments, [ 'delayTime', 'resonance', 'dampening' ], Tone.LowpassCombFilter.defaults); /** * the delay node * @type {DelayNode} * @private */ this._delay = this.input = this.context.createDelay(1); /** * The delayTime of the comb filter. * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); /** * the lowpass filter * @type {BiquadFilterNode} * @private */ this._lowpass = this.output = this.context.createBiquadFilter(); this._lowpass.Q.value = 0; this._lowpass.type = 'lowpass'; /** * The dampening control of the feedback * @type {Frequency} * @signal */ this.dampening = new Tone.Param({ 'param': this._lowpass.frequency, 'units': Tone.Type.Frequency, 'value': options.dampening }); /** * the feedback gain * @type {GainNode} * @private */ this._feedback = this.context.createGain(); /** * The amount of feedback of the delayed signal. * @type {NormalRange} * @signal */ this.resonance = new Tone.Param({ 'param': this._feedback.gain, 'units': Tone.Type.NormalRange, 'value': options.resonance }); //connections this._delay.chain(this._lowpass, this._feedback, this._delay); this.delayTime.connect(this._delay.delayTime); this._readOnly([ 'dampening', 'resonance', 'delayTime' ]); }; Tone.extend(Tone.LowpassCombFilter); /** * the default parameters * @static * @const * @type {Object} */ Tone.LowpassCombFilter.defaults = { 'delayTime': 0.1, 'resonance': 0.5, 'dampening': 3000 }; /** * Clean up. * @returns {Tone.LowpassCombFilter} this */ Tone.LowpassCombFilter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'dampening', 'resonance', 'delayTime' ]); this.dampening.dispose(); this.dampening = null; this.resonance.dispose(); this.resonance = null; this._delay.disconnect(); this._delay = null; this._lowpass.disconnect(); this._lowpass = null; this._feedback.disconnect(); this._feedback = null; this.delayTime.dispose(); this.delayTime = null; return this; }; return Tone.LowpassCombFilter; }); Module(function (Tone) { /** * @class Tone.Merge brings two signals into the left and right * channels of a single stereo channel. * * @constructor * @extends {Tone} * @example * var merge = new Tone.Merge().toMaster(); * //routing a sine tone in the left channel * //and noise in the right channel * var osc = new Tone.Oscillator().connect(merge.left); * var noise = new Tone.Noise().connect(merge.right); * //starting our oscillators * noise.start(); * osc.start(); */ Tone.Merge = function () { Tone.call(this, 2, 0); /** * The left input channel. * Alias for <code>input[0]</code> * @type {GainNode} */ this.left = this.input[0] = this.context.createGain(); /** * The right input channel. * Alias for <code>input[1]</code>. * @type {GainNode} */ this.right = this.input[1] = this.context.createGain(); /** * the merger node for the two channels * @type {ChannelMergerNode} * @private */ this._merger = this.output = this.context.createChannelMerger(2); //connections this.left.connect(this._merger, 0, 0); this.right.connect(this._merger, 0, 1); this.left.channelCount = 1; this.right.channelCount = 1; this.left.channelCountMode = 'explicit'; this.right.channelCountMode = 'explicit'; }; Tone.extend(Tone.Merge); /** * Clean up. * @returns {Tone.Merge} this */ Tone.Merge.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.left.disconnect(); this.left = null; this.right.disconnect(); this.right = null; this._merger.disconnect(); this._merger = null; return this; }; return Tone.Merge; }); Module(function (Tone) { /** * @class Tone.Meter gets the [RMS](https://en.wikipedia.org/wiki/Root_mean_square) * of an input signal with some averaging applied. * It can also get the raw value of the signal or the value in dB. For signal * processing, it's better to use Tone.Follower which will produce an audio-rate * envelope follower instead of needing to poll the Meter to get the output. * <br><br> * Meter was inspired by [Chris Wilsons Volume Meter](https://github.com/cwilso/volume-meter/blob/master/volume-meter.js). * * @constructor * @extends {Tone} * @param {number} [channels=1] number of channels being metered * @param {number} [smoothing=0.8] amount of smoothing applied to the volume * @param {number} [clipMemory=0.5] number in seconds that a "clip" should be remembered * @example * var meter = new Tone.Meter(); * var mic = new Tone.Microphone().start(); * //connect mic to the meter * mic.connect(meter); * //use getLevel or getDb * //to access meter level * meter.getLevel(); */ Tone.Meter = function () { var options = this.optionsObject(arguments, [ 'channels', 'smoothing' ], Tone.Meter.defaults); //extends Unit Tone.call(this); /** * The channel count * @type {number} * @private */ this._channels = options.channels; /** * The amount which the decays of the meter are smoothed. Small values * will follow the contours of the incoming envelope more closely than large values. * @type {NormalRange} */ this.smoothing = options.smoothing; /** * The amount of time a clip is remember for. * @type {Time} */ this.clipMemory = options.clipMemory; /** * The value above which the signal is considered clipped. * @type {Number} */ this.clipLevel = options.clipLevel; /** * the rms for each of the channels * @private * @type {Array} */ this._volume = new Array(this._channels); /** * the raw values for each of the channels * @private * @type {Array} */ this._values = new Array(this._channels); //zero out the volume array for (var i = 0; i < this._channels; i++) { this._volume[i] = 0; this._values[i] = 0; } /** * last time the values clipped * @private * @type {Array} */ this._lastClip = new Array(this._channels); //zero out the clip array for (var j = 0; j < this._lastClip.length; j++) { this._lastClip[j] = 0; } /** * @private * @type {ScriptProcessorNode} */ this._jsNode = this.context.createScriptProcessor(options.bufferSize, this._channels, 1); this._jsNode.onaudioprocess = this._onprocess.bind(this); //so it doesn't get garbage collected this._jsNode.noGC(); //signal just passes this.input.connect(this.output); this.input.connect(this._jsNode); }; Tone.extend(Tone.Meter); /** * The defaults * @type {Object} * @static * @const */ Tone.Meter.defaults = { 'smoothing': 0.8, 'bufferSize': 1024, 'clipMemory': 0.5, 'clipLevel': 0.9, 'channels': 1 }; /** * called on each processing frame * @private * @param {AudioProcessingEvent} event */ Tone.Meter.prototype._onprocess = function (event) { var bufferSize = this._jsNode.bufferSize; var smoothing = this.smoothing; for (var channel = 0; channel < this._channels; channel++) { var input = event.inputBuffer.getChannelData(channel); var sum = 0; var total = 0; var x; for (var i = 0; i < bufferSize; i++) { x = input[i]; total += x; sum += x * x; } var average = total / bufferSize; var rms = Math.sqrt(sum / bufferSize); if (rms > 0.9) { this._lastClip[channel] = Date.now(); } this._volume[channel] = Math.max(rms, this._volume[channel] * smoothing); this._values[channel] = average; } }; /** * Get the rms of the signal. * @param {number} [channel=0] which channel * @return {number} the value */ Tone.Meter.prototype.getLevel = function (channel) { channel = this.defaultArg(channel, 0); var vol = this._volume[channel]; if (vol < 0.00001) { return 0; } else { return vol; } }; /** * Get the raw value of the signal. * @param {number=} channel * @return {number} */ Tone.Meter.prototype.getValue = function (channel) { channel = this.defaultArg(channel, 0); return this._values[channel]; }; /** * Get the volume of the signal in dB * @param {number=} channel * @return {Decibels} */ Tone.Meter.prototype.getDb = function (channel) { return this.gainToDb(this.getLevel(channel)); }; /** * @returns {boolean} if the audio has clipped. The value resets * based on the clipMemory defined. */ Tone.Meter.prototype.isClipped = function (channel) { channel = this.defaultArg(channel, 0); return Date.now() - this._lastClip[channel] < this._clipMemory * 1000; }; /** * Clean up. * @returns {Tone.Meter} this */ Tone.Meter.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._jsNode.disconnect(); this._jsNode.onaudioprocess = null; this._jsNode = null; this._volume = null; this._values = null; this._lastClip = null; return this; }; return Tone.Meter; }); Module(function (Tone) { /** * @class Tone.Split splits an incoming signal into left and right channels. * * @constructor * @extends {Tone} * @example * var split = new Tone.Split(); * stereoSignal.connect(split); */ Tone.Split = function () { Tone.call(this, 0, 2); /** * @type {ChannelSplitterNode} * @private */ this._splitter = this.input = this.context.createChannelSplitter(2); /** * Left channel output. * Alias for <code>output[0]</code> * @type {GainNode} */ this.left = this.output[0] = this.context.createGain(); /** * Right channel output. * Alias for <code>output[1]</code> * @type {GainNode} */ this.right = this.output[1] = this.context.createGain(); //connections this._splitter.connect(this.left, 0, 0); this._splitter.connect(this.right, 1, 0); }; Tone.extend(Tone.Split); /** * Clean up. * @returns {Tone.Split} this */ Tone.Split.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._splitter.disconnect(); this.left.disconnect(); this.right.disconnect(); this.left = null; this.right = null; this._splitter = null; return this; }; return Tone.Split; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels). <br><br> * <code> * Mid = (Left+Right)/sqrt(2); // obtain mid-signal from left and right<br> * Side = (Left-Right)/sqrt(2); // obtain side-signal from left and righ<br> * </code> * * @extends {Tone} * @constructor */ Tone.MidSideSplit = function () { Tone.call(this, 0, 2); /** * split the incoming signal into left and right channels * @type {Tone.Split} * @private */ this._split = this.input = new Tone.Split(); /** * The mid send. Connect to mid processing. Alias for * <code>output[0]</code> * @type {Tone.Expr} */ this.mid = this.output[0] = new Tone.Expr('($0 + $1) * $2'); /** * The side output. Connect to side processing. Alias for * <code>output[1]</code> * @type {Tone.Expr} */ this.side = this.output[1] = new Tone.Expr('($0 - $1) * $2'); this._split.connect(this.mid, 0, 0); this._split.connect(this.mid, 1, 1); this._split.connect(this.side, 0, 0); this._split.connect(this.side, 1, 1); sqrtTwo.connect(this.mid, 0, 2); sqrtTwo.connect(this.side, 0, 2); }; Tone.extend(Tone.MidSideSplit); /** * a constant signal equal to 1 / sqrt(2) * @type {Number} * @signal * @private * @static */ var sqrtTwo = null; Tone._initAudioContext(function () { sqrtTwo = new Tone.Signal(1 / Math.sqrt(2)); }); /** * clean up * @returns {Tone.MidSideSplit} this */ Tone.MidSideSplit.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.mid.dispose(); this.mid = null; this.side.dispose(); this.side = null; this._split.dispose(); this._split = null; return this; }; return Tone.MidSideSplit; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels). * MidSideMerge merges the mid and side signal after they've been seperated * by Tone.MidSideSplit.<br><br> * <code> * Left = (Mid+Side)/sqrt(2); // obtain left signal from mid and side<br> * Right = (Mid-Side)/sqrt(2); // obtain right signal from mid and side<br> * </code> * * @extends {Tone.StereoEffect} * @constructor */ Tone.MidSideMerge = function () { Tone.call(this, 2, 0); /** * The mid signal input. Alias for * <code>input[0]</code> * @type {GainNode} */ this.mid = this.input[0] = this.context.createGain(); /** * recombine the mid/side into Left * @type {Tone.Expr} * @private */ this._left = new Tone.Expr('($0 + $1) * $2'); /** * The side signal input. Alias for * <code>input[1]</code> * @type {GainNode} */ this.side = this.input[1] = this.context.createGain(); /** * recombine the mid/side into Right * @type {Tone.Expr} * @private */ this._right = new Tone.Expr('($0 - $1) * $2'); /** * Merge the left/right signal back into a stereo signal. * @type {Tone.Merge} * @private */ this._merge = this.output = new Tone.Merge(); this.mid.connect(this._left, 0, 0); this.side.connect(this._left, 0, 1); this.mid.connect(this._right, 0, 0); this.side.connect(this._right, 0, 1); this._left.connect(this._merge, 0, 0); this._right.connect(this._merge, 0, 1); sqrtTwo.connect(this._left, 0, 2); sqrtTwo.connect(this._right, 0, 2); }; Tone.extend(Tone.MidSideMerge); /** * A constant signal equal to 1 / sqrt(2). * @type {Number} * @signal * @private * @static */ var sqrtTwo = null; Tone._initAudioContext(function () { sqrtTwo = new Tone.Signal(1 / Math.sqrt(2)); }); /** * clean up * @returns {Tone.MidSideMerge} this */ Tone.MidSideMerge.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.mid.disconnect(); this.mid = null; this.side.disconnect(); this.side = null; this._left.dispose(); this._left = null; this._right.dispose(); this._right = null; this._merge.dispose(); this._merge = null; return this; }; return Tone.MidSideMerge; }); Module(function (Tone) { /** * @class Tone.MidSideCompressor applies two different compressors to the mid * and side signal components. See Tone.MidSideSplit. * * @extends {Tone} * @param {Object} options The options that are passed to the mid and side * compressors. * @constructor */ Tone.MidSideCompressor = function (options) { options = this.defaultArg(options, Tone.MidSideCompressor.defaults); /** * the mid/side split * @type {Tone.MidSideSplit} * @private */ this._midSideSplit = this.input = new Tone.MidSideSplit(); /** * the mid/side recombination * @type {Tone.MidSideMerge} * @private */ this._midSideMerge = this.output = new Tone.MidSideMerge(); /** * The compressor applied to the mid signal * @type {Tone.Compressor} */ this.mid = new Tone.Compressor(options.mid); /** * The compressor applied to the side signal * @type {Tone.Compressor} */ this.side = new Tone.Compressor(options.side); this._midSideSplit.mid.chain(this.mid, this._midSideMerge.mid); this._midSideSplit.side.chain(this.side, this._midSideMerge.side); this._readOnly([ 'mid', 'side' ]); }; Tone.extend(Tone.MidSideCompressor); /** * @const * @static * @type {Object} */ Tone.MidSideCompressor.defaults = { 'mid': { 'ratio': 3, 'threshold': -24, 'release': 0.03, 'attack': 0.02, 'knee': 16 }, 'side': { 'ratio': 6, 'threshold': -30, 'release': 0.25, 'attack': 0.03, 'knee': 10 } }; /** * Clean up. * @returns {Tone.MidSideCompressor} this */ Tone.MidSideCompressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'mid', 'side' ]); this.mid.dispose(); this.mid = null; this.side.dispose(); this.side = null; this._midSideSplit.dispose(); this._midSideSplit = null; this._midSideMerge.dispose(); this._midSideMerge = null; return this; }; return Tone.MidSideCompressor; }); Module(function (Tone) { /** * @class Tone.Mono coerces the incoming mono or stereo signal into a mono signal * where both left and right channels have the same value. This can be useful * for [stereo imaging](https://en.wikipedia.org/wiki/Stereo_imaging). * * @extends {Tone} * @constructor */ Tone.Mono = function () { Tone.call(this, 1, 0); /** * merge the signal * @type {Tone.Merge} * @private */ this._merge = this.output = new Tone.Merge(); this.input.connect(this._merge, 0, 0); this.input.connect(this._merge, 0, 1); this.input.gain.value = this.dbToGain(-10); }; Tone.extend(Tone.Mono); /** * clean up * @returns {Tone.Mono} this */ Tone.Mono.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._merge.dispose(); this._merge = null; return this; }; return Tone.Mono; }); Module(function (Tone) { /** * @class A compressor with seperate controls over low/mid/high dynamics * * @extends {Tone} * @constructor * @param {Object} options The low/mid/high compressor settings. * @example * var multiband = new Tone.MultibandCompressor({ * "lowFrequency" : 200, * "highFrequency" : 1300 * "low" : { * "threshold" : -12 * } * }) */ Tone.MultibandCompressor = function (options) { options = this.defaultArg(arguments, Tone.MultibandCompressor.defaults); /** * split the incoming signal into high/mid/low * @type {Tone.MultibandSplit} * @private */ this._splitter = this.input = new Tone.MultibandSplit({ 'lowFrequency': options.lowFrequency, 'highFrequency': options.highFrequency }); /** * low/mid crossover frequency. * @type {Frequency} * @signal */ this.lowFrequency = this._splitter.lowFrequency; /** * mid/high crossover frequency. * @type {Frequency} * @signal */ this.highFrequency = this._splitter.highFrequency; /** * the output * @type {GainNode} * @private */ this.output = this.context.createGain(); /** * The compressor applied to the low frequencies. * @type {Tone.Compressor} */ this.low = new Tone.Compressor(options.low); /** * The compressor applied to the mid frequencies. * @type {Tone.Compressor} */ this.mid = new Tone.Compressor(options.mid); /** * The compressor applied to the high frequencies. * @type {Tone.Compressor} */ this.high = new Tone.Compressor(options.high); //connect the compressor this._splitter.low.chain(this.low, this.output); this._splitter.mid.chain(this.mid, this.output); this._splitter.high.chain(this.high, this.output); this._readOnly([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); }; Tone.extend(Tone.MultibandCompressor); /** * @const * @static * @type {Object} */ Tone.MultibandCompressor.defaults = { 'low': Tone.Compressor.defaults, 'mid': Tone.Compressor.defaults, 'high': Tone.Compressor.defaults, 'lowFrequency': 250, 'highFrequency': 2000 }; /** * clean up * @returns {Tone.MultibandCompressor} this */ Tone.MultibandCompressor.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._splitter.dispose(); this._writable([ 'high', 'mid', 'low', 'highFrequency', 'lowFrequency' ]); this.low.dispose(); this.mid.dispose(); this.high.dispose(); this._splitter = null; this.low = null; this.mid = null; this.high = null; this.lowFrequency = null; this.highFrequency = null; return this; }; return Tone.MultibandCompressor; }); Module(function (Tone) { /** * @class Maps a NormalRange [0, 1] to an AudioRange [-1, 1]. * See also Tone.AudioToGain. * * @extends {Tone.SignalBase} * @constructor * @example * var g2a = new Tone.GainToAudio(); */ Tone.GainToAudio = function () { /** * @type {WaveShaperNode} * @private */ this._norm = this.input = this.output = new Tone.WaveShaper(function (x) { return Math.abs(x) * 2 - 1; }); }; Tone.extend(Tone.GainToAudio, Tone.SignalBase); /** * clean up * @returns {Tone.GainToAudio} this */ Tone.GainToAudio.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._norm.dispose(); this._norm = null; return this; }; return Tone.GainToAudio; }); Module(function (Tone) { /** * @class Tone.Panner is an equal power Left/Right Panner and does not * support 3D. Panner uses the StereoPannerNode when available. * * @constructor * @extends {Tone} * @param {NormalRange} [initialPan=0.5] The initail panner value (defaults to 0.5 = center) * @example * //pan the input signal hard right. * var panner = new Tone.Panner(1); */ Tone.Panner = function (initialPan) { Tone.call(this); /** * indicates if the panner is using the new StereoPannerNode internally * @type {boolean} * @private */ this._hasStereoPanner = this.isFunction(this.context.createStereoPanner); if (this._hasStereoPanner) { /** * the panner node * @type {StereoPannerNode} * @private */ this._panner = this.input = this.output = this.context.createStereoPanner(); /** * The pan control. 0 = hard left, 1 = hard right. * @type {NormalRange} * @signal */ this.pan = new Tone.Signal(0, Tone.Type.NormalRange); /** * scale the pan signal to between -1 and 1 * @type {Tone.WaveShaper} * @private */ this._scalePan = new Tone.GainToAudio(); //connections this.pan.chain(this._scalePan, this._panner.pan); } else { /** * the dry/wet knob * @type {Tone.CrossFade} * @private */ this._crossFade = new Tone.CrossFade(); /** * @type {Tone.Merge} * @private */ this._merger = this.output = new Tone.Merge(); /** * @type {Tone.Split} * @private */ this._splitter = this.input = new Tone.Split(); /** * The pan control. 0 = hard left, 1 = hard right. * @type {NormalRange} * @signal */ this.pan = this._crossFade.fade; //CONNECTIONS: //left channel is a, right channel is b this._splitter.connect(this._crossFade, 0, 0); this._splitter.connect(this._crossFade, 1, 1); //merge it back together this._crossFade.a.connect(this._merger, 0, 0); this._crossFade.b.connect(this._merger, 0, 1); } //initial value this.pan.value = this.defaultArg(initialPan, 0.5); this._readOnly('pan'); }; Tone.extend(Tone.Panner); /** * Clean up. * @returns {Tone.Panner} this */ Tone.Panner.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('pan'); if (this._hasStereoPanner) { this._panner.disconnect(); this._panner = null; this.pan.dispose(); this.pan = null; this._scalePan.dispose(); this._scalePan = null; } else { this._crossFade.dispose(); this._crossFade = null; this._splitter.dispose(); this._splitter = null; this._merger.dispose(); this._merger = null; this.pan = null; } return this; }; return Tone.Panner; }); Module(function (Tone) { /** * @class Tone.PanVol is a Tone.Panner and Tone.Volume in one. * * @extends {Tone} * @constructor * @param {NormalRange} pan the initial pan * @param {number} volume The output volume. * @example * //pan the incoming signal left and drop the volume * var panVol = new Tone.PanVol(0.25, -12); */ Tone.PanVol = function () { var options = this.optionsObject(arguments, [ 'pan', 'volume' ], Tone.PanVol.defaults); /** * The panning node * @type {Tone.Panner} * @private */ this._panner = this.input = new Tone.Panner(options.pan); /** * The L/R panning control. * @type {NormalRange} * @signal */ this.pan = this._panner.pan; /** * The volume node * @type {Tone.Volume} */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume control in decibels. * @type {Decibels} * @signal */ this.volume = this._volume.volume; //connections this._panner.connect(this._volume); this._readOnly([ 'pan', 'volume' ]); }; Tone.extend(Tone.PanVol); /** * The defaults * @type {Object} * @const * @static */ Tone.PanVol.defaults = { 'pan': 0.5, 'volume': 0 }; /** * clean up * @returns {Tone.PanVol} this */ Tone.PanVol.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable([ 'pan', 'volume' ]); this._panner.dispose(); this._panner = null; this.pan = null; this._volume.dispose(); this._volume = null; this.volume = null; return this; }; return Tone.PanVol; }); Module(function (Tone) { /** * @class Tone.CtrlInterpolate will interpolate between given values based * on the "index" property. Passing in an array or object literal * will interpolate each of the parameters. Note (i.e. "C3") * and Time (i.e. "4n + 2") can be interpolated. All other values are * assumed to be numbers. * @example * var interp = new Tone.CtrlInterpolate([0, 2, 9, 4]); * interp.index = 0.75; * interp.value; //returns 1.5 * * @example * var interp = new Tone.CtrlInterpolate([ * ["C3", "G4", "E5"], * ["D4", "F#4", "E5"], * ]); * @param {Array} values The array of values to interpolate over * @param {Positive} index The initial interpolation index. * @extends {Tone} */ Tone.CtrlInterpolate = function () { var options = this.optionsObject(arguments, [ 'values', 'index' ], Tone.CtrlInterpolate.defaults); /** * The values to interpolate between * @type {Array} */ this.values = options.values; /** * The interpolated index between values. For example: a value of 1.5 * would interpolate equally between the value at index 1 * and the value at index 2. * @example * interp.index = 0; * interp.value; //returns the value at 0 * interp.index = 0.5; * interp.value; //returns the value between indices 0 and 1. * @type {Positive} */ this.index = options.index; }; Tone.extend(Tone.CtrlInterpolate); /** * The defaults * @const * @type {Object} */ Tone.CtrlInterpolate.defaults = { 'index': 0, 'values': [] }; /** * The current interpolated value based on the index * @readOnly * @memberOf Tone.CtrlInterpolate# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlInterpolate.prototype, 'value', { get: function () { var index = this.index; index = Math.min(index, this.values.length - 1); var lowerPosition = Math.floor(index); var lower = this.values[lowerPosition]; var upper = this.values[Math.ceil(index)]; return this._interpolate(index - lowerPosition, lower, upper); } }); /** * Internal interpolation routine * @param {NormalRange} index The index between the lower and upper * @param {*} lower * @param {*} upper * @return {*} The interpolated value * @private */ Tone.CtrlInterpolate.prototype._interpolate = function (index, lower, upper) { if (this.isArray(lower)) { var retArray = []; for (var i = 0; i < lower.length; i++) { retArray[i] = this._interpolate(index, lower[i], upper[i]); } return retArray; } else if (this.isObject(lower)) { var retObj = {}; for (var attr in lower) { retObj[attr] = this._interpolate(index, lower[attr], upper[attr]); } return retObj; } else { lower = this._toNumber(lower); upper = this._toNumber(upper); return (1 - index) * lower + index * upper; } }; /** * Convert from the given type into a number * @param {Number|String} value * @return {Number} * @private */ Tone.CtrlInterpolate.prototype._toNumber = function (val) { if (this.isNumber(val)) { return val; } else if (this.isNote(val)) { return this.toFrequency(val); } else { //otherwise assume that it's Time... return this.toSeconds(val); } }; /** * Clean up * @return {Tone.CtrlInterpolate} this */ Tone.CtrlInterpolate.prototype.dispose = function () { this.values = null; }; return Tone.CtrlInterpolate; }); Module(function (Tone) { /** * @class Tone.CtrlMarkov represents a Markov Chain where each call * to Tone.CtrlMarkov.next will move to the next state. If the next * state choice is an array, the next state is chosen randomly with * even probability for all of the choices. For a weighted probability * of the next choices, pass in an object with "state" and "probability" attributes. * The probabilities will be normalized and then chosen. If no next options * are given for the current state, the state will stay there. * @extends {Tone} * @example * var chain = new Tone.CtrlMarkov({ * "beginning" : ["end", "middle"], * "middle" : "end" * }); * chain.value = "beginning"; * chain.next(); //returns "end" or "middle" with 50% probability * * @example * var chain = new Tone.CtrlMarkov({ * "beginning" : [{"value" : "end", "probability" : 0.8}, * {"value" : "middle", "probability" : 0.2}], * "middle" : "end" * }); * chain.value = "beginning"; * chain.next(); //returns "end" with 80% probability or "middle" with 20%. * @param {Object} values An object with the state names as the keys * and the next state(s) as the values. */ Tone.CtrlMarkov = function (values, initial) { /** * The Markov values with states as the keys * and next state(s) as the values. * @type {Object} */ this.values = this.defaultArg(values, {}); /** * The current state of the Markov values. The next * state will be evaluated and returned when Tone.CtrlMarkov.next * is invoked. * @type {String} */ this.value = this.defaultArg(initial, Object.keys(this.values)[0]); }; Tone.extend(Tone.CtrlMarkov); /** * Returns the next state of the Markov values. * @return {String} */ Tone.CtrlMarkov.prototype.next = function () { if (this.values.hasOwnProperty(this.value)) { var next = this.values[this.value]; if (this.isArray(next)) { var distribution = this._getProbDistribution(next); var rand = Math.random(); var total = 0; for (var i = 0; i < distribution.length; i++) { var dist = distribution[i]; if (rand > total && rand < total + dist) { var chosen = next[i]; if (this.isObject(chosen)) { this.value = chosen.value; } else { this.value = chosen; } } total += dist; } } else { this.value = next; } } return this.value; }; /** * Choose randomly from an array weighted options in the form * {"state" : string, "probability" : number} or an array of values * @param {Array} options * @return {Array} The randomly selected choice * @private */ Tone.CtrlMarkov.prototype._getProbDistribution = function (options) { var distribution = []; var total = 0; var needsNormalizing = false; for (var i = 0; i < options.length; i++) { var option = options[i]; if (this.isObject(option)) { needsNormalizing = true; distribution[i] = option.probability; } else { distribution[i] = 1 / options.length; } total += distribution[i]; } if (needsNormalizing) { //normalize the values for (var j = 0; j < distribution.length; j++) { distribution[j] = distribution[j] / total; } } return distribution; }; /** * Clean up * @return {Tone.CtrlMarkov} this */ Tone.CtrlMarkov.prototype.dispose = function () { this.values = null; }; return Tone.CtrlMarkov; }); Module(function (Tone) { /** * @class Generate patterns from an array of values. * Has a number of arpeggiation and randomized * selection patterns. * <ul> * <li>"up" - cycles upward</li> * <li>"down" - cycles downward</li> * <li>"upDown" - up then and down</li> * <li>"downUp" - cycles down then and up</li> * <li>"alternateUp" - jump up two and down one</li> * <li>"alternateDown" - jump down two and up one</li> * <li>"random" - randomly select an index</li> * <li>"randomWalk" - randomly moves one index away from the current position</li> * <li>"randomOnce" - randomly select an index without repeating until all values have been chosen.</li> * </ul> * @param {Array} values An array of options to choose from. * @param {Tone.CtrlPattern.Type=} type The name of the pattern. * @extends {Tone} */ Tone.CtrlPattern = function () { var options = this.optionsObject(arguments, [ 'values', 'type' ], Tone.CtrlPattern.defaults); /** * The array of values to arpeggiate over * @type {Array} */ this.values = options.values; /** * The current position in the values array * @type {Number} */ this.index = 0; /** * The type placeholder * @type {Tone.CtrlPattern.Type} * @private */ this._type = null; /** * Shuffled values for the RandomOnce type * @type {Array} * @private */ this._shuffled = null; /** * The direction of the movement * @type {String} * @private */ this._direction = null; this.type = options.type; }; Tone.extend(Tone.CtrlPattern); /** * The Control Patterns * @type {Object} * @static */ Tone.CtrlPattern.Type = { Up: 'up', Down: 'down', UpDown: 'upDown', DownUp: 'downUp', AlternateUp: 'alternateUp', AlternateDown: 'alternateDown', Random: 'random', RandomWalk: 'randomWalk', RandomOnce: 'randomOnce' }; /** * The default values. * @type {Object} */ Tone.CtrlPattern.defaults = { 'type': Tone.CtrlPattern.Type.Up, 'values': [] }; /** * The value at the current index of the pattern. * @readOnly * @memberOf Tone.CtrlPattern# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlPattern.prototype, 'value', { get: function () { //some safeguards if (this.values.length === 0) { return; } else if (this.values.length === 1) { return this.values[0]; } this.index = Math.min(this.index, this.values.length - 1); var val = this.values[this.index]; if (this.type === Tone.CtrlPattern.Type.RandomOnce) { if (this.values.length !== this._shuffled.length) { this._shuffleValues(); } val = this.values[this._shuffled[this.index]]; } return val; } }); /** * The pattern used to select the next * item from the values array * @memberOf Tone.CtrlPattern# * @type {Tone.CtrlPattern.Type} * @name type */ Object.defineProperty(Tone.CtrlPattern.prototype, 'type', { get: function () { return this._type; }, set: function (type) { this._type = type; this._shuffled = null; //the first index if (this._type === Tone.CtrlPattern.Type.Up || this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.RandomOnce || this._type === Tone.CtrlPattern.Type.AlternateUp) { this.index = 0; } else if (this._type === Tone.CtrlPattern.Type.Down || this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { this.index = this.values.length - 1; } //the direction if (this._type === Tone.CtrlPattern.Type.UpDown || this._type === Tone.CtrlPattern.Type.AlternateUp) { this._direction = Tone.CtrlPattern.Type.Up; } else if (this._type === Tone.CtrlPattern.Type.DownUp || this._type === Tone.CtrlPattern.Type.AlternateDown) { this._direction = Tone.CtrlPattern.Type.Down; } //randoms if (this._type === Tone.CtrlPattern.Type.RandomOnce) { this._shuffleValues(); } else if (this._type === Tone.CtrlPattern.Random) { this.index = Math.floor(Math.random() * this.values.length); } } }); /** * Return the next value given the current position * and pattern. * @return {*} The next value */ Tone.CtrlPattern.prototype.next = function () { var type = this.type; //choose the next index if (type === Tone.CtrlPattern.Type.Up) { this.index++; if (this.index >= this.values.length) { this.index = 0; } } else if (type === Tone.CtrlPattern.Type.Down) { this.index--; if (this.index < 0) { this.index = this.values.length - 1; } } else if (type === Tone.CtrlPattern.Type.UpDown || type === Tone.CtrlPattern.Type.DownUp) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index++; } else { this.index--; } if (this.index < 0) { this.index = 1; this._direction = Tone.CtrlPattern.Type.Up; } else if (this.index >= this.values.length) { this.index = this.values.length - 2; this._direction = Tone.CtrlPattern.Type.Down; } } else if (type === Tone.CtrlPattern.Type.Random) { this.index = Math.floor(Math.random() * this.values.length); } else if (type === Tone.CtrlPattern.Type.RandomWalk) { if (Math.random() < 0.5) { this.index--; this.index = Math.max(this.index, 0); } else { this.index++; this.index = Math.min(this.index, this.values.length - 1); } } else if (type === Tone.CtrlPattern.Type.RandomOnce) { this.index++; if (this.index >= this.values.length) { this.index = 0; //reshuffle the values for next time this._shuffleValues(); } } else if (type === Tone.CtrlPattern.Type.AlternateUp) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index += 2; this._direction = Tone.CtrlPattern.Type.Down; } else { this.index -= 1; this._direction = Tone.CtrlPattern.Type.Up; } if (this.index >= this.values.length) { this.index = 0; this._direction = Tone.CtrlPattern.Type.Up; } } else if (type === Tone.CtrlPattern.Type.AlternateDown) { if (this._direction === Tone.CtrlPattern.Type.Up) { this.index += 1; this._direction = Tone.CtrlPattern.Type.Down; } else { this.index -= 2; this._direction = Tone.CtrlPattern.Type.Up; } if (this.index < 0) { this.index = this.values.length - 1; this._direction = Tone.CtrlPattern.Type.Down; } } return this.value; }; /** * Shuffles the values and places the results into the _shuffled * @private */ Tone.CtrlPattern.prototype._shuffleValues = function () { var copy = []; this._shuffled = []; for (var i = 0; i < this.values.length; i++) { copy[i] = i; } while (copy.length > 0) { var randVal = copy.splice(Math.floor(copy.length * Math.random()), 1); this._shuffled.push(randVal[0]); } }; /** * Clean up * @returns {Tone.CtrlPattern} this */ Tone.CtrlPattern.prototype.dispose = function () { this._shuffled = null; this.values = null; }; return Tone.CtrlPattern; }); Module(function (Tone) { /** * @class Choose a random value. * @extends {Tone} * @example * var randomWalk = new Tone.CtrlRandom({ * "min" : 0, * "max" : 10, * "integer" : true * }); * randomWalk.eval(); * * @param {Number|Time=} min The minimum return value. * @param {Number|Time=} max The maximum return value. */ Tone.CtrlRandom = function () { var options = this.optionsObject(arguments, [ 'min', 'max' ], Tone.CtrlRandom.defaults); /** * The minimum return value * @type {Number|Time} */ this.min = options.min; /** * The maximum return value * @type {Number|Time} */ this.max = options.max; /** * If the return value should be an integer * @type {Boolean} */ this.integer = options.integer; }; Tone.extend(Tone.CtrlRandom); /** * The defaults * @const * @type {Object} */ Tone.CtrlRandom.defaults = { 'min': 0, 'max': 1, 'integer': false }; /** * Return a random value between min and max. * @readOnly * @memberOf Tone.CtrlRandom# * @type {*} * @name value */ Object.defineProperty(Tone.CtrlRandom.prototype, 'value', { get: function () { var min = this.toSeconds(this.min); var max = this.toSeconds(this.max); var rand = Math.random(); var val = rand * min + (1 - rand) * max; if (this.integer) { val = Math.floor(val); } return val; } }); return Tone.CtrlRandom; }); Module(function (Tone) { /** * @class Buffer loading and storage. Tone.Buffer is used internally by all * classes that make requests for audio files such as Tone.Player, * Tone.Sampler and Tone.Convolver. * <br><br> * Aside from load callbacks from individual buffers, Tone.Buffer * provides static methods which keep track of the loading progress * of all of the buffers. These methods are Tone.Buffer.onload, Tone.Buffer.onprogress, * and Tone.Buffer.onerror. * * @constructor * @extends {Tone} * @param {AudioBuffer|string} url The url to load, or the audio buffer to set. * @param {function=} onload A callback which is invoked after the buffer is loaded. * It's recommended to use Tone.Buffer.onload instead * since it will give you a callback when ALL buffers are loaded. * @example * var buffer = new Tone.Buffer("path/to/sound.mp3", function(){ * //the buffer is now available. * var buff = buffer.get(); * }); */ Tone.Buffer = function () { var options = this.optionsObject(arguments, [ 'url', 'onload' ], Tone.Buffer.defaults); /** * stores the loaded AudioBuffer * @type {AudioBuffer} * @private */ this._buffer = null; /** * indicates if the buffer should be reversed or not * @type {boolean} * @private */ this._reversed = options.reverse; /** * The url of the buffer. <code>undefined</code> if it was * constructed with a buffer * @type {string} * @readOnly */ this.url = undefined; /** * Indicates if the buffer is loaded or not. * @type {boolean} * @readOnly */ this.loaded = false; /** * The callback to invoke when everything is loaded. * @type {function} */ this.onload = options.onload.bind(this, this); if (options.url instanceof AudioBuffer || options.url instanceof Tone.Buffer) { this.set(options.url); this.onload(this); } else if (this.isString(options.url)) { this.url = options.url; Tone.Buffer._addToQueue(options.url, this); } }; Tone.extend(Tone.Buffer); /** * the default parameters * @type {Object} */ Tone.Buffer.defaults = { 'url': undefined, 'onload': Tone.noOp, 'reverse': false }; /** * Pass in an AudioBuffer or Tone.Buffer to set the value * of this buffer. * @param {AudioBuffer|Tone.Buffer} buffer the buffer * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.set = function (buffer) { if (buffer instanceof Tone.Buffer) { this._buffer = buffer.get(); } else { this._buffer = buffer; } this.loaded = true; return this; }; /** * @return {AudioBuffer} The audio buffer stored in the object. */ Tone.Buffer.prototype.get = function () { return this._buffer; }; /** * Load url into the buffer. * @param {String} url The url to load * @param {Function=} callback The callback to invoke on load. * don't need to set if `onload` is * already set. * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.load = function (url, callback) { this.url = url; this.onload = this.defaultArg(callback, this.onload); Tone.Buffer._addToQueue(url, this); return this; }; /** * dispose and disconnect * @returns {Tone.Buffer} this */ Tone.Buffer.prototype.dispose = function () { Tone.prototype.dispose.call(this); Tone.Buffer._removeFromQueue(this); this._buffer = null; this.onload = Tone.Buffer.defaults.onload; return this; }; /** * The duration of the buffer. * @memberOf Tone.Buffer# * @type {number} * @name duration * @readOnly */ Object.defineProperty(Tone.Buffer.prototype, 'duration', { get: function () { if (this._buffer) { return this._buffer.duration; } else { return 0; } } }); /** * Reverse the buffer. * @private * @return {Tone.Buffer} this */ Tone.Buffer.prototype._reverse = function () { if (this.loaded) { for (var i = 0; i < this._buffer.numberOfChannels; i++) { Array.prototype.reverse.call(this._buffer.getChannelData(i)); } } return this; }; /** * Reverse the buffer. * @memberOf Tone.Buffer# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Buffer.prototype, 'reverse', { get: function () { return this._reversed; }, set: function (rev) { if (this._reversed !== rev) { this._reversed = rev; this._reverse(); } } }); /////////////////////////////////////////////////////////////////////////// // STATIC METHODS /////////////////////////////////////////////////////////////////////////// //statically inherits Emitter methods Tone.Emitter.mixin(Tone.Buffer); /** * the static queue for all of the xhr requests * @type {Array} * @private */ Tone.Buffer._queue = []; /** * the array of current downloads * @type {Array} * @private */ Tone.Buffer._currentDownloads = []; /** * the total number of downloads * @type {number} * @private */ Tone.Buffer._totalDownloads = 0; /** * the maximum number of simultaneous downloads * @static * @type {number} */ Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS = 6; /** * Adds a file to be loaded to the loading queue * @param {string} url the url to load * @param {function} callback the callback to invoke once it's loaded * @private */ Tone.Buffer._addToQueue = function (url, buffer) { Tone.Buffer._queue.push({ url: url, Buffer: buffer, progress: 0, xhr: null }); this._totalDownloads++; Tone.Buffer._next(); }; /** * Remove an object from the queue's (if it's still there) * Abort the XHR if it's in progress * @param {Tone.Buffer} buffer the buffer to remove * @private */ Tone.Buffer._removeFromQueue = function (buffer) { var i; for (i = 0; i < Tone.Buffer._queue.length; i++) { var q = Tone.Buffer._queue[i]; if (q.Buffer === buffer) { Tone.Buffer._queue.splice(i, 1); } } for (i = 0; i < Tone.Buffer._currentDownloads.length; i++) { var dl = Tone.Buffer._currentDownloads[i]; if (dl.Buffer === buffer) { Tone.Buffer._currentDownloads.splice(i, 1); dl.xhr.abort(); dl.xhr.onprogress = null; dl.xhr.onload = null; dl.xhr.onerror = null; } } }; /** * load the next buffer in the queue * @private */ Tone.Buffer._next = function () { if (Tone.Buffer._queue.length > 0) { if (Tone.Buffer._currentDownloads.length < Tone.Buffer.MAX_SIMULTANEOUS_DOWNLOADS) { var next = Tone.Buffer._queue.shift(); Tone.Buffer._currentDownloads.push(next); next.xhr = Tone.Buffer.load(next.url, function (buffer) { //remove this one from the queue var index = Tone.Buffer._currentDownloads.indexOf(next); Tone.Buffer._currentDownloads.splice(index, 1); next.Buffer.set(buffer); if (next.Buffer._reversed) { next.Buffer._reverse(); } next.Buffer.onload(next.Buffer); Tone.Buffer._onprogress(); Tone.Buffer._next(); }); next.xhr.onprogress = function (event) { next.progress = event.loaded / event.total; Tone.Buffer._onprogress(); }; next.xhr.onerror = function (e) { Tone.Buffer.trigger('error', e); }; } } else if (Tone.Buffer._currentDownloads.length === 0) { Tone.Buffer.trigger('load'); //reset the downloads Tone.Buffer._totalDownloads = 0; } }; /** * internal progress event handler * @private */ Tone.Buffer._onprogress = function () { var curretDownloadsProgress = 0; var currentDLLen = Tone.Buffer._currentDownloads.length; var inprogress = 0; if (currentDLLen > 0) { for (var i = 0; i < currentDLLen; i++) { var dl = Tone.Buffer._currentDownloads[i]; curretDownloadsProgress += dl.progress; } inprogress = curretDownloadsProgress; } var currentDownloadProgress = currentDLLen - inprogress; var completed = Tone.Buffer._totalDownloads - Tone.Buffer._queue.length - currentDownloadProgress; Tone.Buffer.trigger('progress', completed / Tone.Buffer._totalDownloads); }; /** * Makes an xhr reqest for the selected url then decodes * the file as an audio buffer. Invokes * the callback once the audio buffer loads. * @param {string} url The url of the buffer to load. * filetype support depends on the * browser. * @param {function} callback The function to invoke when the url is loaded. * @returns {XMLHttpRequest} returns the XHR */ Tone.Buffer.load = function (url, callback) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // decode asynchronously request.onload = function () { Tone.context.decodeAudioData(request.response, function (buff) { if (!buff) { throw new Error('could not decode audio data:' + url); } callback(buff); }); }; //send the request request.send(); return request; }; /** * @deprecated us on([event]) instead */ Object.defineProperty(Tone.Buffer, 'onload', { set: function (cb) { console.warn('Tone.Buffer.onload is deprecated, use Tone.Buffer.on(\'load\', callback)'); Tone.Buffer.on('load', cb); } }); Object.defineProperty(Tone.Buffer, 'onprogress', { set: function (cb) { console.warn('Tone.Buffer.onprogress is deprecated, use Tone.Buffer.on(\'progress\', callback)'); Tone.Buffer.on('progress', cb); } }); Object.defineProperty(Tone.Buffer, 'onerror', { set: function (cb) { console.warn('Tone.Buffer.onerror is deprecated, use Tone.Buffer.on(\'error\', callback)'); Tone.Buffer.on('error', cb); } }); return Tone.Buffer; }); Module(function (Tone) { /** * buses are another way of routing audio * * augments Tone.prototype to include send and recieve */ /** * All of the routes * * @type {Object} * @static * @private */ var Buses = {}; /** * Send this signal to the channel name. * @param {string} channelName A named channel to send the signal to. * @param {Decibels} amount The amount of the source to send to the bus. * @return {GainNode} The gain node which connects this node to the desired channel. * Can be used to adjust the levels of the send. * @example * source.send("reverb", -12); */ Tone.prototype.send = function (channelName, amount) { if (!Buses.hasOwnProperty(channelName)) { Buses[channelName] = this.context.createGain(); } var sendKnob = this.context.createGain(); sendKnob.gain.value = this.dbToGain(this.defaultArg(amount, 1)); this.output.chain(sendKnob, Buses[channelName]); return sendKnob; }; /** * Recieve the input from the desired channelName to the input * * @param {string} channelName A named channel to send the signal to. * @param {AudioNode} [input] If no input is selected, the * input of the current node is * chosen. * @returns {Tone} this * @example * reverbEffect.receive("reverb"); */ Tone.prototype.receive = function (channelName, input) { if (!Buses.hasOwnProperty(channelName)) { Buses[channelName] = this.context.createGain(); } if (this.isUndef(input)) { input = this.input; } Buses[channelName].connect(input); return this; }; return Tone; }); Module(function (Tone) { /** * @class Wrapper around Web Audio's native [DelayNode](http://webaudio.github.io/web-audio-api/#the-delaynode-interface). * @extends {Tone} * @param {Time=} delayTime The delay applied to the incoming signal. * @param {Time=} maxDelay The maximum delay time. */ Tone.Delay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'maxDelay' ], Tone.Delay.defaults); /** * The native delay node * @type {DelayNode} * @private */ this._delayNode = this.input = this.output = this.context.createDelay(this.toSeconds(options.maxDelay)); /** * The amount of time the incoming signal is * delayed. * @type {Tone.Param} * @signal */ this.delayTime = new Tone.Param({ 'param': this._delayNode.delayTime, 'units': Tone.Type.Time, 'value': options.delayTime }); this._readOnly('delayTime'); }; Tone.extend(Tone.Delay); /** * The defaults * @const * @type {Object} */ Tone.Delay.defaults = { 'maxDelay': 1, 'delayTime': 0 }; /** * Clean up. * @return {Tone.Delay} this */ Tone.Delay.prototype.dispose = function () { Tone.Param.prototype.dispose.call(this); this._delayNode.disconnect(); this._delayNode = null; this._writable('delayTime'); this.delayTime = null; return this; }; return Tone.Delay; }); Module(function (Tone) { /** * @class A single master output which is connected to the * AudioDestinationNode (aka your speakers). * It provides useful conveniences such as the ability * to set the volume and mute the entire application. * It also gives you the ability to apply master effects to your application. * <br><br> * Like Tone.Transport, A single Tone.Master is created * on initialization and you do not need to explicitly construct one. * * @constructor * @extends {Tone} * @singleton * @example * //the audio will go from the oscillator to the speakers * oscillator.connect(Tone.Master); * //a convenience for connecting to the master output is also provided: * oscillator.toMaster(); * //the above two examples are equivalent. */ Tone.Master = function () { Tone.call(this); /** * the unmuted volume * @type {number} * @private */ this._unmutedVolume = 1; /** * if the master is muted * @type {boolean} * @private */ this._muted = false; /** * The private volume node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(); /** * The volume of the master output. * @type {Decibels} * @signal */ this.volume = this._volume.volume; this._readOnly('volume'); //connections this.input.chain(this.output, this.context.destination); }; Tone.extend(Tone.Master); /** * @type {Object} * @const */ Tone.Master.defaults = { 'volume': 0, 'mute': false }; /** * Mute the output. * @memberOf Tone.Master# * @type {boolean} * @name mute * @example * //mute the output * Tone.Master.mute = true; */ Object.defineProperty(Tone.Master.prototype, 'mute', { get: function () { return this._muted; }, set: function (mute) { if (!this._muted && mute) { this._unmutedVolume = this.volume.value; //maybe it should ramp here? this.volume.value = -Infinity; } else if (this._muted && !mute) { this.volume.value = this._unmutedVolume; } this._muted = mute; } }); /** * Add a master effects chain. NOTE: this will disconnect any nodes which were previously * chained in the master effects chain. * @param {AudioNode|Tone...} args All arguments will be connected in a row * and the Master will be routed through it. * @return {Tone.Master} this * @example * //some overall compression to keep the levels in check * var masterCompressor = new Tone.Compressor({ * "threshold" : -6, * "ratio" : 3, * "attack" : 0.5, * "release" : 0.1 * }); * //give a little boost to the lows * var lowBump = new Tone.Filter(200, "lowshelf"); * //route everything through the filter * //and compressor before going to the speakers * Tone.Master.chain(lowBump, masterCompressor); */ Tone.Master.prototype.chain = function () { this.input.disconnect(); this.input.chain.apply(this.input, arguments); arguments[arguments.length - 1].connect(this.output); }; /** * Clean up * @return {Tone.Master} this */ Tone.Master.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('volume'); this._volume.dispose(); this._volume = null; this.volume = null; }; /////////////////////////////////////////////////////////////////////////// // AUGMENT TONE's PROTOTYPE /////////////////////////////////////////////////////////////////////////// /** * Connect 'this' to the master output. Shorthand for this.connect(Tone.Master) * @returns {Tone} this * @example * //connect an oscillator to the master output * var osc = new Tone.Oscillator().toMaster(); */ Tone.prototype.toMaster = function () { this.connect(Tone.Master); return this; }; /** * Also augment AudioNode's prototype to include toMaster * as a convenience * @returns {AudioNode} this */ AudioNode.prototype.toMaster = function () { this.connect(Tone.Master); return this; }; var MasterConstructor = Tone.Master; /** * initialize the module and listen for new audio contexts */ Tone._initAudioContext(function () { //a single master output if (!Tone.prototype.isUndef(Tone.Master)) { Tone.Master = new MasterConstructor(); } else { MasterConstructor.prototype.dispose.call(Tone.Master); MasterConstructor.call(Tone.Master); } }); return Tone.Master; }); Module(function (Tone) { /** * @class A timed note. Creating a note will register a callback * which will be invoked on the channel at the time with * whatever value was specified. * * @constructor * @param {number|string} channel the channel name of the note * @param {Time} time the time when the note will occur * @param {string|number|Object|Array} value the value of the note */ Tone.Note = function (channel, time, value) { /** * the value of the note. This value is returned * when the channel callback is invoked. * * @type {string|number|Object} */ this.value = value; /** * the channel name or number * * @type {string|number} * @private */ this._channel = channel; /** * an internal reference to the id of the timeline * callback which is set. * * @type {number} * @private */ this._timelineID = Tone.Transport.setTimeline(this._trigger.bind(this), time); }; /** * invoked by the timeline * @private * @param {number} time the time at which the note should play */ Tone.Note.prototype._trigger = function (time) { //invoke the callback channelCallbacks(this._channel, time, this.value); }; /** * clean up * @returns {Tone.Note} this */ Tone.Note.prototype.dispose = function () { Tone.Transport.clearTimeline(this._timelineID); this.value = null; return this; }; /** * @private * @static * @type {Object} */ var NoteChannels = {}; /** * invoke all of the callbacks on a specific channel * @private */ function channelCallbacks(channel, time, value) { if (NoteChannels.hasOwnProperty(channel)) { var callbacks = NoteChannels[channel]; for (var i = 0, len = callbacks.length; i < len; i++) { var callback = callbacks[i]; if (Array.isArray(value)) { callback.apply(window, [time].concat(value)); } else { callback(time, value); } } } } /** * listen to a specific channel, get all of the note callbacks * @static * @param {string|number} channel the channel to route note events from * @param {function(*)} callback callback to be invoked when a note will occur * on the specified channel */ Tone.Note.route = function (channel, callback) { if (NoteChannels.hasOwnProperty(channel)) { NoteChannels[channel].push(callback); } else { NoteChannels[channel] = [callback]; } }; /** * Remove a previously routed callback from a channel. * @static * @param {string|number} channel The channel to unroute note events from * @param {function(*)} callback Callback which was registered to the channel. */ Tone.Note.unroute = function (channel, callback) { if (NoteChannels.hasOwnProperty(channel)) { var channelCallback = NoteChannels[channel]; var index = channelCallback.indexOf(callback); if (index !== -1) { NoteChannels[channel].splice(index, 1); } } }; /** * Parses a score and registers all of the notes along the timeline. * <br><br> * Scores are a JSON object with instruments at the top level * and an array of time and values. The value of a note can be 0 or more * parameters. * <br><br> * The only requirement for the score format is that the time is the first (or only) * value in the array. All other values are optional and will be passed into the callback * function registered using `Note.route(channelName, callback)`. * <br><br> * To convert MIDI files to score notation, take a look at utils/MidiToScore.js * * @example * //an example JSON score which sets up events on channels * var score = { * "synth" : [["0", "C3"], ["0:1", "D3"], ["0:2", "E3"], ... ], * "bass" : [["0", "C2"], ["1:0", "A2"], ["2:0", "C2"], ["3:0", "A2"], ... ], * "kick" : ["0", "0:2", "1:0", "1:2", "2:0", ... ], * //... * }; * //parse the score into Notes * Tone.Note.parseScore(score); * //route all notes on the "synth" channel * Tone.Note.route("synth", function(time, note){ * //trigger synth * }); * @static * @param {Object} score * @return {Array} an array of all of the notes that were created */ Tone.Note.parseScore = function (score) { var notes = []; for (var inst in score) { var part = score[inst]; if (inst === 'tempo') { Tone.Transport.bpm.value = part; } else if (inst === 'timeSignature') { Tone.Transport.timeSignature = part[0] / (part[1] / 4); } else if (Array.isArray(part)) { for (var i = 0; i < part.length; i++) { var noteDescription = part[i]; var note; if (Array.isArray(noteDescription)) { var time = noteDescription[0]; var value = noteDescription.slice(1); note = new Tone.Note(inst, time, value); } else if (typeof noteDescription === 'object') { note = new Tone.Note(inst, noteDescription.time, noteDescription); } else { note = new Tone.Note(inst, noteDescription); } notes.push(note); } } else { throw new TypeError('score parts must be Arrays'); } } return notes; }; return Tone.Note; }); Module(function (Tone) { /** * @class Tone.Effect is the base class for effects. Connect the effect between * the effectSend and effectReturn GainNodes, then control the amount of * effect which goes to the output using the wet control. * * @constructor * @extends {Tone} * @param {NormalRange|Object} [wet] The starting wet value. */ Tone.Effect = function () { Tone.call(this); //get all of the defaults var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); /** * the drywet knob to control the amount of effect * @type {Tone.CrossFade} * @private */ this._dryWet = new Tone.CrossFade(options.wet); /** * The wet control is how much of the effected * will pass through to the output. 1 = 100% effected * signal, 0 = 100% dry signal. * @type {NormalRange} * @signal */ this.wet = this._dryWet.fade; /** * connect the effectSend to the input of hte effect * @type {GainNode} * @private */ this.effectSend = this.context.createGain(); /** * connect the output of the effect to the effectReturn * @type {GainNode} * @private */ this.effectReturn = this.context.createGain(); //connections this.input.connect(this._dryWet.a); this.input.connect(this.effectSend); this.effectReturn.connect(this._dryWet.b); this._dryWet.connect(this.output); this._readOnly(['wet']); }; Tone.extend(Tone.Effect); /** * @static * @type {Object} */ Tone.Effect.defaults = { 'wet': 1 }; /** * chains the effect in between the effectSend and effectReturn * @param {Tone} effect * @private * @returns {Tone.Effect} this */ Tone.Effect.prototype.connectEffect = function (effect) { this.effectSend.chain(effect, this.effectReturn); return this; }; /** * Clean up. * @returns {Tone.Effect} this */ Tone.Effect.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._dryWet.dispose(); this._dryWet = null; this.effectSend.disconnect(); this.effectSend = null; this.effectReturn.disconnect(); this.effectReturn = null; this._writable(['wet']); this.wet = null; return this; }; return Tone.Effect; }); Module(function (Tone) { /** * @class Tone.AutoFilter is a Tone.Filter with a Tone.LFO connected to the filter cutoff frequency. * Setting the LFO rate and depth allows for control over the filter modulation rate * and depth. * * @constructor * @extends {Tone.Effect} * @param {Time|Object} [frequency] The rate of the LFO. * @param {Frequency=} baseFrequency The lower value of the LFOs oscillation * @param {Frequency=} octaves The number of octaves above the baseFrequency * @example * //create an autofilter and start it's LFO * var autoFilter = new Tone.AutoFilter("4n").toMaster().start(); * //route an oscillator through the filter and start it * var oscillator = new Tone.Oscillator().connect(autoFilter).start(); */ Tone.AutoFilter = function () { var options = this.optionsObject(arguments, [ 'frequency', 'baseFrequency', 'octaves' ], Tone.AutoFilter.defaults); Tone.Effect.call(this, options); /** * the lfo which drives the filter cutoff * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'frequency': options.frequency, 'amplitude': options.depth }); /** * The range of the filter modulating between the min and max frequency. * 0 = no modulation. 1 = full modulation. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; /** * How fast the filter modulates between min and max. * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; /** * The filter node * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The octaves placeholder * @type {Positive} * @private */ this._octaves = 0; //connections this.connectEffect(this.filter); this._lfo.connect(this.filter.frequency); this.type = options.type; this._readOnly([ 'frequency', 'depth' ]); this.octaves = options.octaves; this.baseFrequency = options.baseFrequency; }; //extend Effect Tone.extend(Tone.AutoFilter, Tone.Effect); /** * defaults * @static * @type {Object} */ Tone.AutoFilter.defaults = { 'frequency': 1, 'type': 'sine', 'depth': 1, 'baseFrequency': 200, 'octaves': 2.6, 'filter': { 'type': 'lowpass', 'rolloff': -12, 'Q': 1 } }; /** * Start the effect. * @param {Time} [time=now] When the LFO will start. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.start = function (time) { this._lfo.start(time); return this; }; /** * Stop the effect. * @param {Time} [time=now] When the LFO will stop. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.stop = function (time) { this._lfo.stop(time); return this; }; /** * Sync the filter to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.sync = function (delay) { this._lfo.sync(delay); return this; }; /** * Unsync the filter from the transport. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.unsync = function () { this._lfo.unsync(); return this; }; /** * Type of oscillator attached to the AutoFilter. * Possible values: "sine", "square", "triangle", "sawtooth". * @memberOf Tone.AutoFilter# * @type {string} * @name type */ Object.defineProperty(Tone.AutoFilter.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * The minimum value of the filter's cutoff frequency. * @memberOf Tone.AutoFilter# * @type {Frequency} * @name min */ Object.defineProperty(Tone.AutoFilter.prototype, 'baseFrequency', { get: function () { return this._lfo.min; }, set: function (freq) { this._lfo.min = this.toFrequency(freq); } }); /** * The maximum value of the filter's cutoff frequency. * @memberOf Tone.AutoFilter# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.AutoFilter.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (oct) { this._octaves = oct; this._lfo.max = this.baseFrequency * Math.pow(2, oct); } }); /** * Clean up. * @returns {Tone.AutoFilter} this */ Tone.AutoFilter.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._lfo.dispose(); this._lfo = null; this.filter.dispose(); this.filter = null; this._writable([ 'frequency', 'depth' ]); this.frequency = null; this.depth = null; return this; }; return Tone.AutoFilter; }); Module(function (Tone) { /** * @class Tone.AutoPanner is a Tone.Panner with an LFO connected to the pan amount. * More on using autopanners [here](https://www.ableton.com/en/blog/autopan-chopper-effect-and-more-liveschool/). * * @constructor * @extends {Tone.Effect} * @param {Frequency|Object} [frequency] Rate of left-right oscillation. * @example * //create an autopanner and start it's LFO * var autoPanner = new Tone.AutoPanner("4n").toMaster().start(); * //route an oscillator through the panner and start it * var oscillator = new Tone.Oscillator().connect(autoPanner).start(); */ Tone.AutoPanner = function () { var options = this.optionsObject(arguments, ['frequency'], Tone.AutoPanner.defaults); Tone.Effect.call(this, options); /** * the lfo which drives the panning * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'frequency': options.frequency, 'amplitude': options.depth, 'min': 0, 'max': 1 }); /** * The amount of panning between left and right. * 0 = always center. 1 = full range between left and right. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; /** * the panner node which does the panning * @type {Tone.Panner} * @private */ this._panner = new Tone.Panner(); /** * How fast the panner modulates between left and right. * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; //connections this.connectEffect(this._panner); this._lfo.connect(this._panner.pan); this.type = options.type; this._readOnly([ 'depth', 'frequency' ]); }; //extend Effect Tone.extend(Tone.AutoPanner, Tone.Effect); /** * defaults * @static * @type {Object} */ Tone.AutoPanner.defaults = { 'frequency': 1, 'type': 'sine', 'depth': 1 }; /** * Start the effect. * @param {Time} [time=now] When the LFO will start. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.start = function (time) { this._lfo.start(time); return this; }; /** * Stop the effect. * @param {Time} [time=now] When the LFO will stop. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.stop = function (time) { this._lfo.stop(time); return this; }; /** * Sync the panner to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.sync = function (delay) { this._lfo.sync(delay); return this; }; /** * Unsync the panner from the transport * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.unsync = function () { this._lfo.unsync(); return this; }; /** * Type of oscillator attached to the AutoFilter. * Possible values: "sine", "square", "triangle", "sawtooth". * @memberOf Tone.AutoFilter# * @type {string} * @name type */ Object.defineProperty(Tone.AutoPanner.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * clean up * @returns {Tone.AutoPanner} this */ Tone.AutoPanner.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._lfo.dispose(); this._lfo = null; this._panner.dispose(); this._panner = null; this._writable([ 'depth', 'frequency' ]); this.frequency = null; this.depth = null; return this; }; return Tone.AutoPanner; }); Module(function (Tone) { /** * @class Tone.AutoWah connects a Tone.Follower to a bandpass filter (Tone.Filter). * The frequency of the filter is adjusted proportionally to the * incoming signal's amplitude. Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna). * * @constructor * @extends {Tone.Effect} * @param {Frequency|Object} [baseFrequency] The frequency the filter is set * to at the low point of the wah * @param {Positive} [octaves] The number of octaves above the baseFrequency * the filter will sweep to when fully open * @param {Decibels} [sensitivity] The decibel threshold sensitivity for * the incoming signal. Normal range of -40 to 0. * @example * var autoWah = new Tone.AutoWah(50, 6, -30).toMaster(); * //initialize the synth and connect to autowah * var synth = new SimpleSynth.connect(autoWah); * //Q value influences the effect of the wah - default is 2 * autoWah.Q.value = 6; * //more audible on higher notes * synth.triggerAttackRelease("C4", "8n") */ Tone.AutoWah = function () { var options = this.optionsObject(arguments, [ 'baseFrequency', 'octaves', 'sensitivity' ], Tone.AutoWah.defaults); Tone.Effect.call(this, options); /** * The envelope follower. Set the attack/release * timing to adjust how the envelope is followed. * @type {Tone.Follower} * @private */ this.follower = new Tone.Follower(options.follower); /** * scales the follower value to the frequency domain * @type {Tone} * @private */ this._sweepRange = new Tone.ScaleExp(0, 1, 0.5); /** * @type {number} * @private */ this._baseFrequency = options.baseFrequency; /** * @type {number} * @private */ this._octaves = options.octaves; /** * the input gain to adjust the sensitivity * @type {GainNode} * @private */ this._inputBoost = this.context.createGain(); /** * @type {BiquadFilterNode} * @private */ this._bandpass = new Tone.Filter({ 'rolloff': -48, 'frequency': 0, 'Q': options.Q }); /** * @type {Tone.Filter} * @private */ this._peaking = new Tone.Filter(0, 'peaking'); this._peaking.gain.value = options.gain; /** * The gain of the filter. * @type {Number} * @signal */ this.gain = this._peaking.gain; /** * The quality of the filter. * @type {Positive} * @signal */ this.Q = this._bandpass.Q; //the control signal path this.effectSend.chain(this._inputBoost, this.follower, this._sweepRange); this._sweepRange.connect(this._bandpass.frequency); this._sweepRange.connect(this._peaking.frequency); //the filtered path this.effectSend.chain(this._bandpass, this._peaking, this.effectReturn); //set the initial value this._setSweepRange(); this.sensitivity = options.sensitivity; this._readOnly([ 'gain', 'Q' ]); }; Tone.extend(Tone.AutoWah, Tone.Effect); /** * @static * @type {Object} */ Tone.AutoWah.defaults = { 'baseFrequency': 100, 'octaves': 6, 'sensitivity': 0, 'Q': 2, 'gain': 2, 'follower': { 'attack': 0.3, 'release': 0.5 } }; /** * The number of octaves that the filter will sweep above the * baseFrequency. * @memberOf Tone.AutoWah# * @type {Number} * @name octaves */ Object.defineProperty(Tone.AutoWah.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; this._setSweepRange(); } }); /** * The base frequency from which the sweep will start from. * @memberOf Tone.AutoWah# * @type {Frequency} * @name baseFrequency */ Object.defineProperty(Tone.AutoWah.prototype, 'baseFrequency', { get: function () { return this._baseFrequency; }, set: function (baseFreq) { this._baseFrequency = baseFreq; this._setSweepRange(); } }); /** * The sensitivity to control how responsive to the input signal the filter is. * @memberOf Tone.AutoWah# * @type {Decibels} * @name sensitivity */ Object.defineProperty(Tone.AutoWah.prototype, 'sensitivity', { get: function () { return this.gainToDb(1 / this._inputBoost.gain.value); }, set: function (sensitivy) { this._inputBoost.gain.value = 1 / this.dbToGain(sensitivy); } }); /** * sets the sweep range of the scaler * @private */ Tone.AutoWah.prototype._setSweepRange = function () { this._sweepRange.min = this._baseFrequency; this._sweepRange.max = Math.min(this._baseFrequency * Math.pow(2, this._octaves), this.context.sampleRate / 2); }; /** * Clean up. * @returns {Tone.AutoWah} this */ Tone.AutoWah.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this.follower.dispose(); this.follower = null; this._sweepRange.dispose(); this._sweepRange = null; this._bandpass.dispose(); this._bandpass = null; this._peaking.dispose(); this._peaking = null; this._inputBoost.disconnect(); this._inputBoost = null; this._writable([ 'gain', 'Q' ]); this.gain = null; this.Q = null; return this; }; return Tone.AutoWah; }); Module(function (Tone) { /** * @class Tone.Bitcrusher downsamples the incoming signal to a different bitdepth. * Lowering the bitdepth of the signal creates distortion. Read more about Bitcrushing * on [Wikipedia](https://en.wikipedia.org/wiki/Bitcrusher). * * @constructor * @extends {Tone.Effect} * @param {Number} bits The number of bits to downsample the signal. Nominal range * of 1 to 8. * @example * //initialize crusher and route a synth through it * var crusher = new Tone.BitCrusher(4).toMaster(); * var synth = new Tone.MonoSynth().connect(crusher); */ Tone.BitCrusher = function () { var options = this.optionsObject(arguments, ['bits'], Tone.BitCrusher.defaults); Tone.Effect.call(this, options); var invStepSize = 1 / Math.pow(2, options.bits - 1); /** * Subtract the input signal and the modulus of the input signal * @type {Tone.Subtract} * @private */ this._subtract = new Tone.Subtract(); /** * The mod function * @type {Tone.Modulo} * @private */ this._modulo = new Tone.Modulo(invStepSize); /** * keeps track of the bits * @type {number} * @private */ this._bits = options.bits; //connect it up this.effectSend.fan(this._subtract, this._modulo); this._modulo.connect(this._subtract, 0, 1); this._subtract.connect(this.effectReturn); }; Tone.extend(Tone.BitCrusher, Tone.Effect); /** * the default values * @static * @type {Object} */ Tone.BitCrusher.defaults = { 'bits': 4 }; /** * The bit depth of the effect. Nominal range of 1-8. * @memberOf Tone.BitCrusher# * @type {number} * @name bits */ Object.defineProperty(Tone.BitCrusher.prototype, 'bits', { get: function () { return this._bits; }, set: function (bits) { this._bits = bits; var invStepSize = 1 / Math.pow(2, bits - 1); this._modulo.value = invStepSize; } }); /** * Clean up. * @returns {Tone.BitCrusher} this */ Tone.BitCrusher.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._subtract.dispose(); this._subtract = null; this._modulo.dispose(); this._modulo = null; return this; }; return Tone.BitCrusher; }); Module(function (Tone) { /** * @class Tone.ChebyShev is a Chebyshev waveshaper, an effect which is good * for making different types of distortion sounds. * Note that odd orders sound very different from even ones, * and order = 1 is no change. * Read more at [music.columbia.edu](http://music.columbia.edu/cmc/musicandcomputers/chapter4/04_06.php). * * @extends {Tone.Effect} * @constructor * @param {Positive|Object} [order] The order of the chebyshev polynomial. Normal range between 1-100. * @example * //create a new cheby * var cheby = new Tone.Chebyshev(50); * //create a monosynth connected to our cheby * synth = new Tone.MonoSynth().connect(cheby); */ Tone.Chebyshev = function () { var options = this.optionsObject(arguments, ['order'], Tone.Chebyshev.defaults); Tone.Effect.call(this, options); /** * @type {WaveShaperNode} * @private */ this._shaper = new Tone.WaveShaper(4096); /** * holds onto the order of the filter * @type {number} * @private */ this._order = options.order; this.connectEffect(this._shaper); this.order = options.order; this.oversample = options.oversample; }; Tone.extend(Tone.Chebyshev, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Chebyshev.defaults = { 'order': 1, 'oversample': 'none' }; /** * get the coefficient for that degree * @param {number} x the x value * @param {number} degree * @param {Object} memo memoize the computed value. * this speeds up computation greatly. * @return {number} the coefficient * @private */ Tone.Chebyshev.prototype._getCoefficient = function (x, degree, memo) { if (memo.hasOwnProperty(degree)) { return memo[degree]; } else if (degree === 0) { memo[degree] = 0; } else if (degree === 1) { memo[degree] = x; } else { memo[degree] = 2 * x * this._getCoefficient(x, degree - 1, memo) - this._getCoefficient(x, degree - 2, memo); } return memo[degree]; }; /** * The order of the Chebyshev polynomial which creates * the equation which is applied to the incoming * signal through a Tone.WaveShaper. The equations * are in the form:<br> * order 2: 2x^2 + 1<br> * order 3: 4x^3 + 3x <br> * @memberOf Tone.Chebyshev# * @type {Positive} * @name order */ Object.defineProperty(Tone.Chebyshev.prototype, 'order', { get: function () { return this._order; }, set: function (order) { this._order = order; var curve = new Array(4096); var len = curve.length; for (var i = 0; i < len; ++i) { var x = i * 2 / len - 1; if (x === 0) { //should output 0 when input is 0 curve[i] = 0; } else { curve[i] = this._getCoefficient(x, order, {}); } } this._shaper.curve = curve; } }); /** * The oversampling of the effect. Can either be "none", "2x" or "4x". * @memberOf Tone.Chebyshev# * @type {string} * @name oversample */ Object.defineProperty(Tone.Chebyshev.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { this._shaper.oversample = oversampling; } }); /** * Clean up. * @returns {Tone.Chebyshev} this */ Tone.Chebyshev.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; return this; }; return Tone.Chebyshev; }); Module(function (Tone) { /** * @class Base class for Stereo effects. Provides effectSendL/R and effectReturnL/R. * * @constructor * @extends {Tone.Effect} */ Tone.StereoEffect = function () { Tone.call(this); //get the defaults var options = this.optionsObject(arguments, ['wet'], Tone.Effect.defaults); /** * the drywet knob to control the amount of effect * @type {Tone.CrossFade} * @private */ this._dryWet = new Tone.CrossFade(options.wet); /** * The wet control, i.e. how much of the effected * will pass through to the output. * @type {NormalRange} * @signal */ this.wet = this._dryWet.fade; /** * then split it * @type {Tone.Split} * @private */ this._split = new Tone.Split(); /** * the effects send LEFT * @type {GainNode} * @private */ this.effectSendL = this._split.left; /** * the effects send RIGHT * @type {GainNode} * @private */ this.effectSendR = this._split.right; /** * the stereo effect merger * @type {Tone.Merge} * @private */ this._merge = new Tone.Merge(); /** * the effect return LEFT * @type {GainNode} * @private */ this.effectReturnL = this._merge.left; /** * the effect return RIGHT * @type {GainNode} * @private */ this.effectReturnR = this._merge.right; //connections this.input.connect(this._split); //dry wet connections this.input.connect(this._dryWet, 0, 0); this._merge.connect(this._dryWet, 0, 1); this._dryWet.connect(this.output); this._readOnly(['wet']); }; Tone.extend(Tone.StereoEffect, Tone.Effect); /** * Clean up. * @returns {Tone.StereoEffect} this */ Tone.StereoEffect.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._dryWet.dispose(); this._dryWet = null; this._split.dispose(); this._split = null; this._merge.dispose(); this._merge = null; this.effectSendL = null; this.effectSendR = null; this.effectReturnL = null; this.effectReturnR = null; this._writable(['wet']); this.wet = null; return this; }; return Tone.StereoEffect; }); Module(function (Tone) { /** * @class Tone.FeedbackEffect provides a loop between an * audio source and its own output. This is a base-class * for feedback effects. * * @constructor * @extends {Tone.Effect} * @param {NormalRange|Object} [feedback] The initial feedback value. */ Tone.FeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback']); options = this.defaultArg(options, Tone.FeedbackEffect.defaults); Tone.Effect.call(this, options); /** * The amount of signal which is fed back into the effect input. * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the gain which controls the feedback * @type {GainNode} * @private */ this._feedbackGain = this.context.createGain(); //the feedback loop this.effectReturn.chain(this._feedbackGain, this.effectSend); this.feedback.connect(this._feedbackGain.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.FeedbackEffect, Tone.Effect); /** * @static * @type {Object} */ Tone.FeedbackEffect.defaults = { 'feedback': 0.125 }; /** * Clean up. * @returns {Tone.FeedbackEffect} this */ Tone.FeedbackEffect.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackGain.disconnect(); this._feedbackGain = null; return this; }; return Tone.FeedbackEffect; }); Module(function (Tone) { /** * @class Just like a stereo feedback effect, but the feedback is routed from left to right * and right to left instead of on the same channel. * * @constructor * @extends {Tone.FeedbackEffect} */ Tone.StereoXFeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); Tone.StereoEffect.call(this, options); /** * The amount of feedback from the output * back into the input of the effect (routed * across left and right channels). * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the left side feeback * @type {GainNode} * @private */ this._feedbackLR = this.context.createGain(); /** * the right side feeback * @type {GainNode} * @private */ this._feedbackRL = this.context.createGain(); //connect it up this.effectReturnL.chain(this._feedbackLR, this.effectSendR); this.effectReturnR.chain(this._feedbackRL, this.effectSendL); this.feedback.fan(this._feedbackLR.gain, this._feedbackRL.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.StereoXFeedbackEffect, Tone.FeedbackEffect); /** * clean up * @returns {Tone.StereoXFeedbackEffect} this */ Tone.StereoXFeedbackEffect.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackLR.disconnect(); this._feedbackLR = null; this._feedbackRL.disconnect(); this._feedbackRL = null; return this; }; return Tone.StereoXFeedbackEffect; }); Module(function (Tone) { /** * @class Tone.Chorus is a stereo chorus effect with feedback composed of * a left and right delay with a Tone.LFO applied to the delayTime of each channel. * Inspiration from [Tuna.js](https://github.com/Dinahmoe/tuna/blob/master/tuna.js). * Read more on the chorus effect on [SoundOnSound](http://www.soundonsound.com/sos/jun04/articles/synthsecrets.htm). * * @constructor * @extends {Tone.StereoXFeedbackEffect} * @param {Frequency|Object} [frequency] The frequency of the LFO. * @param {Milliseconds} [delayTime] The delay of the chorus effect in ms. * @param {NormalRange} [depth] The depth of the chorus. * @example * var chorus = new Tone.Chorus(4, 2.5, 0.5); * var synth = new Tone.PolySynth(4, Tone.MonoSynth).connect(chorus); * synth.triggerAttackRelease(["C3","E3","G3"], "8n"); */ Tone.Chorus = function () { var options = this.optionsObject(arguments, [ 'frequency', 'delayTime', 'depth' ], Tone.Chorus.defaults); Tone.StereoXFeedbackEffect.call(this, options); /** * the depth of the chorus * @type {number} * @private */ this._depth = options.depth; /** * the delayTime * @type {number} * @private */ this._delayTime = options.delayTime / 1000; /** * the lfo which controls the delayTime * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO({ 'frequency': options.frequency, 'min': 0, 'max': 1 }); /** * another LFO for the right side with a 180 degree phase diff * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO({ 'frequency': options.frequency, 'min': 0, 'max': 1, 'phase': 180 }); /** * delay for left * @type {DelayNode} * @private */ this._delayNodeL = this.context.createDelay(); /** * delay for right * @type {DelayNode} * @private */ this._delayNodeR = this.context.createDelay(); /** * The frequency of the LFO which modulates the delayTime. * @type {Frequency} * @signal */ this.frequency = this._lfoL.frequency; //connections this.effectSendL.chain(this._delayNodeL, this.effectReturnL); this.effectSendR.chain(this._delayNodeR, this.effectReturnR); //and pass through to make the detune apparent this.effectSendL.connect(this.effectReturnL); this.effectSendR.connect(this.effectReturnR); //lfo setup this._lfoL.connect(this._delayNodeL.delayTime); this._lfoR.connect(this._delayNodeR.delayTime); //start the lfo this._lfoL.start(); this._lfoR.start(); //have one LFO frequency control the other this._lfoL.frequency.connect(this._lfoR.frequency); //set the initial values this.depth = this._depth; this.frequency.value = options.frequency; this.type = options.type; this._readOnly(['frequency']); this.spread = options.spread; }; Tone.extend(Tone.Chorus, Tone.StereoXFeedbackEffect); /** * @static * @type {Object} */ Tone.Chorus.defaults = { 'frequency': 1.5, 'delayTime': 3.5, 'depth': 0.7, 'feedback': 0.1, 'type': 'sine', 'spread': 180 }; /** * The depth of the effect. A depth of 1 makes the delayTime * modulate between 0 and 2*delayTime (centered around the delayTime). * @memberOf Tone.Chorus# * @type {NormalRange} * @name depth */ Object.defineProperty(Tone.Chorus.prototype, 'depth', { get: function () { return this._depth; }, set: function (depth) { this._depth = depth; var deviation = this._delayTime * depth; this._lfoL.min = Math.max(this._delayTime - deviation, 0); this._lfoL.max = this._delayTime + deviation; this._lfoR.min = Math.max(this._delayTime - deviation, 0); this._lfoR.max = this._delayTime + deviation; } }); /** * The delayTime in milliseconds of the chorus. A larger delayTime * will give a more pronounced effect. Nominal range a delayTime * is between 2 and 20ms. * @memberOf Tone.Chorus# * @type {Milliseconds} * @name delayTime */ Object.defineProperty(Tone.Chorus.prototype, 'delayTime', { get: function () { return this._delayTime * 1000; }, set: function (delayTime) { this._delayTime = delayTime / 1000; this.depth = this._depth; } }); /** * The oscillator type of the LFO. * @memberOf Tone.Chorus# * @type {string} * @name type */ Object.defineProperty(Tone.Chorus.prototype, 'type', { get: function () { return this._lfoL.type; }, set: function (type) { this._lfoL.type = type; this._lfoR.type = type; } }); /** * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. * When set to 180, LFO's will be panned hard left and right respectively. * @memberOf Tone.Chorus# * @type {Degrees} * @name spread */ Object.defineProperty(Tone.Chorus.prototype, 'spread', { get: function () { return this._lfoR.phase - this._lfoL.phase; //180 }, set: function (spread) { this._lfoL.phase = 90 - spread / 2; this._lfoR.phase = spread / 2 + 90; } }); /** * Clean up. * @returns {Tone.Chorus} this */ Tone.Chorus.prototype.dispose = function () { Tone.StereoXFeedbackEffect.prototype.dispose.call(this); this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; this._delayNodeL.disconnect(); this._delayNodeL = null; this._delayNodeR.disconnect(); this._delayNodeR = null; this._writable('frequency'); this.frequency = null; return this; }; return Tone.Chorus; }); Module(function (Tone) { /** * @class Tone.Convolver is a wrapper around the Native Web Audio * [ConvolverNode](http://webaudio.github.io/web-audio-api/#the-convolvernode-interface). * Convolution is useful for reverb and filter emulation. Read more about convolution reverb on * [Wikipedia](https://en.wikipedia.org/wiki/Convolution_reverb). * * @constructor * @extends {Tone.Effect} * @param {string|Tone.Buffer|Object} [url] The URL of the impulse response or the Tone.Buffer * contianing the impulse response. * @example * //initializing the convolver with an impulse response * var convolver = new Tone.Convolver("./path/to/ir.wav"); * convolver.toMaster(); * //after the buffer has loaded * Tone.Buffer.onload = function(){ * //testing out convolution with a noise burst * var burst = new Tone.NoiseSynth().connect(convolver); * burst.triggerAttackRelease("16n"); * }; */ Tone.Convolver = function () { var options = this.optionsObject(arguments, ['url'], Tone.Convolver.defaults); Tone.Effect.call(this, options); /** * convolver node * @type {ConvolverNode} * @private */ this._convolver = this.context.createConvolver(); /** * the convolution buffer * @type {Tone.Buffer} * @private */ this._buffer = new Tone.Buffer(options.url, function (buffer) { this.buffer = buffer; options.onload(); }.bind(this)); this.connectEffect(this._convolver); }; Tone.extend(Tone.Convolver, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Convolver.defaults = { 'url': '', 'onload': Tone.noOp }; /** * The convolver's buffer * @memberOf Tone.Convolver# * @type {AudioBuffer} * @name buffer */ Object.defineProperty(Tone.Convolver.prototype, 'buffer', { get: function () { return this._buffer.get(); }, set: function (buffer) { this._buffer.set(buffer); this._convolver.buffer = this._buffer.get(); } }); /** * Load an impulse response url as an audio buffer. * Decodes the audio asynchronously and invokes * the callback once the audio buffer loads. * @param {string} url The url of the buffer to load. * filetype support depends on the * browser. * @param {function=} callback * @returns {Tone.Convolver} this */ Tone.Convolver.prototype.load = function (url, callback) { this._buffer.load(url, function (buff) { this.buffer = buff; if (callback) { callback(); } }.bind(this)); return this; }; /** * Clean up. * @returns {Tone.Convolver} this */ Tone.Convolver.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._convolver.disconnect(); this._convolver = null; this._buffer.dispose(); this._buffer = null; return this; }; return Tone.Convolver; }); Module(function (Tone) { /** * @class Tone.Distortion is a simple distortion effect using Tone.WaveShaper. * Algorithm from [a stackoverflow answer](http://stackoverflow.com/a/22313408). * * @extends {Tone.Effect} * @constructor * @param {Number|Object} [distortion] The amount of distortion (nominal range of 0-1) * @example * var dist = new Tone.Distortion(0.8).toMaster(); * var fm = new Tone.SimpleFM().connect(dist); * //this sounds good on bass notes * fm.triggerAttackRelease("A1", "8n"); */ Tone.Distortion = function () { var options = this.optionsObject(arguments, ['distortion'], Tone.Distortion.defaults); Tone.Effect.call(this, options); /** * @type {Tone.WaveShaper} * @private */ this._shaper = new Tone.WaveShaper(4096); /** * holds the distortion amount * @type {number} * @private */ this._distortion = options.distortion; this.connectEffect(this._shaper); this.distortion = options.distortion; this.oversample = options.oversample; }; Tone.extend(Tone.Distortion, Tone.Effect); /** * @static * @const * @type {Object} */ Tone.Distortion.defaults = { 'distortion': 0.4, 'oversample': 'none' }; /** * The amount of distortion. * @memberOf Tone.Distortion# * @type {NormalRange} * @name distortion */ Object.defineProperty(Tone.Distortion.prototype, 'distortion', { get: function () { return this._distortion; }, set: function (amount) { this._distortion = amount; var k = amount * 100; var deg = Math.PI / 180; this._shaper.setMap(function (x) { if (Math.abs(x) < 0.001) { //should output 0 when input is 0 return 0; } else { return (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x)); } }); } }); /** * The oversampling of the effect. Can either be "none", "2x" or "4x". * @memberOf Tone.Distortion# * @type {string} * @name oversample */ Object.defineProperty(Tone.Distortion.prototype, 'oversample', { get: function () { return this._shaper.oversample; }, set: function (oversampling) { this._shaper.oversample = oversampling; } }); /** * Clean up. * @returns {Tone.Distortion} this */ Tone.Distortion.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._shaper.dispose(); this._shaper = null; return this; }; return Tone.Distortion; }); Module(function (Tone) { /** * @class Tone.FeedbackDelay is a DelayNode in which part of output * signal is fed back into the delay. * * @constructor * @extends {Tone.FeedbackEffect} * @param {Time|Object} [delayTime] The delay applied to the incoming signal. * @param {NormalRange=} feedback The amount of the effected signal which * is fed back through the delay. * @example * var feedbackDelay = new Tone.FeedbackDelay("8n", 0.5).toMaster(); * var tom = new Tone.DrumSynth({ * "octaves" : 4, * "pitchDecay" : 0.1 * }).connect(feedbackDelay); * tom.triggerAttackRelease("A2","32n"); */ Tone.FeedbackDelay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'feedback' ], Tone.FeedbackDelay.defaults); Tone.FeedbackEffect.call(this, options); /** * The delayTime of the DelayNode. * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); /** * the delay node * @type {DelayNode} * @private */ this._delayNode = this.context.createDelay(4); // connect it up this.connectEffect(this._delayNode); this.delayTime.connect(this._delayNode.delayTime); this._readOnly(['delayTime']); }; Tone.extend(Tone.FeedbackDelay, Tone.FeedbackEffect); /** * The default values. * @const * @static * @type {Object} */ Tone.FeedbackDelay.defaults = { 'delayTime': 0.25 }; /** * clean up * @returns {Tone.FeedbackDelay} this */ Tone.FeedbackDelay.prototype.dispose = function () { Tone.FeedbackEffect.prototype.dispose.call(this); this.delayTime.dispose(); this._delayNode.disconnect(); this._delayNode = null; this._writable(['delayTime']); this.delayTime = null; return this; }; return Tone.FeedbackDelay; }); Module(function (Tone) { /** * an array of comb filter delay values from Freeverb implementation * @static * @private * @type {Array} */ var combFilterTunings = [ 1557 / 44100, 1617 / 44100, 1491 / 44100, 1422 / 44100, 1277 / 44100, 1356 / 44100, 1188 / 44100, 1116 / 44100 ]; /** * an array of allpass filter frequency values from Freeverb implementation * @private * @static * @type {Array} */ var allpassFilterFrequencies = [ 225, 556, 441, 341 ]; /** * @class Tone.Freeverb is a reverb based on [Freeverb](https://ccrma.stanford.edu/~jos/pasp/Freeverb.html). * Read more on reverb on [SoundOnSound](http://www.soundonsound.com/sos/may00/articles/reverb.htm). * * @extends {Tone.Effect} * @constructor * @param {NormalRange|Object} [roomSize] Correlated to the decay time. * @param {Frequency} [dampening] The cutoff frequency of a lowpass filter as part * of the reverb. * @example * var freeverb = new Tone.Freeverb().toMaster(); * freeverb.dampening.value = 1000; * //routing synth through the reverb * var synth = new Tone.AMSynth().connect(freeverb); */ Tone.Freeverb = function () { var options = this.optionsObject(arguments, [ 'roomSize', 'dampening' ], Tone.Freeverb.defaults); Tone.StereoEffect.call(this, options); /** * The roomSize value between. A larger roomSize * will result in a longer decay. * @type {NormalRange} * @signal */ this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); /** * The amount of dampening of the reverberant signal. * @type {Frequency} * @signal */ this.dampening = new Tone.Signal(options.dampening, Tone.Type.Frequency); /** * the comb filters * @type {Array} * @private */ this._combFilters = []; /** * the allpass filters on the left * @type {Array} * @private */ this._allpassFiltersL = []; /** * the allpass filters on the right * @type {Array} * @private */ this._allpassFiltersR = []; //make the allpass filters on teh right for (var l = 0; l < allpassFilterFrequencies.length; l++) { var allpassL = this.context.createBiquadFilter(); allpassL.type = 'allpass'; allpassL.frequency.value = allpassFilterFrequencies[l]; this._allpassFiltersL.push(allpassL); } //make the allpass filters on the left for (var r = 0; r < allpassFilterFrequencies.length; r++) { var allpassR = this.context.createBiquadFilter(); allpassR.type = 'allpass'; allpassR.frequency.value = allpassFilterFrequencies[r]; this._allpassFiltersR.push(allpassR); } //make the comb filters for (var c = 0; c < combFilterTunings.length; c++) { var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]); if (c < combFilterTunings.length / 2) { this.effectSendL.chain(lfpf, this._allpassFiltersL[0]); } else { this.effectSendR.chain(lfpf, this._allpassFiltersR[0]); } this.roomSize.connect(lfpf.resonance); this.dampening.connect(lfpf.dampening); this._combFilters.push(lfpf); } //chain the allpass filters togetehr this.connectSeries.apply(this, this._allpassFiltersL); this.connectSeries.apply(this, this._allpassFiltersR); this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL); this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR); this._readOnly([ 'roomSize', 'dampening' ]); }; Tone.extend(Tone.Freeverb, Tone.StereoEffect); /** * @static * @type {Object} */ Tone.Freeverb.defaults = { 'roomSize': 0.7, 'dampening': 3000 }; /** * Clean up. * @returns {Tone.Freeverb} this */ Tone.Freeverb.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); for (var al = 0; al < this._allpassFiltersL.length; al++) { this._allpassFiltersL[al].disconnect(); this._allpassFiltersL[al] = null; } this._allpassFiltersL = null; for (var ar = 0; ar < this._allpassFiltersR.length; ar++) { this._allpassFiltersR[ar].disconnect(); this._allpassFiltersR[ar] = null; } this._allpassFiltersR = null; for (var cf = 0; cf < this._combFilters.length; cf++) { this._combFilters[cf].dispose(); this._combFilters[cf] = null; } this._combFilters = null; this._writable([ 'roomSize', 'dampening' ]); this.roomSize.dispose(); this.roomSize = null; this.dampening.dispose(); this.dampening = null; return this; }; return Tone.Freeverb; }); Module(function (Tone) { /** * an array of the comb filter delay time values * @private * @static * @type {Array} */ var combFilterDelayTimes = [ 1687 / 25000, 1601 / 25000, 2053 / 25000, 2251 / 25000 ]; /** * the resonances of each of the comb filters * @private * @static * @type {Array} */ var combFilterResonances = [ 0.773, 0.802, 0.753, 0.733 ]; /** * the allpass filter frequencies * @private * @static * @type {Array} */ var allpassFilterFreqs = [ 347, 113, 37 ]; /** * @class Tone.JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html) * tuned by John Chowning in 1970. * It is made up of three allpass filters and four Tone.FeedbackCombFilter. * * * @extends {Tone.Effect} * @constructor * @param {NormalRange|Object} [roomSize] Coorelates to the decay time. * @example * var reverb = new Tone.JCReverb(0.4).connect(Tone.Master); * var delay = new Tone.FeedbackDelay(0.5); * //connecting the synth to reverb through delay * var synth = new Tone.DuoSynth().chain(delay, reverb); * synth.triggerAttackRelease("A4","8n"); */ Tone.JCReverb = function () { var options = this.optionsObject(arguments, ['roomSize'], Tone.JCReverb.defaults); Tone.StereoEffect.call(this, options); /** * room size control values between [0,1] * @type {NormalRange} * @signal */ this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange); /** * scale the room size * @type {Tone.Scale} * @private */ this._scaleRoomSize = new Tone.Scale(-0.733, 0.197); /** * a series of allpass filters * @type {Array} * @private */ this._allpassFilters = []; /** * parallel feedback comb filters * @type {Array} * @private */ this._feedbackCombFilters = []; //make the allpass filters for (var af = 0; af < allpassFilterFreqs.length; af++) { var allpass = this.context.createBiquadFilter(); allpass.type = 'allpass'; allpass.frequency.value = allpassFilterFreqs[af]; this._allpassFilters.push(allpass); } //and the comb filters for (var cf = 0; cf < combFilterDelayTimes.length; cf++) { var fbcf = new Tone.FeedbackCombFilter(combFilterDelayTimes[cf], 0.1); this._scaleRoomSize.connect(fbcf.resonance); fbcf.resonance.value = combFilterResonances[cf]; this._allpassFilters[this._allpassFilters.length - 1].connect(fbcf); if (cf < combFilterDelayTimes.length / 2) { fbcf.connect(this.effectReturnL); } else { fbcf.connect(this.effectReturnR); } this._feedbackCombFilters.push(fbcf); } //chain the allpass filters together this.roomSize.connect(this._scaleRoomSize); this.connectSeries.apply(this, this._allpassFilters); this.effectSendL.connect(this._allpassFilters[0]); this.effectSendR.connect(this._allpassFilters[0]); this._readOnly(['roomSize']); }; Tone.extend(Tone.JCReverb, Tone.StereoEffect); /** * the default values * @static * @const * @type {Object} */ Tone.JCReverb.defaults = { 'roomSize': 0.5 }; /** * Clean up. * @returns {Tone.JCReverb} this */ Tone.JCReverb.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); for (var apf = 0; apf < this._allpassFilters.length; apf++) { this._allpassFilters[apf].disconnect(); this._allpassFilters[apf] = null; } this._allpassFilters = null; for (var fbcf = 0; fbcf < this._feedbackCombFilters.length; fbcf++) { this._feedbackCombFilters[fbcf].dispose(); this._feedbackCombFilters[fbcf] = null; } this._feedbackCombFilters = null; this._writable(['roomSize']); this.roomSize.dispose(); this.roomSize = null; this._scaleRoomSize.dispose(); this._scaleRoomSize = null; return this; }; return Tone.JCReverb; }); Module(function (Tone) { /** * @class Mid/Side processing separates the the 'mid' signal * (which comes out of both the left and the right channel) * and the 'side' (which only comes out of the the side channels) * and effects them separately before being recombined. * Applies a Mid/Side seperation and recombination. * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). * <br><br> * This is a base-class for Mid/Side Effects. * * @extends {Tone.Effect} * @constructor */ Tone.MidSideEffect = function () { Tone.Effect.apply(this, arguments); /** * The mid/side split * @type {Tone.MidSideSplit} * @private */ this._midSideSplit = new Tone.MidSideSplit(); /** * The mid/side merge * @type {Tone.MidSideMerge} * @private */ this._midSideMerge = new Tone.MidSideMerge(); /** * The mid send. Connect to mid processing * @type {Tone.Expr} * @private */ this.midSend = this._midSideSplit.mid; /** * The side send. Connect to side processing * @type {Tone.Expr} * @private */ this.sideSend = this._midSideSplit.side; /** * The mid return connection * @type {GainNode} * @private */ this.midReturn = this._midSideMerge.mid; /** * The side return connection * @type {GainNode} * @private */ this.sideReturn = this._midSideMerge.side; //the connections this.effectSend.connect(this._midSideSplit); this._midSideMerge.connect(this.effectReturn); }; Tone.extend(Tone.MidSideEffect, Tone.Effect); /** * Clean up. * @returns {Tone.MidSideEffect} this */ Tone.MidSideEffect.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._midSideSplit.dispose(); this._midSideSplit = null; this._midSideMerge.dispose(); this._midSideMerge = null; this.midSend = null; this.sideSend = null; this.midReturn = null; this.sideReturn = null; return this; }; return Tone.MidSideEffect; }); Module(function (Tone) { /** * @class Tone.Phaser is a phaser effect. Phasers work by changing the phase * of different frequency components of an incoming signal. Read more on * [Wikipedia](https://en.wikipedia.org/wiki/Phaser_(effect)). * Inspiration for this phaser comes from [Tuna.js](https://github.com/Dinahmoe/tuna/). * * @extends {Tone.StereoEffect} * @constructor * @param {Frequency|Object} [frequency] The speed of the phasing. * @param {number} [octaves] The octaves of the effect. * @param {Frequency} [baseFrequency] The base frequency of the filters. * @example * var phaser = new Tone.Phaser({ * "frequency" : 15, * "octaves" : 5, * "baseFrequency" : 1000 * }).toMaster(); * var synth = new Tone.FMSynth().connect(phaser); * synth.triggerAttackRelease("E3", "2n"); */ Tone.Phaser = function () { //set the defaults var options = this.optionsObject(arguments, [ 'frequency', 'octaves', 'baseFrequency' ], Tone.Phaser.defaults); Tone.StereoEffect.call(this, options); /** * the lfo which controls the frequency on the left side * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO(options.frequency, 0, 1); /** * the lfo which controls the frequency on the right side * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO(options.frequency, 0, 1); this._lfoR.phase = 180; /** * the base modulation frequency * @type {number} * @private */ this._baseFrequency = options.baseFrequency; /** * the octaves of the phasing * @type {number} * @private */ this._octaves = options.octaves; /** * The quality factor of the filters * @type {Positive} * @signal */ this.Q = new Tone.Signal(options.Q, Tone.Type.Positive); /** * the array of filters for the left side * @type {Array} * @private */ this._filtersL = this._makeFilters(options.stages, this._lfoL, this.Q); /** * the array of filters for the left side * @type {Array} * @private */ this._filtersR = this._makeFilters(options.stages, this._lfoR, this.Q); /** * the frequency of the effect * @type {Tone.Signal} */ this.frequency = this._lfoL.frequency; this.frequency.value = options.frequency; //connect them up this.effectSendL.connect(this._filtersL[0]); this.effectSendR.connect(this._filtersR[0]); this._filtersL[options.stages - 1].connect(this.effectReturnL); this._filtersR[options.stages - 1].connect(this.effectReturnR); //control the frequency with one LFO this._lfoL.frequency.connect(this._lfoR.frequency); //set the options this.baseFrequency = options.baseFrequency; this.octaves = options.octaves; //start the lfo this._lfoL.start(); this._lfoR.start(); this._readOnly([ 'frequency', 'Q' ]); }; Tone.extend(Tone.Phaser, Tone.StereoEffect); /** * defaults * @static * @type {object} */ Tone.Phaser.defaults = { 'frequency': 0.5, 'octaves': 3, 'stages': 10, 'Q': 10, 'baseFrequency': 350 }; /** * @param {number} stages * @returns {Array} the number of filters all connected together * @private */ Tone.Phaser.prototype._makeFilters = function (stages, connectToFreq, Q) { var filters = new Array(stages); //make all the filters for (var i = 0; i < stages; i++) { var filter = this.context.createBiquadFilter(); filter.type = 'allpass'; Q.connect(filter.Q); connectToFreq.connect(filter.frequency); filters[i] = filter; } this.connectSeries.apply(this, filters); return filters; }; /** * The number of octaves the phase goes above * the baseFrequency * @memberOf Tone.Phaser# * @type {Positive} * @name octaves */ Object.defineProperty(Tone.Phaser.prototype, 'octaves', { get: function () { return this._octaves; }, set: function (octaves) { this._octaves = octaves; var max = this._baseFrequency * Math.pow(2, octaves); this._lfoL.max = max; this._lfoR.max = max; } }); /** * The the base frequency of the filters. * @memberOf Tone.Phaser# * @type {number} * @name baseFrequency */ Object.defineProperty(Tone.Phaser.prototype, 'baseFrequency', { get: function () { return this._baseFrequency; }, set: function (freq) { this._baseFrequency = freq; this._lfoL.min = freq; this._lfoR.min = freq; this.octaves = this._octaves; } }); /** * clean up * @returns {Tone.Phaser} this */ Tone.Phaser.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable([ 'frequency', 'Q' ]); this.Q.dispose(); this.Q = null; this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; for (var i = 0; i < this._filtersL.length; i++) { this._filtersL[i].disconnect(); this._filtersL[i] = null; } this._filtersL = null; for (var j = 0; j < this._filtersR.length; j++) { this._filtersR[j].disconnect(); this._filtersR[j] = null; } this._filtersR = null; this.frequency = null; return this; }; return Tone.Phaser; }); Module(function (Tone) { /** * @class Tone.PingPongDelay is a feedback delay effect where the echo is heard * first in one channel and next in the opposite channel. In a stereo * system these are the right and left channels. * PingPongDelay in more simplified terms is two Tone.FeedbackDelays * with independent delay values. Each delay is routed to one channel * (left or right), and the channel triggered second will always * trigger at the same interval after the first. * * @constructor * @extends {Tone.StereoXFeedbackEffect} * @param {Time|Object} [delayTime] The delayTime between consecutive echos. * @param {NormalRange=} feedback The amount of the effected signal which * is fed back through the delay. * @example * var pingPong = new Tone.PingPongDelay("4n", 0.2).toMaster(); * var drum = new Tone.DrumSynth().connect(pingPong); * drum.triggerAttackRelease("C4", "32n"); */ Tone.PingPongDelay = function () { var options = this.optionsObject(arguments, [ 'delayTime', 'feedback' ], Tone.PingPongDelay.defaults); Tone.StereoXFeedbackEffect.call(this, options); /** * the delay node on the left side * @type {DelayNode} * @private */ this._leftDelay = this.context.createDelay(options.maxDelayTime); /** * the delay node on the right side * @type {DelayNode} * @private */ this._rightDelay = this.context.createDelay(options.maxDelayTime); /** * the predelay on the right side * @type {DelayNode} * @private */ this._rightPreDelay = this.context.createDelay(options.maxDelayTime); /** * the delay time signal * @type {Time} * @signal */ this.delayTime = new Tone.Signal(options.delayTime, Tone.Type.Time); //connect it up this.effectSendL.chain(this._leftDelay, this.effectReturnL); this.effectSendR.chain(this._rightPreDelay, this._rightDelay, this.effectReturnR); this.delayTime.fan(this._leftDelay.delayTime, this._rightDelay.delayTime, this._rightPreDelay.delayTime); //rearranged the feedback to be after the rightPreDelay this._feedbackLR.disconnect(); this._feedbackLR.connect(this._rightDelay); this._readOnly(['delayTime']); }; Tone.extend(Tone.PingPongDelay, Tone.StereoXFeedbackEffect); /** * @static * @type {Object} */ Tone.PingPongDelay.defaults = { 'delayTime': 0.25, 'maxDelayTime': 1 }; /** * Clean up. * @returns {Tone.PingPongDelay} this */ Tone.PingPongDelay.prototype.dispose = function () { Tone.StereoXFeedbackEffect.prototype.dispose.call(this); this._leftDelay.disconnect(); this._leftDelay = null; this._rightDelay.disconnect(); this._rightDelay = null; this._rightPreDelay.disconnect(); this._rightPreDelay = null; this._writable(['delayTime']); this.delayTime.dispose(); this.delayTime = null; return this; }; return Tone.PingPongDelay; }); Module(function (Tone) { /** * @class Tone.PitchShift does near-realtime pitch shifting to the incoming signal. * The effect is achieved by speeding up or slowing down the delayTime * of a DelayNode using a sawtooth wave. * Algorithm found in [this pdf](http://dsp-book.narod.ru/soundproc.pdf). * Additional reference by [Miller Pucket](http://msp.ucsd.edu/techniques/v0.11/book-html/node115.html). * * @extends {Tone.FeedbackEffect} * @param {Interval=} pitch The interval to transpose the incoming signal by. */ Tone.PitchShift = function () { var options = this.optionsObject(arguments, ['pitch'], Tone.PitchShift.defaults); Tone.FeedbackEffect.call(this, options); /** * The pitch signal * @type {Tone.Signal} * @private */ this._frequency = new Tone.Signal(0); /** * Uses two DelayNodes to cover up the jump in * the sawtooth wave. * @type {DelayNode} * @private */ this._delayA = new Tone.Delay(0, 1); /** * The first LFO. * @type {Tone.LFO} * @private */ this._lfoA = new Tone.LFO({ 'min': 0, 'max': 0.1, 'type': 'sawtooth' }).connect(this._delayA.delayTime); /** * The second DelayNode * @type {DelayNode} * @private */ this._delayB = new Tone.Delay(0, 1); /** * The first LFO. * @type {Tone.LFO} * @private */ this._lfoB = new Tone.LFO({ 'min': 0, 'max': 0.1, 'type': 'sawtooth', 'phase': 180 }).connect(this._delayB.delayTime); /** * Crossfade quickly between the two delay lines * to cover up the jump in the sawtooth wave * @type {Tone.CrossFade} * @private */ this._crossFade = new Tone.CrossFade(); /** * LFO which alternates between the two * delay lines to cover up the disparity in the * sawtooth wave. * @type {Tone.LFO} * @private */ this._crossFadeLFO = new Tone.LFO({ 'min': 0, 'max': 1, 'type': 'triangle', 'phase': 90 }).connect(this._crossFade.fade); /** * The delay node * @type {Tone.Delay} * @private */ this._feedbackDelay = new Tone.Delay(options.delayTime); /** * The amount of delay on the input signal * @type {Time} * @signal */ this.delayTime = this._feedbackDelay.delayTime; this._readOnly('delayTime'); /** * Hold the current pitch * @type {Number} * @private */ this._pitch = options.pitch; /** * Hold the current windowSize * @type {Number} * @private */ this._windowSize = options.windowSize; //connect the two delay lines up this._delayA.connect(this._crossFade.a); this._delayB.connect(this._crossFade.b); //connect the frequency this._frequency.fan(this._lfoA.frequency, this._lfoB.frequency, this._crossFadeLFO.frequency); //route the input this.effectSend.fan(this._delayA, this._delayB); this._crossFade.chain(this._feedbackDelay, this.effectReturn); //start the LFOs at the same time var now = this.now(); this._lfoA.start(now); this._lfoB.start(now); this._crossFadeLFO.start(now); //set the initial value this.windowSize = this._windowSize; }; Tone.extend(Tone.PitchShift, Tone.FeedbackEffect); /** * default values * @static * @type {Object} * @const */ Tone.PitchShift.defaults = { 'pitch': 0, 'windowSize': 0.1, 'delayTime': 0, 'feedback': 0 }; /** * Repitch the incoming signal by some interval (measured * in semi-tones). * @memberOf Tone.PitchShift# * @type {Interval} * @name pitch * @example * pitchShift.pitch = -12; //down one octave * pitchShift.pitch = 7; //up a fifth */ Object.defineProperty(Tone.PitchShift.prototype, 'pitch', { get: function () { return this._pitch; }, set: function (interval) { this._pitch = interval; var factor = 0; if (interval < 0) { this._lfoA.min = 0; this._lfoA.max = this._windowSize; this._lfoB.min = 0; this._lfoB.max = this._windowSize; factor = this.intervalToFrequencyRatio(interval - 1) + 1; } else { this._lfoA.min = this._windowSize; this._lfoA.max = 0; this._lfoB.min = this._windowSize; this._lfoB.max = 0; factor = this.intervalToFrequencyRatio(interval) - 1; } this._frequency.value = factor * (1.2 / this._windowSize); } }); /** * The window size corresponds roughly to the sample length in a looping sampler. * Smaller values are desirable for a less noticeable delay time of the pitch shifted * signal, but larger values will result in smoother pitch shifting for larger intervals. * A nominal range of 0.03 to 0.1 is recommended. * @memberOf Tone.PitchShift# * @type {Time} * @name windowSize * @example * pitchShift.windowSize = 0.1; */ Object.defineProperty(Tone.PitchShift.prototype, 'windowSize', { get: function () { return this._windowSize; }, set: function (size) { this._windowSize = this.toSeconds(size); this.pitch = this._pitch; } }); /** * Clean up. * @return {Tone.PitchShift} this */ Tone.PitchShift.prototype.dispose = function () { Tone.FeedbackEffect.prototype.dispose.call(this); this._frequency.dispose(); this._frequency = null; this._delayA.disconnect(); this._delayA = null; this._delayB.disconnect(); this._delayB = null; this._lfoA.dispose(); this._lfoA = null; this._lfoB.dispose(); this._lfoB = null; this._crossFade.dispose(); this._crossFade = null; this._crossFadeLFO.dispose(); this._crossFadeLFO = null; this._writable('delayTime'); this._feedbackDelay.dispose(); this._feedbackDelay = null; this.delayTime = null; return this; }; return Tone.PitchShift; }); Module(function (Tone) { /** * @class Base class for stereo feedback effects where the effectReturn * is fed back into the same channel. * * @constructor * @extends {Tone.FeedbackEffect} */ Tone.StereoFeedbackEffect = function () { var options = this.optionsObject(arguments, ['feedback'], Tone.FeedbackEffect.defaults); Tone.StereoEffect.call(this, options); /** * controls the amount of feedback * @type {NormalRange} * @signal */ this.feedback = new Tone.Signal(options.feedback, Tone.Type.NormalRange); /** * the left side feeback * @type {GainNode} * @private */ this._feedbackL = this.context.createGain(); /** * the right side feeback * @type {GainNode} * @private */ this._feedbackR = this.context.createGain(); //connect it up this.effectReturnL.chain(this._feedbackL, this.effectSendL); this.effectReturnR.chain(this._feedbackR, this.effectSendR); this.feedback.fan(this._feedbackL.gain, this._feedbackR.gain); this._readOnly(['feedback']); }; Tone.extend(Tone.StereoFeedbackEffect, Tone.FeedbackEffect); /** * clean up * @returns {Tone.StereoFeedbackEffect} this */ Tone.StereoFeedbackEffect.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable(['feedback']); this.feedback.dispose(); this.feedback = null; this._feedbackL.disconnect(); this._feedbackL = null; this._feedbackR.disconnect(); this._feedbackR = null; return this; }; return Tone.StereoFeedbackEffect; }); Module(function (Tone) { /** * @class Applies a width factor to the mid/side seperation. * 0 is all mid and 1 is all side. * Algorithm found in [kvraudio forums](http://www.kvraudio.com/forum/viewtopic.php?t=212587). * <br><br> * <code> * Mid *= 2*(1-width)<br> * Side *= 2*width * </code> * * @extends {Tone.MidSideEffect} * @constructor * @param {NormalRange|Object} [width] The stereo width. A width of 0 is mono and 1 is stereo. 0.5 is no change. */ Tone.StereoWidener = function () { var options = this.optionsObject(arguments, ['width'], Tone.StereoWidener.defaults); Tone.MidSideEffect.call(this, options); /** * The width control. 0 = 100% mid. 1 = 100% side. 0.5 = no change. * @type {NormalRange} * @signal */ this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); /** * Mid multiplier * @type {Tone.Expr} * @private */ this._midMult = new Tone.Expr('$0 * ($1 * (1 - $2))'); /** * Side multiplier * @type {Tone.Expr} * @private */ this._sideMult = new Tone.Expr('$0 * ($1 * $2)'); /** * constant output of 2 * @type {Tone} * @private */ this._two = new Tone.Signal(2); //the mid chain this._two.connect(this._midMult, 0, 1); this.width.connect(this._midMult, 0, 2); //the side chain this._two.connect(this._sideMult, 0, 1); this.width.connect(this._sideMult, 0, 2); //connect it to the effect send/return this.midSend.chain(this._midMult, this.midReturn); this.sideSend.chain(this._sideMult, this.sideReturn); this._readOnly(['width']); }; Tone.extend(Tone.StereoWidener, Tone.MidSideEffect); /** * the default values * @static * @type {Object} */ Tone.StereoWidener.defaults = { 'width': 0.5 }; /** * Clean up. * @returns {Tone.StereoWidener} this */ Tone.StereoWidener.prototype.dispose = function () { Tone.MidSideEffect.prototype.dispose.call(this); this._writable(['width']); this.width.dispose(); this.width = null; this._midMult.dispose(); this._midMult = null; this._sideMult.dispose(); this._sideMult = null; this._two.dispose(); this._two = null; return this; }; return Tone.StereoWidener; }); Module(function (Tone) { /** * @class Tone.Tremolo modulates the amplitude of an incoming signal using a Tone.LFO. * The type, frequency, and depth of the LFO is controllable. * * @extends {Tone.StereoEffect} * @constructor * @param {Frequency} [frequency] The rate of the effect. * @param {NormalRange} [depth] The depth of the effect. * @example * //create a tremolo and start it's LFO * var tremolo = new Tone.Tremolo(9, 0.75).toMaster().start(); * //route an oscillator through the tremolo and start it * var oscillator = new Tone.Oscillator().connect(tremolo).start(); */ Tone.Tremolo = function () { var options = this.optionsObject(arguments, [ 'frequency', 'depth' ], Tone.Tremolo.defaults); Tone.StereoEffect.call(this, options); /** * The tremelo LFO in the left channel * @type {Tone.LFO} * @private */ this._lfoL = new Tone.LFO({ 'phase': options.spread, 'min': 1, 'max': 0 }); /** * The tremelo LFO in the left channel * @type {Tone.LFO} * @private */ this._lfoR = new Tone.LFO({ 'phase': options.spread, 'min': 1, 'max': 0 }); /** * Where the gain is multiplied * @type {Tone.Gain} * @private */ this._amplitudeL = new Tone.Gain(); /** * Where the gain is multiplied * @type {Tone.Gain} * @private */ this._amplitudeR = new Tone.Gain(); /** * The frequency of the tremolo. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The depth of the effect. A depth of 0, has no effect * on the amplitude, and a depth of 1 makes the amplitude * modulate fully between 0 and 1. * @type {NormalRange} * @signal */ this.depth = new Tone.Signal(options.depth, Tone.Type.NormalRange); this._readOnly([ 'frequency', 'depth' ]); this.effectSendL.chain(this._amplitudeL, this.effectReturnL); this.effectSendR.chain(this._amplitudeR, this.effectReturnR); this._lfoL.connect(this._amplitudeL.gain); this._lfoR.connect(this._amplitudeR.gain); this.frequency.fan(this._lfoL.frequency, this._lfoR.frequency); this.depth.fan(this._lfoR.amplitude, this._lfoL.amplitude); this.type = options.type; this.spread = options.spread; }; Tone.extend(Tone.Tremolo, Tone.StereoEffect); /** * @static * @const * @type {Object} */ Tone.Tremolo.defaults = { 'frequency': 10, 'type': 'sine', 'depth': 0.5, 'spread': 180 }; /** * Start the tremolo. * @param {Time} [time=now] When the tremolo begins. * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.start = function (time) { this._lfoL.start(time); this._lfoR.start(time); return this; }; /** * Stop the tremolo. * @param {Time} [time=now] When the tremolo stops. * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.stop = function (time) { this._lfoL.stop(time); this._lfoR.stop(time); return this; }; /** * Sync the effect to the transport. * @param {Time} [delay=0] Delay time before starting the effect after the * Transport has started. * @returns {Tone.AutoFilter} this */ Tone.Tremolo.prototype.sync = function (delay) { this._lfoL.sync(delay); this._lfoR.sync(delay); return this; }; /** * Unsync the filter from the transport * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.unsync = function () { this._lfoL.unsync(); this._lfoR.unsync(); return this; }; /** * The Tremolo's oscillator type. * @memberOf Tone.Tremolo# * @type {string} * @name type */ Object.defineProperty(Tone.Tremolo.prototype, 'type', { get: function () { return this._lfoL.type; }, set: function (type) { this._lfoL.type = type; this._lfoR.type = type; } }); /** * Amount of stereo spread. When set to 0, both LFO's will be panned centrally. * When set to 180, LFO's will be panned hard left and right respectively. * @memberOf Tone.Tremolo# * @type {Degrees} * @name spread */ Object.defineProperty(Tone.Tremolo.prototype, 'spread', { get: function () { return this._lfoR.phase - this._lfoL.phase; //180 }, set: function (spread) { this._lfoL.phase = 90 - spread / 2; this._lfoR.phase = spread / 2 + 90; } }); /** * clean up * @returns {Tone.Tremolo} this */ Tone.Tremolo.prototype.dispose = function () { Tone.StereoEffect.prototype.dispose.call(this); this._writable([ 'frequency', 'depth' ]); this._lfoL.dispose(); this._lfoL = null; this._lfoR.dispose(); this._lfoR = null; this._amplitudeL.dispose(); this._amplitudeL = null; this._amplitudeR.dispose(); this._amplitudeR = null; this.frequency = null; this.depth = null; return this; }; return Tone.Tremolo; }); Module(function (Tone) { /** * @class A Vibrato effect composed of a Tone.Delay and a Tone.LFO. The LFO * modulates the delayTime of the delay, causing the pitch to rise * and fall. * @extends {Tone.Effect} * @param {Frequency} frequency The frequency of the vibrato. * @param {NormalRange} depth The amount the pitch is modulated. */ Tone.Vibrato = function () { var options = this.optionsObject(arguments, [ 'frequency', 'depth' ], Tone.Vibrato.defaults); Tone.Effect.call(this, options); /** * The delay node used for the vibrato effect * @type {Tone.Delay} * @private */ this._delayNode = new Tone.Delay(0, options.maxDelay); /** * The LFO used to control the vibrato * @type {Tone.LFO} * @private */ this._lfo = new Tone.LFO({ 'type': options.type, 'min': 0, 'max': options.maxDelay, 'frequency': options.frequency, 'phase': -90 //offse the phase so the resting position is in the center }).start().connect(this._delayNode.delayTime); /** * The frequency of the vibrato * @type {Frequency} * @signal */ this.frequency = this._lfo.frequency; /** * The depth of the vibrato. * @type {NormalRange} * @signal */ this.depth = this._lfo.amplitude; this.depth.value = options.depth; this._readOnly([ 'frequency', 'depth' ]); this.effectSend.chain(this._delayNode, this.effectReturn); }; Tone.extend(Tone.Vibrato, Tone.Effect); /** * The defaults * @type {Object} * @const */ Tone.Vibrato.defaults = { 'maxDelay': 0.005, 'frequency': 5, 'depth': 0.1, 'type': 'sine' }; /** * Type of oscillator attached to the Vibrato. * @memberOf Tone.Vibrato# * @type {string} * @name type */ Object.defineProperty(Tone.Vibrato.prototype, 'type', { get: function () { return this._lfo.type; }, set: function (type) { this._lfo.type = type; } }); /** * Clean up. * @returns {Tone.Vibrato} this */ Tone.Vibrato.prototype.dispose = function () { Tone.Effect.prototype.dispose.call(this); this._delayNode.dispose(); this._delayNode = null; this._lfo.dispose(); this._lfo = null; this._writable([ 'frequency', 'depth' ]); this.frequency = null; this.depth = null; }; return Tone.Vibrato; }); Module(function (Tone) { /** * @class Tone.Event abstracts away Tone.Transport.schedule and provides a schedulable * callback for a single or repeatable events along the timeline. * * @extends {Tone} * @param {function} callback The callback to invoke at the time. * @param {*} value The value or values which should be passed to * the callback function on invocation. * @example * var chord = new Tone.Event(function(time, chord){ * //the chord as well as the exact time of the event * //are passed in as arguments to the callback function * }, ["D4", "E4", "F4"]); * //start the chord at the beginning of the transport timeline * chord.start(); * //loop it every measure for 8 measures * chord.loop = 8; * chord.loopEnd = "1m"; */ Tone.Event = function () { var options = this.optionsObject(arguments, [ 'callback', 'value' ], Tone.Event.defaults); /** * Loop value * @type {Boolean|Positive} * @private */ this._loop = options.loop; /** * The callback to invoke. * @type {Function} */ this.callback = options.callback; /** * The value which is passed to the * callback function. * @type {*} * @private */ this.value = options.value; /** * When the note is scheduled to start. * @type {Number} * @private */ this._loopStart = this.toTicks(options.loopStart); /** * When the note is scheduled to start. * @type {Number} * @private */ this._loopEnd = this.toTicks(options.loopEnd); /** * Tracks the scheduled events * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * The playback speed of the note. A speed of 1 * is no change. * @private * @type {Positive} */ this._playbackRate = 1; /** * A delay time from when the event is scheduled to start * @type {Ticks} * @private */ this._startOffset = 0; /** * The probability that the callback will be invoked * at the scheduled time. * @type {NormalRange} * @example * //the callback will be invoked 50% of the time * event.probability = 0.5; */ this.probability = options.probability; /** * If set to true, will apply small (+/-0.02 seconds) random variation * to the callback time. If the value is given as a time, it will randomize * by that amount. * @example * event.humanize = true; * @type {Boolean|Time} */ this.humanize = options.humanize; /** * If mute is true, the callback won't be * invoked. * @type {Boolean} */ this.mute = options.mute; //set the initial values this.playbackRate = options.playbackRate; }; Tone.extend(Tone.Event); /** * The default values * @type {Object} * @const */ Tone.Event.defaults = { 'callback': Tone.noOp, 'loop': false, 'loopEnd': '1m', 'loopStart': 0, 'playbackRate': 1, 'value': null, 'probability': 1, 'mute': false, 'humanize': false }; /** * Reschedule all of the events along the timeline * with the updated values. * @param {Time} after Only reschedules events after the given time. * @return {Tone.Event} this * @private */ Tone.Event.prototype._rescheduleEvents = function (after) { //if no argument is given, schedules all of the events after = this.defaultArg(after, -1); this._state.forEachFrom(after, function (event) { var duration; if (event.state === Tone.State.Started) { if (!this.isUndef(event.id)) { Tone.Transport.clear(event.id); } var startTick = event.time + Math.round(this.startOffset / this._playbackRate); if (this._loop) { duration = Infinity; if (this.isNumber(this._loop)) { duration = (this._loop - 1) * this._getLoopDuration(); } var nextEvent = this._state.getEventAfter(startTick); if (nextEvent !== null) { duration = Math.min(duration, nextEvent.time - startTick); } if (duration !== Infinity) { //schedule a stop since it's finite duration this._state.setStateAtTime(Tone.State.Stopped, startTick + duration + 1); duration += 'i'; } event.id = Tone.Transport.scheduleRepeat(this._tick.bind(this), this._getLoopDuration().toString() + 'i', startTick + 'i', duration); } else { event.id = Tone.Transport.schedule(this._tick.bind(this), startTick + 'i'); } } }.bind(this)); return this; }; /** * Returns the playback state of the note, either "started" or "stopped". * @type {String} * @readOnly * @memberOf Tone.Event# * @name state */ Object.defineProperty(Tone.Event.prototype, 'state', { get: function () { return this._state.getStateAtTime(Tone.Transport.ticks); } }); /** * The start from the scheduled start time * @type {Ticks} * @memberOf Tone.Event# * @name startOffset * @private */ Object.defineProperty(Tone.Event.prototype, 'startOffset', { get: function () { return this._startOffset; }, set: function (offset) { this._startOffset = offset; } }); /** * Start the note at the given time. * @param {Time} time When the note should start. * @return {Tone.Event} this */ Tone.Event.prototype.start = function (time) { time = this.toTicks(time); if (this._state.getStateAtTime(time) === Tone.State.Stopped) { this._state.addEvent({ 'state': Tone.State.Started, 'time': time, 'id': undefined }); this._rescheduleEvents(time); } return this; }; /** * Stop the Event at the given time. * @param {Time} time When the note should stop. * @return {Tone.Event} this */ Tone.Event.prototype.stop = function (time) { this.cancel(time); time = this.toTicks(time); if (this._state.getStateAtTime(time) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, time); var previousEvent = this._state.getEventBefore(time); var reschedulTime = time; if (previousEvent !== null) { reschedulTime = previousEvent.time; } this._rescheduleEvents(reschedulTime); } return this; }; /** * Cancel all scheduled events greater than or equal to the given time * @param {Time} [time=0] The time after which events will be cancel. * @return {Tone.Event} this */ Tone.Event.prototype.cancel = function (time) { time = this.defaultArg(time, -Infinity); time = this.toTicks(time); this._state.forEachFrom(time, function (event) { Tone.Transport.clear(event.id); }); this._state.cancel(time); return this; }; /** * The callback function invoker. Also * checks if the Event is done playing * @param {Number} time The time of the event in seconds * @private */ Tone.Event.prototype._tick = function (time) { if (!this.mute && this._state.getStateAtTime(Tone.Transport.ticks) === Tone.State.Started) { if (this.probability < 1 && Math.random() > this.probability) { return; } if (this.humanize) { var variation = 0.02; if (!this.isBoolean(this.humanize)) { variation = this.toSeconds(this.humanize); } time += (Math.random() * 2 - 1) * variation; } this.callback(time, this.value); } }; /** * Get the duration of the loop. * @return {Ticks} * @private */ Tone.Event.prototype._getLoopDuration = function () { return Math.round((this._loopEnd - this._loopStart) / this._playbackRate); }; /** * If the note should loop or not * between Tone.Event.loopStart and * Tone.Event.loopEnd. An integer * value corresponds to the number of * loops the Event does after it starts. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loop */ Object.defineProperty(Tone.Event.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; this._rescheduleEvents(); } }); /** * The playback rate of the note. Defaults to 1. * @memberOf Tone.Event# * @type {Positive} * @name playbackRate * @example * note.loop = true; * //repeat the note twice as fast * note.playbackRate = 2; */ Object.defineProperty(Tone.Event.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; this._rescheduleEvents(); } }); /** * The loopEnd point is the time the event will loop. * Note: only loops if Tone.Event.loop is true. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loopEnd */ Object.defineProperty(Tone.Event.prototype, 'loopEnd', { get: function () { return this.toNotation(this._loopEnd + 'i'); }, set: function (loopEnd) { this._loopEnd = this.toTicks(loopEnd); if (this._loop) { this._rescheduleEvents(); } } }); /** * The time when the loop should start. * @memberOf Tone.Event# * @type {Boolean|Positive} * @name loopStart */ Object.defineProperty(Tone.Event.prototype, 'loopStart', { get: function () { return this.toNotation(this._loopStart + 'i'); }, set: function (loopStart) { this._loopStart = this.toTicks(loopStart); if (this._loop) { this._rescheduleEvents(); } } }); /** * The current progress of the loop interval. * Returns 0 if the event is not started yet or * it is not set to loop. * @memberOf Tone.Event# * @type {NormalRange} * @name progress * @readOnly */ Object.defineProperty(Tone.Event.prototype, 'progress', { get: function () { if (this._loop) { var ticks = Tone.Transport.ticks; var lastEvent = this._state.getEvent(ticks); if (lastEvent !== null && lastEvent.state === Tone.State.Started) { var loopDuration = this._getLoopDuration(); var progress = (ticks - lastEvent.time) % loopDuration; return progress / loopDuration; } else { return 0; } } else { return 0; } } }); /** * Clean up * @return {Tone.Event} this */ Tone.Event.prototype.dispose = function () { this.cancel(); this._state.dispose(); this._state = null; this.callback = null; this.value = null; }; return Tone.Event; }); Module(function (Tone) { /** * @class Tone.Loop creates a looped callback at the * specified interval. The callback can be * started, stopped and scheduled along * the Transport's timeline. * @example * var loop = new Tone.Loop(function(time){ * //triggered every eighth note. * console.log(time); * }, "8n").start(0); * Tone.Transport.start(); * @extends {Tone} * @param {Function} callback The callback to invoke with the * event. * @param {Array} events The events to arpeggiate over. */ Tone.Loop = function () { var options = this.optionsObject(arguments, [ 'callback', 'interval' ], Tone.Loop.defaults); /** * The event which produces the callbacks */ this._event = new Tone.Event({ 'callback': this._tick.bind(this), 'loop': true, 'loopEnd': options.interval, 'playbackRate': options.playbackRate, 'probability': options.probability }); /** * The callback to invoke with the next event in the pattern * @type {Function} */ this.callback = options.callback; //set the iterations this.iterations = options.iterations; }; Tone.extend(Tone.Loop); /** * The defaults * @const * @type {Object} */ Tone.Loop.defaults = { 'interval': '4n', 'callback': Tone.noOp, 'playbackRate': 1, 'iterations': Infinity, 'probability': true, 'mute': false }; /** * Start the loop at the specified time along the Transport's * timeline. * @param {Time=} time When to start the Loop. * @return {Tone.Loop} this */ Tone.Loop.prototype.start = function (time) { this._event.start(time); return this; }; /** * Stop the loop at the given time. * @param {Time=} time When to stop the Arpeggio * @return {Tone.Loop} this */ Tone.Loop.prototype.stop = function (time) { this._event.stop(time); return this; }; /** * Cancel all scheduled events greater than or equal to the given time * @param {Time} [time=0] The time after which events will be cancel. * @return {Tone.Loop} this */ Tone.Loop.prototype.cancel = function (time) { this._event.cancel(time); return this; }; /** * Internal function called when the notes should be called * @param {Number} time The time the event occurs * @private */ Tone.Loop.prototype._tick = function (time) { this.callback(time); }; /** * The state of the Loop, either started or stopped. * @memberOf Tone.Loop# * @type {String} * @name state * @readOnly */ Object.defineProperty(Tone.Loop.prototype, 'state', { get: function () { return this._event.state; } }); /** * The progress of the loop as a value between 0-1. 0, when * the loop is stopped or done iterating. * @memberOf Tone.Loop# * @type {NormalRange} * @name progress * @readOnly */ Object.defineProperty(Tone.Loop.prototype, 'progress', { get: function () { return this._event.progress; } }); /** * The time between successive callbacks. * @example * loop.interval = "8n"; //loop every 8n * @memberOf Tone.Loop# * @type {Time} * @name interval */ Object.defineProperty(Tone.Loop.prototype, 'interval', { get: function () { return this._event.loopEnd; }, set: function (interval) { this._event.loopEnd = interval; } }); /** * The playback rate of the loop. The normal playback rate is 1 (no change). * A `playbackRate` of 2 would be twice as fast. * @memberOf Tone.Loop# * @type {Time} * @name playbackRate */ Object.defineProperty(Tone.Loop.prototype, 'playbackRate', { get: function () { return this._event.playbackRate; }, set: function (rate) { this._event.playbackRate = rate; } }); /** * Random variation +/-0.01s to the scheduled time. * Or give it a time value which it will randomize by. * @type {Boolean|Time} * @memberOf Tone.Loop# * @name humanize */ Object.defineProperty(Tone.Loop.prototype, 'humanize', { get: function () { return this._event.humanize; }, set: function (variation) { this._event.humanize = variation; } }); /** * The probably of the callback being invoked. * @memberOf Tone.Loop# * @type {NormalRange} * @name probability */ Object.defineProperty(Tone.Loop.prototype, 'probability', { get: function () { return this._event.probability; }, set: function (prob) { this._event.probability = prob; } }); /** * Muting the Loop means that no callbacks are invoked. * @memberOf Tone.Loop# * @type {Boolean} * @name mute */ Object.defineProperty(Tone.Loop.prototype, 'mute', { get: function () { return this._event.mute; }, set: function (mute) { this._event.mute = mute; } }); /** * The number of iterations of the loop. The default * value is Infinity (loop forever). * @memberOf Tone.Loop# * @type {Positive} * @name iterations */ Object.defineProperty(Tone.Loop.prototype, 'iterations', { get: function () { if (this._event.loop === true) { return Infinity; } else { return this._event.loop; } return this._pattern.index; }, set: function (iters) { if (iters === Infinity) { this._event.loop = true; } else { this._event.loop = iters; } } }); /** * Clean up * @return {Tone.Loop} this */ Tone.Loop.prototype.dispose = function () { this._event.dispose(); this._event = null; this.callback = null; }; return Tone.Loop; }); Module(function (Tone) { /** * @class Tone.Part is a collection Tone.Events which can be * started/stoped and looped as a single unit. * * @extends {Tone.Event} * @param {Function} callback The callback to invoke on each event * @param {Array} events the array of events * @example * var part = new Tone.Part(function(time, note){ * //the notes given as the second element in the array * //will be passed in as the second argument * synth.triggerAttackRelease(note, "8n", time); * }, [[0, "C2"], ["0:2", "C3"], ["0:3:2", "G2"]]); * @example * //use an array of objects as long as the object has a "time" attribute * var part = new Tone.Part(function(time, value){ * //the value is an object which contains both the note and the velocity * synth.triggerAttackRelease(value.note, "8n", time, value.velocity); * }, [{"time" : 0, "note" : "C3", "velocity": 0.9}, * {"time" : "0:2", "note" : "C4", "velocity": 0.5} * ]).start(0); */ Tone.Part = function () { var options = this.optionsObject(arguments, [ 'callback', 'events' ], Tone.Part.defaults); /** * If the part is looping or not * @type {Boolean|Positive} * @private */ this._loop = options.loop; /** * When the note is scheduled to start. * @type {Ticks} * @private */ this._loopStart = this.toTicks(options.loopStart); /** * When the note is scheduled to start. * @type {Ticks} * @private */ this._loopEnd = this.toTicks(options.loopEnd); /** * The playback rate of the part * @type {Positive} * @private */ this._playbackRate = options.playbackRate; /** * private holder of probability value * @type {NormalRange} * @private */ this._probability = options.probability; /** * the amount of variation from the * given time. * @type {Boolean|Time} * @private */ this._humanize = options.humanize; /** * The start offset * @type {Ticks} * @private */ this._startOffset = 0; /** * Keeps track of the current state * @type {Tone.TimelineState} * @private */ this._state = new Tone.TimelineState(Tone.State.Stopped); /** * An array of Objects. * @type {Array} * @private */ this._events = []; /** * The callback to invoke at all the scheduled events. * @type {Function} */ this.callback = options.callback; /** * If mute is true, the callback won't be * invoked. * @type {Boolean} */ this.mute = options.mute; //add the events var events = this.defaultArg(options.events, []); if (!this.isUndef(options.events)) { for (var i = 0; i < events.length; i++) { if (Array.isArray(events[i])) { this.add(events[i][0], events[i][1]); } else { this.add(events[i]); } } } }; Tone.extend(Tone.Part, Tone.Event); /** * The default values * @type {Object} * @const */ Tone.Part.defaults = { 'callback': Tone.noOp, 'loop': false, 'loopEnd': '1m', 'loopStart': 0, 'playbackRate': 1, 'probability': 1, 'humanize': false, 'mute': false }; /** * Start the part at the given time. * @param {Time} time When to start the part. * @param {Time=} offset The offset from the start of the part * to begin playing at. * @return {Tone.Part} this */ Tone.Part.prototype.start = function (time, offset) { var ticks = this.toTicks(time); if (this._state.getStateAtTime(ticks) !== Tone.State.Started) { offset = this.defaultArg(offset, 0); offset = this.toTicks(offset); this._state.addEvent({ 'state': Tone.State.Started, 'time': ticks, 'offset': offset }); this._forEach(function (event) { this._startNote(event, ticks, offset); }); } return this; }; /** * Start the event in the given event at the correct time given * the ticks and offset and looping. * @param {Tone.Event} event * @param {Ticks} ticks * @param {Ticks} offset * @private */ Tone.Part.prototype._startNote = function (event, ticks, offset) { ticks -= offset; if (this._loop) { if (event.startOffset >= this._loopStart && event.startOffset < this._loopEnd) { if (event.startOffset < offset) { //start it on the next loop ticks += this._getLoopDuration(); } event.start(ticks + 'i'); } } else { if (event.startOffset >= offset) { event.start(ticks + 'i'); } } }; /** * The start from the scheduled start time * @type {Ticks} * @memberOf Tone.Part# * @name startOffset * @private */ Object.defineProperty(Tone.Part.prototype, 'startOffset', { get: function () { return this._startOffset; }, set: function (offset) { this._startOffset = offset; this._forEach(function (event) { event.startOffset += this._startOffset; }); } }); /** * Stop the part at the given time. * @param {Time} time When to stop the part. * @return {Tone.Part} this */ Tone.Part.prototype.stop = function (time) { var ticks = this.toTicks(time); if (this._state.getStateAtTime(ticks) === Tone.State.Started) { this._state.setStateAtTime(Tone.State.Stopped, ticks); this._forEach(function (event) { event.stop(time); }); } return this; }; /** * Get/Set an Event's value at the given time. * If a value is passed in and no event exists at * the given time, one will be created with that value. * If two events are at the same time, the first one will * be returned. * @example * part.at("1m"); //returns the part at the first measure * * part.at("2m", "C2"); //set the value at "2m" to C2. * //if an event didn't exist at that time, it will be created. * @param {Time} time the time of the event to get or set * @param {*=} value If a value is passed in, the value of the * event at the given time will be set to it. * @return {Tone.Event} the event at the time */ Tone.Part.prototype.at = function (time, value) { time = this.toTicks(time); var tickTime = this.ticksToSeconds(1); for (var i = 0; i < this._events.length; i++) { var event = this._events[i]; if (Math.abs(time - event.startOffset) < tickTime) { if (!this.isUndef(value)) { event.value = value; } return event; } } //if there was no event at that time, create one if (!this.isUndef(value)) { this.add(time + 'i', value); //return the new event return this._events[this._events.length - 1]; } else { return null; } }; /** * Add a an event to the part. * @param {Time} time The time the note should start. * If an object is passed in, it should * have a 'time' attribute and the rest * of the object will be used as the 'value'. * @param {Tone.Event|*} value * @returns {Tone.Part} this * @example * part.add("1m", "C#+11"); */ Tone.Part.prototype.add = function (time, value) { //extract the parameters if (this.isObject(time) && time.hasOwnProperty('time')) { value = time; time = value.time; delete value.time; } time = this.toTicks(time); var event; if (value instanceof Tone.Event) { event = value; event.callback = this._tick.bind(this); } else { event = new Tone.Event({ 'callback': this._tick.bind(this), 'value': value }); } //the start offset event.startOffset = time; //initialize the values event.set({ 'loopEnd': this.loopEnd, 'loopStart': this.loopStart, 'loop': this.loop, 'humanize': this.humanize, 'playbackRate': this.playbackRate, 'probability': this.probability }); this._events.push(event); //start the note if it should be played right now this._restartEvent(event); return this; }; /** * Restart the given event * @param {Tone.Event} event * @private */ Tone.Part.prototype._restartEvent = function (event) { var stateEvent = this._state.getEvent(this.now()); if (stateEvent && stateEvent.state === Tone.State.Started) { this._startNote(event, stateEvent.time, stateEvent.offset); } }; /** * Remove an event from the part. Will recursively iterate * into nested parts to find the event. * @param {Time} time The time of the event * @param {*} value Optionally select only a specific event value */ Tone.Part.prototype.remove = function (time, value) { //extract the parameters if (this.isObject(time) && time.hasOwnProperty('time')) { value = time; time = value.time; } time = this.toTicks(time); for (var i = this._events.length - 1; i >= 0; i--) { var event = this._events[i]; if (event instanceof Tone.Part) { event.remove(time, value); } else { if (event.startOffset === time) { if (this.isUndef(value) || !this.isUndef(value) && event.value === value) { this._events.splice(i, 1); event.dispose(); } } } } return this; }; /** * Remove all of the notes from the group. * @return {Tone.Part} this */ Tone.Part.prototype.removeAll = function () { this._forEach(function (event) { event.dispose(); }); this._events = []; return this; }; /** * Cancel scheduled state change events: i.e. "start" and "stop". * @param {Time} after The time after which to cancel the scheduled events. * @return {Tone.Part} this */ Tone.Part.prototype.cancel = function (after) { this._forEach(function (event) { event.cancel(after); }); this._state.cancel(after); return this; }; /** * Iterate over all of the events * @param {Function} callback * @param {Object} ctx The context * @private */ Tone.Part.prototype._forEach = function (callback, ctx) { ctx = this.defaultArg(ctx, this); for (var i = this._events.length - 1; i >= 0; i--) { var e = this._events[i]; if (e instanceof Tone.Part) { e._forEach(callback, ctx); } else { callback.call(ctx, e); } } return this; }; /** * Set the attribute of all of the events * @param {String} attr the attribute to set * @param {*} value The value to set it to * @private */ Tone.Part.prototype._setAll = function (attr, value) { this._forEach(function (event) { event[attr] = value; }); }; /** * Internal tick method * @param {Number} time The time of the event in seconds * @private */ Tone.Part.prototype._tick = function (time, value) { if (!this.mute) { this.callback(time, value); } }; /** * Determine if the event should be currently looping * given the loop boundries of this Part. * @param {Tone.Event} event The event to test * @private */ Tone.Part.prototype._testLoopBoundries = function (event) { if (event.startOffset < this._loopStart || event.startOffset >= this._loopEnd) { event.cancel(); } else { //reschedule it if it's stopped if (event.state === Tone.State.Stopped) { this._restartEvent(event); } } }; /** * The probability of the notes being triggered. * @memberOf Tone.Part# * @type {NormalRange} * @name probability */ Object.defineProperty(Tone.Part.prototype, 'probability', { get: function () { return this._probability; }, set: function (prob) { this._probability = prob; this._setAll('probability', prob); } }); /** * If set to true, will apply small random variation * to the callback time. If the value is given as a time, it will randomize * by that amount. * @example * event.humanize = true; * @type {Boolean|Time} * @name humanize */ Object.defineProperty(Tone.Part.prototype, 'humanize', { get: function () { return this._humanize; }, set: function (variation) { this._humanize = variation; this._setAll('humanize', variation); } }); /** * If the part should loop or not * between Tone.Part.loopStart and * Tone.Part.loopEnd. An integer * value corresponds to the number of * loops the Part does after it starts. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loop * @example * //loop the part 8 times * part.loop = 8; */ Object.defineProperty(Tone.Part.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; this._forEach(function (event) { event._loopStart = this._loopStart; event._loopEnd = this._loopEnd; event.loop = loop; this._testLoopBoundries(event); }); } }); /** * The loopEnd point determines when it will * loop if Tone.Part.loop is true. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loopEnd */ Object.defineProperty(Tone.Part.prototype, 'loopEnd', { get: function () { return this.toNotation(this._loopEnd + 'i'); }, set: function (loopEnd) { this._loopEnd = this.toTicks(loopEnd); if (this._loop) { this._forEach(function (event) { event.loopEnd = this.loopEnd; this._testLoopBoundries(event); }); } } }); /** * The loopStart point determines when it will * loop if Tone.Part.loop is true. * @memberOf Tone.Part# * @type {Boolean|Positive} * @name loopStart */ Object.defineProperty(Tone.Part.prototype, 'loopStart', { get: function () { return this.toNotation(this._loopStart + 'i'); }, set: function (loopStart) { this._loopStart = this.toTicks(loopStart); if (this._loop) { this._forEach(function (event) { event.loopStart = this.loopStart; this._testLoopBoundries(event); }); } } }); /** * The playback rate of the part * @memberOf Tone.Part# * @type {Positive} * @name playbackRate */ Object.defineProperty(Tone.Part.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; this._setAll('playbackRate', rate); } }); /** * The number of scheduled notes in the part. * @memberOf Tone.Part# * @type {Positive} * @name length * @readOnly */ Object.defineProperty(Tone.Part.prototype, 'length', { get: function () { return this._events.length; } }); /** * Clean up * @return {Tone.Part} this */ Tone.Part.prototype.dispose = function () { this.removeAll(); this._state.dispose(); this._state = null; this.callback = null; this._events = null; return this; }; return Tone.Part; }); Module(function (Tone) { /** * @class Tone.Pattern arpeggiates between the given notes * in a number of patterns. See Tone.CtrlPattern for * a full list of patterns. * @example * var pattern = new Tone.Pattern(function(time, note){ * //the order of the notes passed in depends on the pattern * }, ["C2", "D4", "E5", "A6"], "upDown"); * @extends {Tone.Loop} * @param {Function} callback The callback to invoke with the * event. * @param {Array} events The events to arpeggiate over. */ Tone.Pattern = function () { var options = this.optionsObject(arguments, [ 'callback', 'events', 'pattern' ], Tone.Pattern.defaults); Tone.Loop.call(this, options); /** * The pattern manager * @type {Tone.CtrlPattern} * @private */ this._pattern = new Tone.CtrlPattern({ 'values': options.events, 'type': options.pattern, 'index': options.index }); }; Tone.extend(Tone.Pattern, Tone.Loop); /** * The defaults * @const * @type {Object} */ Tone.Pattern.defaults = { 'pattern': Tone.CtrlPattern.Type.Up, 'events': [] }; /** * Internal function called when the notes should be called * @param {Number} time The time the event occurs * @private */ Tone.Pattern.prototype._tick = function (time) { this.callback(time, this._pattern.value); this._pattern.next(); }; /** * The current index in the events array. * @memberOf Tone.Pattern# * @type {Positive} * @name index */ Object.defineProperty(Tone.Pattern.prototype, 'index', { get: function () { return this._pattern.index; }, set: function (i) { this._pattern.index = i; } }); /** * The array of events. * @memberOf Tone.Pattern# * @type {Array} * @name events */ Object.defineProperty(Tone.Pattern.prototype, 'events', { get: function () { return this._pattern.values; }, set: function (vals) { this._pattern.values = vals; } }); /** * The current value of the pattern. * @memberOf Tone.Pattern# * @type {*} * @name value * @readOnly */ Object.defineProperty(Tone.Pattern.prototype, 'value', { get: function () { return this._pattern.value; } }); /** * The pattern type. See Tone.CtrlPattern for the full list of patterns. * @memberOf Tone.Pattern# * @type {String} * @name pattern */ Object.defineProperty(Tone.Pattern.prototype, 'pattern', { get: function () { return this._pattern.type; }, set: function (pattern) { this._pattern.type = pattern; } }); /** * Clean up * @return {Tone.Pattern} this */ Tone.Pattern.prototype.dispose = function () { Tone.Loop.prototype.dispose.call(this); this._pattern.dispose(); this._pattern = null; }; return Tone.Pattern; }); Module(function (Tone) { /** * @class A sequence is an alternate notation of a part. Instead * of passing in an array of [time, event] pairs, pass * in an array of events which will be spaced at the * given subdivision. Sub-arrays will subdivide that beat * by the number of items are in the array. * Sequence notation inspiration from [Tidal](http://yaxu.org/tidal/) * @param {Function} callback The callback to invoke with every note * @param {Array} events The sequence * @param {Time} subdivision The subdivision between which events are placed. * @extends {Tone.Part} * @example * var seq = new Tone.Sequence(function(time, note){ * console.log(note); * //straight quater notes * }, ["C4", "E4", "G4", "A4"], "4n"); * @example * var seq = new Tone.Sequence(function(time, note){ * console.log(note); * //subdivisions are given as subarrays * }, ["C4", ["E4", "D4", "E4"], "G4", ["A4", "G4"]]); */ Tone.Sequence = function () { var options = this.optionsObject(arguments, [ 'callback', 'events', 'subdivision' ], Tone.Sequence.defaults); //remove the events var events = options.events; delete options.events; Tone.Part.call(this, options); /** * The subdivison of each note * @type {Ticks} * @private */ this._subdivision = this.toTicks(options.subdivision); //if no time was passed in, the loop end is the end of the cycle if (this.isUndef(options.loopEnd) && !this.isUndef(events)) { this._loopEnd = events.length * this._subdivision; } //defaults to looping this._loop = true; //add all of the events if (!this.isUndef(events)) { for (var i = 0; i < events.length; i++) { this.add(i, events[i]); } } }; Tone.extend(Tone.Sequence, Tone.Part); /** * The default values. * @type {Object} */ Tone.Sequence.defaults = { 'subdivision': '4n' }; /** * The subdivision of the sequence. This can only be * set in the constructor. The subdivision is the * interval between successive steps. * @type {Time} * @memberOf Tone.Sequence# * @name subdivision * @readOnly */ Object.defineProperty(Tone.Sequence.prototype, 'subdivision', { get: function () { return this.toNotation(this._subdivision + 'i'); } }); /** * Get/Set an index of the sequence. If the index contains a subarray, * a Tone.Sequence representing that sub-array will be returned. * @example * var sequence = new Tone.Sequence(playNote, ["E4", "C4", "F#4", ["A4", "Bb3"]]) * sequence.at(0)// => returns "E4" * //set a value * sequence.at(0, "G3"); * //get a nested sequence * sequence.at(3).at(1)// => returns "Bb3" * @param {Positive} index The index to get or set * @param {*} value Optionally pass in the value to set at the given index. */ Tone.Sequence.prototype.at = function (index, value) { //if the value is an array, if (this.isArray(value)) { //remove the current event at that index this.remove(index); } //call the parent's method return Tone.Part.prototype.at.call(this, this._indexTime(index), value); }; /** * Add an event at an index, if there's already something * at that index, overwrite it. If `value` is an array, * it will be parsed as a subsequence. * @param {Number} index The index to add the event to * @param {*} value The value to add at that index * @returns {Tone.Sequence} this */ Tone.Sequence.prototype.add = function (index, value) { if (value === null) { return this; } if (this.isArray(value)) { //make a subsequence and add that to the sequence var subSubdivision = Math.round(this._subdivision / value.length) + 'i'; value = new Tone.Sequence(this._tick.bind(this), value, subSubdivision); } Tone.Part.prototype.add.call(this, this._indexTime(index), value); return this; }; /** * Remove a value from the sequence by index * @param {Number} index The index of the event to remove * @returns {Tone.Sequence} this */ Tone.Sequence.prototype.remove = function (index, value) { Tone.Part.prototype.remove.call(this, this._indexTime(index), value); return this; }; /** * Get the time of the index given the Sequence's subdivision * @param {Number} index * @return {Time} The time of that index * @private */ Tone.Sequence.prototype._indexTime = function (index) { if (this.isTicks(index)) { return index; } else { return index * this._subdivision + this.startOffset + 'i'; } }; /** * Clean up. * @return {Tone.Sequence} this */ Tone.Sequence.prototype.dispose = function () { Tone.Part.prototype.dispose.call(this); return this; }; return Tone.Sequence; }); Module(function (Tone) { /** * @class Tone.PulseOscillator is a pulse oscillator with control over pulse width, * also known as the duty cycle. At 50% duty cycle (width = 0.5) the wave is * a square and only odd-numbered harmonics are present. At all other widths * even-numbered harmonics are present. Read more * [here](https://wigglewave.wordpress.com/2014/08/16/pulse-waveforms-and-harmonics/). * * @constructor * @extends {Tone.Oscillator} * @param {Frequency} [frequency] The frequency of the oscillator * @param {NormalRange} [width] The width of the pulse * @example * var pulse = new Tone.PulseOscillator("E5", 0.4).toMaster().start(); */ Tone.PulseOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'width' ], Tone.Oscillator.defaults); Tone.Source.call(this, options); /** * The width of the pulse. * @type {NormalRange} * @signal */ this.width = new Tone.Signal(options.width, Tone.Type.NormalRange); /** * gate the width amount * @type {GainNode} * @private */ this._widthGate = this.context.createGain(); /** * the sawtooth oscillator * @type {Tone.Oscillator} * @private */ this._sawtooth = new Tone.Oscillator({ frequency: options.frequency, detune: options.detune, type: 'sawtooth', phase: options.phase }); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this._sawtooth.frequency; /** * The detune in cents. * @type {Cents} * @signal */ this.detune = this._sawtooth.detune; /** * Threshold the signal to turn it into a square * @type {Tone.WaveShaper} * @private */ this._thresh = new Tone.WaveShaper(function (val) { if (val < 0) { return -1; } else { return 1; } }); //connections this._sawtooth.chain(this._thresh, this.output); this.width.chain(this._widthGate, this._thresh); this._readOnly([ 'width', 'frequency', 'detune' ]); }; Tone.extend(Tone.PulseOscillator, Tone.Oscillator); /** * The default parameters. * @static * @const * @type {Object} */ Tone.PulseOscillator.defaults = { 'frequency': 440, 'detune': 0, 'phase': 0, 'width': 0.2 }; /** * start the oscillator * @param {Time} time * @private */ Tone.PulseOscillator.prototype._start = function (time) { time = this.toSeconds(time); this._sawtooth.start(time); this._widthGate.gain.setValueAtTime(1, time); }; /** * stop the oscillator * @param {Time} time * @private */ Tone.PulseOscillator.prototype._stop = function (time) { time = this.toSeconds(time); this._sawtooth.stop(time); //the width is still connected to the output. //that needs to be stopped also this._widthGate.gain.setValueAtTime(0, time); }; /** * The phase of the oscillator in degrees. * @memberOf Tone.PulseOscillator# * @type {Degrees} * @name phase */ Object.defineProperty(Tone.PulseOscillator.prototype, 'phase', { get: function () { return this._sawtooth.phase; }, set: function (phase) { this._sawtooth.phase = phase; } }); /** * The type of the oscillator. Always returns "pulse". * @readOnly * @memberOf Tone.PulseOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.PulseOscillator.prototype, 'type', { get: function () { return 'pulse'; } }); /** * The partials of the waveform. Cannot set partials for this waveform type * @memberOf Tone.PulseOscillator# * @type {Array} * @name partials * @private */ Object.defineProperty(Tone.PulseOscillator.prototype, 'partials', { get: function () { return []; } }); /** * Clean up method. * @return {Tone.PulseOscillator} this */ Tone.PulseOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._sawtooth.dispose(); this._sawtooth = null; this._writable([ 'width', 'frequency', 'detune' ]); this.width.dispose(); this.width = null; this._widthGate.disconnect(); this._widthGate = null; this._widthGate = null; this._thresh.disconnect(); this._thresh = null; this.frequency = null; this.detune = null; return this; }; return Tone.PulseOscillator; }); Module(function (Tone) { /** * @class Tone.PWMOscillator modulates the width of a Tone.PulseOscillator * at the modulationFrequency. This has the effect of continuously * changing the timbre of the oscillator by altering the harmonics * generated. * * @extends {Tone.Oscillator} * @constructor * @param {Frequency} frequency The starting frequency of the oscillator. * @param {Frequency} modulationFrequency The modulation frequency of the width of the pulse. * @example * var pwm = new Tone.PWMOscillator("Ab3", 0.3).toMaster().start(); */ Tone.PWMOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'modulationFrequency' ], Tone.PWMOscillator.defaults); Tone.Source.call(this, options); /** * the pulse oscillator * @type {Tone.PulseOscillator} * @private */ this._pulse = new Tone.PulseOscillator(options.modulationFrequency); //change the pulse oscillator type this._pulse._sawtooth.type = 'sine'; /** * the modulator * @type {Tone.Oscillator} * @private */ this._modulator = new Tone.Oscillator({ 'frequency': options.frequency, 'detune': options.detune, 'phase': options.phase }); /** * Scale the oscillator so it doesn't go silent * at the extreme values. * @type {Tone.Multiply} * @private */ this._scale = new Tone.Multiply(1.01); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this._modulator.frequency; /** * The detune of the oscillator. * @type {Cents} * @signal */ this.detune = this._modulator.detune; /** * The modulation rate of the oscillator. * @type {Frequency} * @signal */ this.modulationFrequency = this._pulse.frequency; //connections this._modulator.chain(this._scale, this._pulse.width); this._pulse.connect(this.output); this._readOnly([ 'modulationFrequency', 'frequency', 'detune' ]); }; Tone.extend(Tone.PWMOscillator, Tone.Oscillator); /** * default values * @static * @type {Object} * @const */ Tone.PWMOscillator.defaults = { 'frequency': 440, 'detune': 0, 'phase': 0, 'modulationFrequency': 0.4 }; /** * start the oscillator * @param {Time} [time=now] * @private */ Tone.PWMOscillator.prototype._start = function (time) { time = this.toSeconds(time); this._modulator.start(time); this._pulse.start(time); }; /** * stop the oscillator * @param {Time} time (optional) timing parameter * @private */ Tone.PWMOscillator.prototype._stop = function (time) { time = this.toSeconds(time); this._modulator.stop(time); this._pulse.stop(time); }; /** * The type of the oscillator. Always returns "pwm". * @readOnly * @memberOf Tone.PWMOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.PWMOscillator.prototype, 'type', { get: function () { return 'pwm'; } }); /** * The partials of the waveform. Cannot set partials for this waveform type * @memberOf Tone.PWMOscillator# * @type {Array} * @name partials * @private */ Object.defineProperty(Tone.PWMOscillator.prototype, 'partials', { get: function () { return []; } }); /** * The phase of the oscillator in degrees. * @memberOf Tone.PWMOscillator# * @type {number} * @name phase */ Object.defineProperty(Tone.PWMOscillator.prototype, 'phase', { get: function () { return this._modulator.phase; }, set: function (phase) { this._modulator.phase = phase; } }); /** * Clean up. * @return {Tone.PWMOscillator} this */ Tone.PWMOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._pulse.dispose(); this._pulse = null; this._scale.dispose(); this._scale = null; this._modulator.dispose(); this._modulator = null; this._writable([ 'modulationFrequency', 'frequency', 'detune' ]); this.frequency = null; this.detune = null; this.modulationFrequency = null; return this; }; return Tone.PWMOscillator; }); Module(function (Tone) { /** * @class Tone.OmniOscillator aggregates Tone.Oscillator, Tone.PulseOscillator, * and Tone.PWMOscillator into one class, allowing it to have the * types: sine, square, triangle, sawtooth, pulse or pwm. Additionally, * OmniOscillator is capable of setting the first x number of partials * of the oscillator. For example: "sine4" would set be the first 4 * partials of the sine wave and "triangle8" would set the first * 8 partials of the triangle wave. * * @extends {Tone.Oscillator} * @constructor * @param {Frequency} frequency The initial frequency of the oscillator. * @param {string} type The type of the oscillator. * @example * var omniOsc = new Tone.OmniOscillator("C#4", "pwm"); */ Tone.OmniOscillator = function () { var options = this.optionsObject(arguments, [ 'frequency', 'type' ], Tone.OmniOscillator.defaults); Tone.Source.call(this, options); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(options.frequency, Tone.Type.Frequency); /** * The detune control * @type {Cents} * @signal */ this.detune = new Tone.Signal(options.detune, Tone.Type.Cents); /** * the type of the oscillator source * @type {string} * @private */ this._sourceType = undefined; /** * the oscillator * @type {Tone.Oscillator|Tone.PWMOscillator|Tone.PulseOscillator} * @private */ this._oscillator = null; //set the oscillator this.type = options.type; this.phase = options.phase; this._readOnly([ 'frequency', 'detune' ]); if (this.isArray(options.partials)) { this.partials = options.partials; } }; Tone.extend(Tone.OmniOscillator, Tone.Oscillator); /** * default values * @static * @type {Object} * @const */ Tone.OmniOscillator.defaults = { 'frequency': 440, 'detune': 0, 'type': 'sine', 'phase': 0, 'width': 0.4, //only applies if the oscillator is set to "pulse", 'modulationFrequency': 0.4 }; /** * @enum {string} * @private */ var OmniOscType = { PulseOscillator: 'PulseOscillator', PWMOscillator: 'PWMOscillator', Oscillator: 'Oscillator' }; /** * start the oscillator * @param {Time} [time=now] the time to start the oscillator * @private */ Tone.OmniOscillator.prototype._start = function (time) { this._oscillator.start(time); }; /** * start the oscillator * @param {Time} [time=now] the time to start the oscillator * @private */ Tone.OmniOscillator.prototype._stop = function (time) { this._oscillator.stop(time); }; /** * The type of the oscillator. sine, square, triangle, sawtooth, pwm, or pulse. * @memberOf Tone.OmniOscillator# * @type {string} * @name type */ Object.defineProperty(Tone.OmniOscillator.prototype, 'type', { get: function () { return this._oscillator.type; }, set: function (type) { if (type.indexOf('sine') === 0 || type.indexOf('square') === 0 || type.indexOf('triangle') === 0 || type.indexOf('sawtooth') === 0 || type === Tone.Oscillator.Type.Custom) { if (this._sourceType !== OmniOscType.Oscillator) { this._sourceType = OmniOscType.Oscillator; this._createNewOscillator(Tone.Oscillator); } this._oscillator.type = type; } else if (type === 'pwm') { if (this._sourceType !== OmniOscType.PWMOscillator) { this._sourceType = OmniOscType.PWMOscillator; this._createNewOscillator(Tone.PWMOscillator); } } else if (type === 'pulse') { if (this._sourceType !== OmniOscType.PulseOscillator) { this._sourceType = OmniOscType.PulseOscillator; this._createNewOscillator(Tone.PulseOscillator); } } else { throw new Error('Tone.OmniOscillator does not support type ' + type); } } }); /** * The partials of the waveform. A partial represents * the amplitude at a harmonic. The first harmonic is the * fundamental frequency, the second is the octave and so on * following the harmonic series. * Setting this value will automatically set the type to "custom". * The value is an empty array when the type is not "custom". * @memberOf Tone.OmniOscillator# * @type {Array} * @name partials * @example * osc.partials = [1, 0.2, 0.01]; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'partials', { get: function () { return this._oscillator.partials; }, set: function (partials) { if (this._sourceType !== OmniOscType.Oscillator) { this.type = Tone.Oscillator.Type.Custom; } this._oscillator.partials = partials; } }); /** * connect the oscillator to the frequency and detune signals * @private */ Tone.OmniOscillator.prototype._createNewOscillator = function (OscillatorConstructor) { //short delay to avoid clicks on the change var now = this.now() + this.blockTime; if (this._oscillator !== null) { var oldOsc = this._oscillator; oldOsc.stop(now); //dispose the old one setTimeout(function () { oldOsc.dispose(); oldOsc = null; }, this.blockTime * 1000); } this._oscillator = new OscillatorConstructor(); this.frequency.connect(this._oscillator.frequency); this.detune.connect(this._oscillator.detune); this._oscillator.connect(this.output); if (this.state === Tone.State.Started) { this._oscillator.start(now); } }; /** * The phase of the oscillator in degrees. * @memberOf Tone.OmniOscillator# * @type {Degrees} * @name phase */ Object.defineProperty(Tone.OmniOscillator.prototype, 'phase', { get: function () { return this._oscillator.phase; }, set: function (phase) { this._oscillator.phase = phase; } }); /** * The width of the oscillator (only if the oscillator is set to pulse) * @memberOf Tone.OmniOscillator# * @type {NormalRange} * @signal * @name width * @example * var omniOsc = new Tone.OmniOscillator(440, "pulse"); * //can access the width attribute only if type === "pulse" * omniOsc.width.value = 0.2; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'width', { get: function () { if (this._sourceType === OmniOscType.PulseOscillator) { return this._oscillator.width; } } }); /** * The modulationFrequency Signal of the oscillator * (only if the oscillator type is set to pwm). * @memberOf Tone.OmniOscillator# * @type {Frequency} * @signal * @name modulationFrequency * @example * var omniOsc = new Tone.OmniOscillator(440, "pwm"); * //can access the modulationFrequency attribute only if type === "pwm" * omniOsc.modulationFrequency.value = 0.2; */ Object.defineProperty(Tone.OmniOscillator.prototype, 'modulationFrequency', { get: function () { if (this._sourceType === OmniOscType.PWMOscillator) { return this._oscillator.modulationFrequency; } } }); /** * Clean up. * @return {Tone.OmniOscillator} this */ Tone.OmniOscillator.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this._writable([ 'frequency', 'detune' ]); this.detune.dispose(); this.detune = null; this.frequency.dispose(); this.frequency = null; this._oscillator.dispose(); this._oscillator = null; this._sourceType = null; return this; }; return Tone.OmniOscillator; }); Module(function (Tone) { /** * @class Base-class for all instruments * * @constructor * @extends {Tone} */ Tone.Instrument = function (options) { //get the defaults options = this.defaultArg(options, Tone.Instrument.defaults); /** * The output and volume triming node * @type {Tone.Volume} * @private */ this._volume = this.output = new Tone.Volume(options.volume); /** * The volume of the output in decibels. * @type {Decibels} * @signal * @example * source.volume.value = -6; */ this.volume = this._volume.volume; this._readOnly('volume'); }; Tone.extend(Tone.Instrument); /** * the default attributes * @type {object} */ Tone.Instrument.defaults = { /** the volume of the output in decibels */ 'volume': 0 }; /** * @abstract * @param {string|number} note the note to trigger * @param {Time} [time=now] the time to trigger the ntoe * @param {number} [velocity=1] the velocity to trigger the note */ Tone.Instrument.prototype.triggerAttack = Tone.noOp; /** * @abstract * @param {Time} [time=now] when to trigger the release */ Tone.Instrument.prototype.triggerRelease = Tone.noOp; /** * Trigger the attack and then the release after the duration. * @param {Frequency} note The note to trigger. * @param {Time} duration How long the note should be held for before * triggering the release. * @param {Time} [time=now] When the note should be triggered. * @param {NormalRange} [velocity=1] The velocity the note should be triggered at. * @returns {Tone.Instrument} this * @example * //trigger "C4" for the duration of an 8th note * synth.triggerAttackRelease("C4", "8n"); */ Tone.Instrument.prototype.triggerAttackRelease = function (note, duration, time, velocity) { time = this.toSeconds(time); duration = this.toSeconds(duration); this.triggerAttack(note, time, velocity); this.triggerRelease(time + duration); return this; }; /** * clean up * @returns {Tone.Instrument} this */ Tone.Instrument.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._volume.dispose(); this._volume = null; this._writable(['volume']); this.volume = null; return this; }; return Tone.Instrument; }); Module(function (Tone) { /** * @class This is an abstract base class for other monophonic instruments to * extend. IMPORTANT: It does not make any sound on its own and * shouldn't be directly instantiated. * * @constructor * @abstract * @extends {Tone.Instrument} */ Tone.Monophonic = function (options) { //get the defaults options = this.defaultArg(options, Tone.Monophonic.defaults); Tone.Instrument.call(this, options); /** * The glide time between notes. * @type {Time} */ this.portamento = options.portamento; }; Tone.extend(Tone.Monophonic, Tone.Instrument); /** * @static * @const * @type {Object} */ Tone.Monophonic.defaults = { 'portamento': 0 }; /** * Trigger the attack of the note optionally with a given velocity. * * * @param {Frequency} note The note to trigger. * @param {Time} [time=now] When the note should start. * @param {number} [velocity=1] velocity The velocity scaler * determines how "loud" the note * will be triggered. * @returns {Tone.Monophonic} this * @example * synth.triggerAttack("C4"); * @example * //trigger the note a half second from now at half velocity * synth.triggerAttack("C4", "+0.5", 0.5); */ Tone.Monophonic.prototype.triggerAttack = function (note, time, velocity) { time = this.toSeconds(time); this._triggerEnvelopeAttack(time, velocity); this.setNote(note, time); return this; }; /** * Trigger the release portion of the envelope * @param {Time} [time=now] If no time is given, the release happens immediatly * @returns {Tone.Monophonic} this * @example * synth.triggerRelease(); */ Tone.Monophonic.prototype.triggerRelease = function (time) { this._triggerEnvelopeRelease(time); return this; }; /** * override this method with the actual method * @abstract * @private */ Tone.Monophonic.prototype._triggerEnvelopeAttack = function () { }; /** * override this method with the actual method * @abstract * @private */ Tone.Monophonic.prototype._triggerEnvelopeRelease = function () { }; /** * Set the note at the given time. If no time is given, the note * will set immediately. * @param {Frequency} note The note to change to. * @param {Time} [time=now] The time when the note should be set. * @returns {Tone.Monophonic} this * @example * //change to F#6 in one quarter note from now. * synth.setNote("F#6", "+4n"); * @example * //change to Bb4 right now * synth.setNote("Bb4"); */ Tone.Monophonic.prototype.setNote = function (note, time) { time = this.toSeconds(time); if (this.portamento > 0) { var currentNote = this.frequency.value; this.frequency.setValueAtTime(currentNote, time); var portTime = this.toSeconds(this.portamento); this.frequency.exponentialRampToValueAtTime(note, time + portTime); } else { this.frequency.setValueAtTime(note, time); } return this; }; return Tone.Monophonic; }); Module(function (Tone) { /** * @class Tone.MonoSynth is composed of one oscillator, one filter, and two envelopes. * The amplitude of the Tone.Oscillator and the cutoff frequency of the * Tone.Filter are controlled by Tone.Envelopes. * <img src="https://docs.google.com/drawings/d/1gaY1DF9_Hzkodqf8JI1Cg2VZfwSElpFQfI94IQwad38/pub?w=924&h=240"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.MonoSynth({ * "oscillator" : { * "type" : "square" * }, * "envelope" : { * "attack" : 0.1 * } * }).toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.MonoSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.MonoSynth.defaults); Tone.Monophonic.call(this, options); /** * The oscillator. * @type {Tone.OmniOscillator} */ this.oscillator = new Tone.OmniOscillator(options.oscillator); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this.oscillator.frequency; /** * The detune control. * @type {Cents} * @signal */ this.detune = this.oscillator.detune; /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the oscillators to the output this.oscillator.chain(this.filter, this.envelope, this.output); //start the oscillators this.oscillator.start(); //connect the filter envelope this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'oscillator', 'frequency', 'detune', 'filter', 'filterEnvelope', 'envelope' ]); }; Tone.extend(Tone.MonoSynth, Tone.Monophonic); /** * @const * @static * @type {Object} */ Tone.MonoSynth.defaults = { 'frequency': 'C4', 'detune': 0, 'oscillator': { 'type': 'square' }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0.9, 'release': 1 }, 'filterEnvelope': { 'attack': 0.06, 'decay': 0.2, 'sustain': 0.5, 'release': 2, 'baseFrequency': 200, 'octaves': 7, 'exponent': 2 } }; /** * start the attack portion of the envelope * @param {Time} [time=now] the time the attack should start * @param {NormalRange} [velocity=1] the velocity of the note (0-1) * @returns {Tone.MonoSynth} this * @private */ Tone.MonoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * start the release portion of the envelope * @param {Time} [time=now] the time the release should start * @returns {Tone.MonoSynth} this * @private */ Tone.MonoSynth.prototype._triggerEnvelopeRelease = function (time) { this.envelope.triggerRelease(time); this.filterEnvelope.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.MonoSynth} this */ Tone.MonoSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'oscillator', 'frequency', 'detune', 'filter', 'filterEnvelope', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; this.filterEnvelope.dispose(); this.filterEnvelope = null; this.filter.dispose(); this.filter = null; this.frequency = null; this.detune = null; return this; }; return Tone.MonoSynth; }); Module(function (Tone) { /** * @class AMSynth uses the output of one Tone.MonoSynth to modulate the * amplitude of another Tone.MonoSynth. The harmonicity (the ratio between * the two signals) affects the timbre of the output signal the most. * Read more about Amplitude Modulation Synthesis on * [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1TQu8Ed4iFr1YTLKpB3U1_hur-UwBrh5gdBXc8BxfGKw/pub?w=1009&h=457"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.AMSynth().toMaster(); * synth.triggerAttackRelease("C4", "4n"); */ Tone.AMSynth = function (options) { options = this.defaultArg(options, Tone.AMSynth.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.MonoSynth} */ this.carrier = new Tone.MonoSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.MonoSynth} */ this.modulator = new Tone.MonoSynth(options.modulator); this.modulator.volume.value = -10; /** * The frequency. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * convert the -1,1 output to 0,1 * @type {Tone.AudioToGain} * @private */ this._modulationScale = new Tone.AudioToGain(); /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.modulator.chain(this._modulationScale, this._modulationNode.gain); this.carrier.chain(this._modulationNode, this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); }; Tone.extend(Tone.AMSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.AMSynth.defaults = { 'harmonicity': 3, 'carrier': { 'volume': -10, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0.01, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 20000, 'octaves': 0 }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 } }, 'modulator': { 'volume': -10, 'oscillator': { 'type': 'square' }, 'envelope': { 'attack': 2, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 4, 'decay': 0.2, 'sustain': 0.5, 'release': 0.5, 'baseFrequency': 20, 'octaves': 6 }, 'filter': { 'Q': 6, 'type': 'lowpass', 'rolloff': -24 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {NormalRange} [velocity=1] the velocity of the note * @private * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); this.carrier.filterEnvelope.triggerAttack(time); this.modulator.filterEnvelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @private * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.AMSynth} this */ Tone.AMSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationScale.dispose(); this._modulationScale = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.AMSynth; }); Module(function (Tone) { /** * @class Tone.DrumSynth makes kick and tom sounds using a single oscillator * with an amplitude envelope and frequency ramp. A Tone.Oscillator * is routed through a Tone.AmplitudeEnvelope to the output. The drum * quality of the sound comes from the frequency envelope applied * during during Tone.DrumSynth.triggerAttack(note). The frequency * envelope starts at <code>note * .octaves</code> and ramps to * <code>note</code> over the duration of <code>.pitchDecay</code>. * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.DrumSynth().toMaster(); * synth.triggerAttackRelease("C2", "8n"); */ Tone.DrumSynth = function (options) { options = this.defaultArg(options, Tone.DrumSynth.defaults); Tone.Instrument.call(this, options); /** * The oscillator. * @type {Tone.Oscillator} */ this.oscillator = new Tone.Oscillator(options.oscillator).start(); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); /** * The number of octaves the pitch envelope ramps. * @type {Positive} */ this.octaves = options.octaves; /** * The amount of time the frequency envelope takes. * @type {Time} */ this.pitchDecay = options.pitchDecay; this.oscillator.chain(this.envelope, this.output); this._readOnly([ 'oscillator', 'envelope' ]); }; Tone.extend(Tone.DrumSynth, Tone.Instrument); /** * @static * @type {Object} */ Tone.DrumSynth.defaults = { 'pitchDecay': 0.05, 'octaves': 10, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.001, 'decay': 0.4, 'sustain': 0.01, 'release': 1.4, 'attackCurve': 'exponential' } }; /** * Trigger the note at the given time with the given velocity. * * @param {Frequency} note the note * @param {Time} [time=now] the time, if not given is now * @param {number} [velocity=1] velocity defaults to 1 * @returns {Tone.DrumSynth} this * @example * kick.triggerAttack(60); */ Tone.DrumSynth.prototype.triggerAttack = function (note, time, velocity) { time = this.toSeconds(time); note = this.toFrequency(note); var maxNote = note * this.octaves; this.oscillator.frequency.setValueAtTime(maxNote, time); this.oscillator.frequency.exponentialRampToValueAtTime(note, time + this.toSeconds(this.pitchDecay)); this.envelope.triggerAttack(time, velocity); return this; }; /** * Trigger the release portion of the note. * * @param {Time} [time=now] the time the note will release * @returns {Tone.DrumSynth} this */ Tone.DrumSynth.prototype.triggerRelease = function (time) { this.envelope.triggerRelease(time); return this; }; /** * Clean up. * @returns {Tone.DrumSynth} this */ Tone.DrumSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'oscillator', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; return this; }; return Tone.DrumSynth; }); Module(function (Tone) { /** * @class Tone.DuoSynth is a monophonic synth composed of two * MonoSynths run in parallel with control over the * frequency ratio between the two voices and vibrato effect. * <img src="https://docs.google.com/drawings/d/1bL4GXvfRMMlqS7XyBm9CjL9KJPSUKbcdBNpqOlkFLxk/pub?w=1012&h=448"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var duoSynth = new Tone.DuoSynth().toMaster(); * duoSynth.triggerAttackRelease("C4", "2n"); */ Tone.DuoSynth = function (options) { options = this.defaultArg(options, Tone.DuoSynth.defaults); Tone.Monophonic.call(this, options); /** * the first voice * @type {Tone.MonoSynth} */ this.voice0 = new Tone.MonoSynth(options.voice0); this.voice0.volume.value = -10; /** * the second voice * @type {Tone.MonoSynth} */ this.voice1 = new Tone.MonoSynth(options.voice1); this.voice1.volume.value = -10; /** * The vibrato LFO. * @type {Tone.LFO} * @private */ this._vibrato = new Tone.LFO(options.vibratoRate, -50, 50); this._vibrato.start(); /** * the vibrato frequency * @type {Frequency} * @signal */ this.vibratoRate = this._vibrato.frequency; /** * the vibrato gain * @type {GainNode} * @private */ this._vibratoGain = this.context.createGain(); /** * The amount of vibrato * @type {Positive} * @signal */ this.vibratoAmount = new Tone.Param({ 'param': this._vibratoGain.gain, 'units': Tone.Type.Positive, 'value': options.vibratoAmount }); /** * the delay before the vibrato starts * @type {number} * @private */ this._vibratoDelay = this.toSeconds(options.vibratoDelay); /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * duoSynth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; //control the two voices frequency this.frequency.connect(this.voice0.frequency); this.frequency.chain(this.harmonicity, this.voice1.frequency); this._vibrato.connect(this._vibratoGain); this._vibratoGain.fan(this.voice0.detune, this.voice1.detune); this.voice0.connect(this.output); this.voice1.connect(this.output); this._readOnly([ 'voice0', 'voice1', 'frequency', 'vibratoAmount', 'vibratoRate' ]); }; Tone.extend(Tone.DuoSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.DuoSynth.defaults = { 'vibratoAmount': 0.5, 'vibratoRate': 5, 'vibratoDelay': 1, 'harmonicity': 1.5, 'voice0': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } }, 'voice1': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } } }; /** * start the attack portion of the envelopes * * @param {Time} [time=now] the time the attack should start * @param {NormalRange} [velocity=1] the velocity of the note (0-1) * @returns {Tone.DuoSynth} this * @private */ Tone.DuoSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { time = this.toSeconds(time); this.voice0.envelope.triggerAttack(time, velocity); this.voice1.envelope.triggerAttack(time, velocity); this.voice0.filterEnvelope.triggerAttack(time); this.voice1.filterEnvelope.triggerAttack(time); return this; }; /** * start the release portion of the envelopes * * @param {Time} [time=now] the time the release should start * @returns {Tone.DuoSynth} this * @private */ Tone.DuoSynth.prototype._triggerEnvelopeRelease = function (time) { this.voice0.triggerRelease(time); this.voice1.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.DuoSynth} this */ Tone.DuoSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'voice0', 'voice1', 'frequency', 'vibratoAmount', 'vibratoRate' ]); this.voice0.dispose(); this.voice0 = null; this.voice1.dispose(); this.voice1 = null; this.frequency.dispose(); this.frequency = null; this._vibrato.dispose(); this._vibrato = null; this._vibratoGain.disconnect(); this._vibratoGain = null; this.harmonicity.dispose(); this.harmonicity = null; this.vibratoAmount.dispose(); this.vibratoAmount = null; this.vibratoRate = null; return this; }; return Tone.DuoSynth; }); Module(function (Tone) { /** * @class FMSynth is composed of two Tone.MonoSynths where one Tone.MonoSynth modulates * the frequency of a second Tone.MonoSynth. A lot of spectral content * can be explored using the modulationIndex parameter. Read more about * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1h0PUDZXPgi4Ikx6bVT6oncrYPLluFKy7lj53puxj-DM/pub?w=902&h=462"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var fmSynth = new Tone.FMSynth().toMaster(); * fmSynth.triggerAttackRelease("C5", "4n"); */ Tone.FMSynth = function (options) { options = this.defaultArg(options, Tone.FMSynth.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.MonoSynth} */ this.carrier = new Tone.MonoSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.MonoSynth} */ this.modulator = new Tone.MonoSynth(options.modulator); this.modulator.volume.value = -10; /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * The modulation index which essentially the depth or amount of the modulation. It is the * ratio of the frequency of the modulating signal (mf) to the amplitude of the * modulating signal (ma) -- as in ma/mf. * @type {Positive} * @signal */ this.modulationIndex = new Tone.Multiply(options.modulationIndex); this.modulationIndex.units = Tone.Type.Positive; /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.frequency.chain(this.modulationIndex, this._modulationNode); this.modulator.connect(this._modulationNode.gain); this._modulationNode.gain.value = 0; this._modulationNode.connect(this.carrier.frequency); this.carrier.connect(this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); }; Tone.extend(Tone.FMSynth, Tone.Monophonic); /** * @static * @type {Object} */ Tone.FMSynth.defaults = { 'harmonicity': 3, 'modulationIndex': 10, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 200, 'octaves': 8 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 }, 'filterEnvelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5, 'baseFrequency': 600, 'octaves': 5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.FMSynth} this * @private */ Tone.FMSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); this.carrier.filterEnvelope.triggerAttack(time); this.modulator.filterEnvelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.FMSynth} this * @private */ Tone.FMSynth.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.FMSynth} this */ Tone.FMSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.modulationIndex.dispose(); this.modulationIndex = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.FMSynth; }); Module(function (Tone) { /** * @class Tone.Noise is a noise generator. It uses looped noise buffers to save on performance. * Tone.Noise supports the noise types: "pink", "white", and "brown". Read more about * colors of noise on [Wikipedia](https://en.wikipedia.org/wiki/Colors_of_noise). * * @constructor * @extends {Tone.Source} * @param {string} type the noise type (white|pink|brown) * @example * //initialize the noise and start * var noise = new Tone.Noise("pink").start(); * * //make an autofilter to shape the noise * var autoFilter = new Tone.AutoFilter({ * "frequency" : "8m", * "min" : 800, * "max" : 15000 * }).connect(Tone.Master); * * //connect the noise * noise.connect(autoFilter); * //start the autofilter LFO * autoFilter.start() */ Tone.Noise = function () { var options = this.optionsObject(arguments, ['type'], Tone.Noise.defaults); Tone.Source.call(this, options); /** * @private * @type {AudioBufferSourceNode} */ this._source = null; /** * the buffer * @private * @type {AudioBuffer} */ this._buffer = null; /** * The playback rate of the noise. Affects * the "frequency" of the noise. * @type {Positive} * @signal */ this._playbackRate = options.playbackRate; this.type = options.type; }; Tone.extend(Tone.Noise, Tone.Source); /** * the default parameters * * @static * @const * @type {Object} */ Tone.Noise.defaults = { 'type': 'white', 'playbackRate': 1 }; /** * The type of the noise. Can be "white", "brown", or "pink". * @memberOf Tone.Noise# * @type {string} * @name type * @example * noise.type = "white"; */ Object.defineProperty(Tone.Noise.prototype, 'type', { get: function () { if (this._buffer === _whiteNoise) { return 'white'; } else if (this._buffer === _brownNoise) { return 'brown'; } else if (this._buffer === _pinkNoise) { return 'pink'; } }, set: function (type) { if (this.type !== type) { switch (type) { case 'white': this._buffer = _whiteNoise; break; case 'pink': this._buffer = _pinkNoise; break; case 'brown': this._buffer = _brownNoise; break; default: throw new Error('invalid noise type: ' + type); } //if it's playing, stop and restart it if (this.state === Tone.State.Started) { var now = this.now() + this.blockTime; //remove the listener this._stop(now); this._start(now); } } } }); /** * The playback rate of the noise. Affects * the "frequency" of the noise. * @type {Positive} * @signal */ Object.defineProperty(Tone.Noise.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; if (this._source) { this._source.playbackRate.value = rate; } } }); /** * internal start method * * @param {Time} time * @private */ Tone.Noise.prototype._start = function (time) { this._source = this.context.createBufferSource(); this._source.buffer = this._buffer; this._source.loop = true; this._source.playbackRate.value = this._playbackRate; this._source.connect(this.output); this._source.start(this.toSeconds(time)); }; /** * internal stop method * * @param {Time} time * @private */ Tone.Noise.prototype._stop = function (time) { if (this._source) { this._source.stop(this.toSeconds(time)); } }; /** * Clean up. * @returns {Tone.Noise} this */ Tone.Noise.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._source !== null) { this._source.disconnect(); this._source = null; } this._buffer = null; return this; }; /////////////////////////////////////////////////////////////////////////// // THE BUFFERS // borrowed heavily from http://noisehack.com/generate-noise-web-audio-api/ /////////////////////////////////////////////////////////////////////////// /** * static noise buffers * * @static * @private * @type {AudioBuffer} */ var _pinkNoise = null, _brownNoise = null, _whiteNoise = null; Tone._initAudioContext(function (audioContext) { var sampleRate = audioContext.sampleRate; //four seconds per buffer var bufferLength = sampleRate * 4; //fill the buffers _pinkNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); var b0, b1, b2, b3, b4, b5, b6; b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0; for (var i = 0; i < bufferLength; i++) { var white = Math.random() * 2 - 1; b0 = 0.99886 * b0 + white * 0.0555179; b1 = 0.99332 * b1 + white * 0.0750759; b2 = 0.969 * b2 + white * 0.153852; b3 = 0.8665 * b3 + white * 0.3104856; b4 = 0.55 * b4 + white * 0.5329522; b5 = -0.7616 * b5 - white * 0.016898; channel[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362; channel[i] *= 0.11; // (roughly) compensate for gain b6 = white * 0.115926; } } return buffer; }(); _brownNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); var lastOut = 0; for (var i = 0; i < bufferLength; i++) { var white = Math.random() * 2 - 1; channel[i] = (lastOut + 0.02 * white) / 1.02; lastOut = channel[i]; channel[i] *= 3.5; // (roughly) compensate for gain } } return buffer; }(); _whiteNoise = function () { var buffer = audioContext.createBuffer(2, bufferLength, sampleRate); for (var channelNum = 0; channelNum < buffer.numberOfChannels; channelNum++) { var channel = buffer.getChannelData(channelNum); for (var i = 0; i < bufferLength; i++) { channel[i] = Math.random() * 2 - 1; } } return buffer; }(); }); return Tone.Noise; }); Module(function (Tone) { /** * @class Tone.NoiseSynth is composed of a noise generator (Tone.Noise), one filter (Tone.Filter), * and two envelopes (Tone.Envelop). One envelope controls the amplitude * of the noise and the other is controls the cutoff frequency of the filter. * <img src="https://docs.google.com/drawings/d/1rqzuX9rBlhT50MRvD2TKml9bnZhcZmzXF1rf_o7vdnE/pub?w=918&h=242"> * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] the options available for the synth * see defaults below * @example * var noiseSynth = new Tone.NoiseSynth().toMaster(); * noiseSynth.triggerAttackRelease("8n"); */ Tone.NoiseSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.NoiseSynth.defaults); Tone.Instrument.call(this, options); /** * The noise source. * @type {Tone.Noise} * @example * noiseSynth.set("noise.type", "brown"); */ this.noise = new Tone.Noise(); /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the noise to the output this.noise.chain(this.filter, this.envelope, this.output); //start the noise this.noise.start(); //connect the filter envelope this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'noise', 'filter', 'filterEnvelope', 'envelope' ]); }; Tone.extend(Tone.NoiseSynth, Tone.Instrument); /** * @const * @static * @type {Object} */ Tone.NoiseSynth.defaults = { 'noise': { 'type': 'white' }, 'filter': { 'Q': 6, 'type': 'highpass', 'rolloff': -24 }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0 }, 'filterEnvelope': { 'attack': 0.06, 'decay': 0.2, 'sustain': 0, 'release': 2, 'baseFrequency': 20, 'octaves': 5 } }; /** * Start the attack portion of the envelopes. Unlike other * instruments, Tone.NoiseSynth doesn't have a note. * @param {Time} [time=now] the time the attack should start * @param {number} [velocity=1] the velocity of the note (0-1) * @returns {Tone.NoiseSynth} this * @example * noiseSynth.triggerAttack(); */ Tone.NoiseSynth.prototype.triggerAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * Start the release portion of the envelopes. * @param {Time} [time=now] the time the release should start * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.triggerRelease = function (time) { this.envelope.triggerRelease(time); this.filterEnvelope.triggerRelease(time); return this; }; /** * Trigger the attack and then the release. * @param {Time} duration the duration of the note * @param {Time} [time=now] the time of the attack * @param {number} [velocity=1] the velocity * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.triggerAttackRelease = function (duration, time, velocity) { time = this.toSeconds(time); duration = this.toSeconds(duration); this.triggerAttack(time, velocity); this.triggerRelease(time + duration); return this; }; /** * Clean up. * @returns {Tone.NoiseSynth} this */ Tone.NoiseSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'noise', 'filter', 'filterEnvelope', 'envelope' ]); this.noise.dispose(); this.noise = null; this.envelope.dispose(); this.envelope = null; this.filterEnvelope.dispose(); this.filterEnvelope = null; this.filter.dispose(); this.filter = null; return this; }; return Tone.NoiseSynth; }); Module(function (Tone) { /** * @class Karplus-String string synthesis. Often out of tune. * Will change when the AudioWorkerNode is available across * browsers. * * @constructor * @extends {Tone.Instrument} * @param {Object} [options] see the defaults * @example * var plucky = new Tone.PluckSynth().toMaster(); * plucky.triggerAttack("C4"); */ Tone.PluckSynth = function (options) { options = this.defaultArg(options, Tone.PluckSynth.defaults); Tone.Instrument.call(this, options); /** * @type {Tone.Noise} * @private */ this._noise = new Tone.Noise('pink'); /** * The amount of noise at the attack. * Nominal range of [0.1, 20] * @type {number} */ this.attackNoise = 1; /** * the LFCF * @type {Tone.LowpassCombFilter} * @private */ this._lfcf = new Tone.LowpassCombFilter({ 'resonance': options.resonance, 'dampening': options.dampening }); /** * The resonance control. * @type {NormalRange} * @signal */ this.resonance = this._lfcf.resonance; /** * The dampening control. i.e. the lowpass filter frequency of the comb filter * @type {Frequency} * @signal */ this.dampening = this._lfcf.dampening; //connections this._noise.connect(this._lfcf); this._lfcf.connect(this.output); this._readOnly([ 'resonance', 'dampening' ]); }; Tone.extend(Tone.PluckSynth, Tone.Instrument); /** * @static * @const * @type {Object} */ Tone.PluckSynth.defaults = { 'attackNoise': 1, 'dampening': 4000, 'resonance': 0.9 }; /** * Trigger the note. * @param {Frequency} note The note to trigger. * @param {Time} [time=now] When the note should be triggered. * @returns {Tone.PluckSynth} this */ Tone.PluckSynth.prototype.triggerAttack = function (note, time) { note = this.toFrequency(note); time = this.toSeconds(time); var delayAmount = 1 / note; this._lfcf.delayTime.setValueAtTime(delayAmount, time); this._noise.start(time); this._noise.stop(time + delayAmount * this.attackNoise); return this; }; /** * Clean up. * @returns {Tone.PluckSynth} this */ Tone.PluckSynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._noise.dispose(); this._lfcf.dispose(); this._noise = null; this._lfcf = null; this._writable([ 'resonance', 'dampening' ]); this.dampening = null; this.resonance = null; return this; }; return Tone.PluckSynth; }); Module(function (Tone) { /** * @class Tone.PolySynth handles voice creation and allocation for any * instruments passed in as the second paramter. PolySynth is * not a synthesizer by itself, it merely manages voices of * one of the other types of synths, allowing any of the * monophonic synthesizers to be polyphonic. * * @constructor * @extends {Tone.Instrument} * @param {number|Object} [polyphony=4] The number of voices to create * @param {function} [voice=Tone.MonoSynth] The constructor of the voices * uses Tone.MonoSynth by default. * @example * //a polysynth composed of 6 Voices of MonoSynth * var synth = new Tone.PolySynth(6, Tone.MonoSynth).toMaster(); * //set the attributes using the set interface * synth.set("detune", -1200); * //play a chord * synth.triggerAttackRelease(["C4", "E4", "A4"], "4n"); */ Tone.PolySynth = function () { Tone.Instrument.call(this); var options = this.optionsObject(arguments, [ 'polyphony', 'voice' ], Tone.PolySynth.defaults); /** * the array of voices * @type {Array} */ this.voices = new Array(options.polyphony); /** * If there are no more voices available, * should an active voice be stolen to play the new note? * @type {Boolean} */ this.stealVoices = true; /** * the queue of free voices * @private * @type {Array} */ this._freeVoices = []; /** * keeps track of which notes are down * @private * @type {Object} */ this._activeVoices = {}; //create the voices for (var i = 0; i < options.polyphony; i++) { var v = new options.voice(arguments[2], arguments[3]); this.voices[i] = v; v.connect(this.output); } //make a copy of the voices this._freeVoices = this.voices.slice(0); //get the prototypes and properties }; Tone.extend(Tone.PolySynth, Tone.Instrument); /** * the defaults * @const * @static * @type {Object} */ Tone.PolySynth.defaults = { 'polyphony': 4, 'voice': Tone.MonoSynth }; /** * Trigger the attack portion of the note * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} [time=now] The start time of the note. * @param {number} [velocity=1] The velocity of the note. * @returns {Tone.PolySynth} this * @example * //trigger a chord immediately with a velocity of 0.2 * poly.triggerAttack(["Ab3", "C4", "F5"], undefined, 0.2); */ Tone.PolySynth.prototype.triggerAttack = function (notes, time, velocity) { if (!Array.isArray(notes)) { notes = [notes]; } for (var i = 0; i < notes.length; i++) { var val = notes[i]; var stringified = JSON.stringify(val); //retrigger the same note if possible if (this._activeVoices.hasOwnProperty(stringified)) { this._activeVoices[stringified].triggerAttack(val, time, velocity); } else if (this._freeVoices.length > 0) { var voice = this._freeVoices.shift(); voice.triggerAttack(val, time, velocity); this._activeVoices[stringified] = voice; } else if (this.stealVoices) { //steal a voice //take the first voice for (var voiceName in this._activeVoices) { this._activeVoices[voiceName].triggerAttack(val, time, velocity); break; } } } return this; }; /** * Trigger the attack and release after the specified duration * * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} duration the duration of the note * @param {Time} [time=now] if no time is given, defaults to now * @param {number} [velocity=1] the velocity of the attack (0-1) * @returns {Tone.PolySynth} this * @example * //trigger a chord for a duration of a half note * poly.triggerAttackRelease(["Eb3", "G4", "C5"], "2n"); */ Tone.PolySynth.prototype.triggerAttackRelease = function (notes, duration, time, velocity) { time = this.toSeconds(time); this.triggerAttack(notes, time, velocity); this.triggerRelease(notes, time + this.toSeconds(duration)); return this; }; /** * Trigger the release of the note. Unlike monophonic instruments, * a note (or array of notes) needs to be passed in as the first argument. * @param {Frequency|Array} notes The notes to play. Accepts a single * Frequency or an array of frequencies. * @param {Time} [time=now] When the release will be triggered. * @returns {Tone.PolySynth} this * @example * poly.triggerRelease(["Ab3", "C4", "F5"], "+2n"); */ Tone.PolySynth.prototype.triggerRelease = function (notes, time) { if (!Array.isArray(notes)) { notes = [notes]; } for (var i = 0; i < notes.length; i++) { //get the voice var stringified = JSON.stringify(notes[i]); var voice = this._activeVoices[stringified]; if (voice) { voice.triggerRelease(time); this._freeVoices.push(voice); delete this._activeVoices[stringified]; voice = null; } } return this; }; /** * Set a member/attribute of the voices. * @param {Object|string} params * @param {number=} value * @param {Time=} rampTime * @returns {Tone.PolySynth} this * @example * poly.set({ * "filter" : { * "type" : "highpass" * }, * "envelope" : { * "attack" : 0.25 * } * }); */ Tone.PolySynth.prototype.set = function (params, value, rampTime) { for (var i = 0; i < this.voices.length; i++) { this.voices[i].set(params, value, rampTime); } return this; }; /** * Get the synth's attributes. Given no arguments get * will return all available object properties and their corresponding * values. Pass in a single attribute to retrieve or an array * of attributes. The attribute strings can also include a "." * to access deeper properties. * @param {Array=} params the parameters to get, otherwise will return * all available. */ Tone.PolySynth.prototype.get = function (params) { return this.voices[0].get(params); }; /** * Trigger the release portion of all the currently active voices. * @param {Time} [time=now] When the notes should be released. * @return {Tone.PolySynth} this */ Tone.PolySynth.prototype.releaseAll = function (time) { for (var i = 0; i < this.voices.length; i++) { this.voices[i].triggerRelease(time); } return this; }; /** * Clean up. * @returns {Tone.PolySynth} this */ Tone.PolySynth.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); for (var i = 0; i < this.voices.length; i++) { this.voices[i].dispose(); this.voices[i] = null; } this.voices = null; this._activeVoices = null; this._freeVoices = null; return this; }; return Tone.PolySynth; }); Module(function (Tone) { /** * @class Tone.Player is an audio file player with start, loop, and stop functions. * * @constructor * @extends {Tone.Source} * @param {string|AudioBuffer} url Either the AudioBuffer or the url from * which to load the AudioBuffer * @param {function=} onload The function to invoke when the buffer is loaded. * Recommended to use Tone.Buffer.onload instead. * @example * var player = new Tone.Player("./path/to/sample.mp3").toMaster(); * Tone.Buffer.onload = function(){ * player.start(); * } */ Tone.Player = function (url) { var options; if (url instanceof Tone.Buffer) { url = url.get(); options = Tone.Player.defaults; } else { options = this.optionsObject(arguments, [ 'url', 'onload' ], Tone.Player.defaults); } Tone.Source.call(this, options); /** * @private * @type {AudioBufferSourceNode} */ this._source = null; /** * If the file should play as soon * as the buffer is loaded. * @type {boolean} * @example * //will play as soon as it's loaded * var player = new Tone.Player({ * "url" : "./path/to/sample.mp3", * "autostart" : true, * }).toMaster(); */ this.autostart = options.autostart; /** * the buffer * @private * @type {Tone.Buffer} */ this._buffer = new Tone.Buffer({ 'url': options.url, 'onload': this._onload.bind(this, options.onload), 'reverse': options.reverse }); if (url instanceof AudioBuffer) { this._buffer.set(url); } /** * if the buffer should loop once it's over * @type {boolean} * @private */ this._loop = options.loop; /** * if 'loop' is true, the loop will start at this position * @type {Time} * @private */ this._loopStart = options.loopStart; /** * if 'loop' is true, the loop will end at this position * @type {Time} * @private */ this._loopEnd = options.loopEnd; /** * the playback rate * @private * @type {number} */ this._playbackRate = options.playbackRate; /** * Enabling retrigger will allow a player to be restarted * before the the previous 'start' is done playing. Otherwise, * successive calls to Tone.Player.start will only start * the sample if it had played all the way through. * @type {boolean} */ this.retrigger = options.retrigger; }; Tone.extend(Tone.Player, Tone.Source); /** * the default parameters * @static * @const * @type {Object} */ Tone.Player.defaults = { 'onload': Tone.noOp, 'playbackRate': 1, 'loop': false, 'autostart': false, 'loopStart': 0, 'loopEnd': 0, 'retrigger': false, 'reverse': false }; /** * Load the audio file as an audio buffer. * Decodes the audio asynchronously and invokes * the callback once the audio buffer loads. * Note: this does not need to be called if a url * was passed in to the constructor. Only use this * if you want to manually load a new url. * @param {string} url The url of the buffer to load. * Filetype support depends on the * browser. * @param {function=} callback The function to invoke once * the sample is loaded. * @returns {Tone.Player} this */ Tone.Player.prototype.load = function (url, callback) { this._buffer.load(url, this._onload.bind(this, callback)); return this; }; /** * Internal callback when the buffer is loaded. * @private */ Tone.Player.prototype._onload = function (callback) { callback(this); if (this.autostart) { this.start(); } }; /** * play the buffer between the desired positions * * @private * @param {Time} [startTime=now] when the player should start. * @param {Time} [offset=0] the offset from the beginning of the sample * to start at. * @param {Time=} duration how long the sample should play. If no duration * is given, it will default to the full length * of the sample (minus any offset) * @returns {Tone.Player} this */ Tone.Player.prototype._start = function (startTime, offset, duration) { if (this._buffer.loaded) { //if it's a loop the default offset is the loopstart point if (this._loop) { offset = this.defaultArg(offset, this._loopStart); } else { //otherwise the default offset is 0 offset = this.defaultArg(offset, 0); } offset = this.toSeconds(offset); duration = this.defaultArg(duration, this._buffer.duration - offset); //the values in seconds startTime = this.toSeconds(startTime); duration = this.toSeconds(duration); //make the source this._source = this.context.createBufferSource(); this._source.buffer = this._buffer.get(); //set the looping properties if (this._loop) { this._source.loop = this._loop; this._source.loopStart = this.toSeconds(this._loopStart); this._source.loopEnd = this.toSeconds(this._loopEnd); } else { //if it's not looping, set the state change at the end of the sample this._state.setStateAtTime(Tone.State.Stopped, startTime + duration); } //and other properties this._source.playbackRate.value = this._playbackRate; this._source.connect(this.output); //start it if (this._loop) { this._source.start(startTime, offset); } else { this._source.start(startTime, offset, duration); } } else { throw Error('tried to start Player before the buffer was loaded'); } return this; }; /** * Stop playback. * @private * @param {Time} [time=now] * @returns {Tone.Player} this */ Tone.Player.prototype._stop = function (time) { if (this._source) { this._source.stop(this.toSeconds(time)); this._source = null; } return this; }; /** * Set the loop start and end. Will only loop if loop is * set to true. * @param {Time} loopStart The loop end time * @param {Time} loopEnd The loop end time * @returns {Tone.Player} this * @example * //loop 0.1 seconds of the file. * player.setLoopPoints(0.2, 0.3); * player.loop = true; */ Tone.Player.prototype.setLoopPoints = function (loopStart, loopEnd) { this.loopStart = loopStart; this.loopEnd = loopEnd; return this; }; /** * If loop is true, the loop will start at this position. * @memberOf Tone.Player# * @type {Time} * @name loopStart */ Object.defineProperty(Tone.Player.prototype, 'loopStart', { get: function () { return this._loopStart; }, set: function (loopStart) { this._loopStart = loopStart; if (this._source) { this._source.loopStart = this.toSeconds(loopStart); } } }); /** * If loop is true, the loop will end at this position. * @memberOf Tone.Player# * @type {Time} * @name loopEnd */ Object.defineProperty(Tone.Player.prototype, 'loopEnd', { get: function () { return this._loopEnd; }, set: function (loopEnd) { this._loopEnd = loopEnd; if (this._source) { this._source.loopEnd = this.toSeconds(loopEnd); } } }); /** * The audio buffer belonging to the player. * @memberOf Tone.Player# * @type {Tone.Buffer} * @name buffer */ Object.defineProperty(Tone.Player.prototype, 'buffer', { get: function () { return this._buffer; }, set: function (buffer) { this._buffer.set(buffer); } }); /** * If the buffer should loop once it's over. * @memberOf Tone.Player# * @type {boolean} * @name loop */ Object.defineProperty(Tone.Player.prototype, 'loop', { get: function () { return this._loop; }, set: function (loop) { this._loop = loop; if (this._source) { this._source.loop = loop; } } }); /** * The playback speed. 1 is normal speed. This is not a signal because * Safari and iOS currently don't support playbackRate as a signal. * @memberOf Tone.Player# * @type {number} * @name playbackRate */ Object.defineProperty(Tone.Player.prototype, 'playbackRate', { get: function () { return this._playbackRate; }, set: function (rate) { this._playbackRate = rate; if (this._source) { this._source.playbackRate.value = rate; } } }); /** * The direction the buffer should play in * @memberOf Tone.Player# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Player.prototype, 'reverse', { get: function () { return this._buffer.reverse; }, set: function (rev) { this._buffer.reverse = rev; } }); /** * Dispose and disconnect. * @return {Tone.Player} this */ Tone.Player.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); if (this._source !== null) { this._source.disconnect(); this._source = null; } this._buffer.dispose(); this._buffer = null; return this; }; return Tone.Player; }); Module(function (Tone) { /** * @class A sampler instrument which plays an audio buffer * through an amplitude envelope and a filter envelope. The sampler takes * an Object in the constructor which maps a sample name to the URL * of the sample. Nested Objects will be flattened and can be accessed using * a dot notation (see the example). * <img src="https://docs.google.com/drawings/d/1UK-gi_hxzKDz9Dh4ByyOptuagMOQxv52WxN12HwvtW8/pub?w=931&h=241"> * * @constructor * @extends {Tone.Instrument} * @param {Object|string} urls the urls of the audio file * @param {Object} [options] the options object for the synth * @example * var sampler = new Sampler({ * A : { * 1 : "./audio/casio/A1.mp3", * 2 : "./audio/casio/A2.mp3", * }, * "B.1" : "./audio/casio/B1.mp3", * }).toMaster(); * * //listen for when all the samples have loaded * Tone.Buffer.onload = function(){ * sampler.triggerAttack("A.1", time, velocity); * }; */ Tone.Sampler = function (urls, options) { options = this.defaultArg(options, Tone.Sampler.defaults); Tone.Instrument.call(this, options); /** * The sample player. * @type {Tone.Player} */ this.player = new Tone.Player(options.player); this.player.retrigger = true; /** * the buffers * @type {Object} * @private */ this._buffers = {}; /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); /** * The filter envelope. * @type {Tone.FrequencyEnvelope} */ this.filterEnvelope = new Tone.FrequencyEnvelope(options.filterEnvelope); /** * The name of the current sample. * @type {string} * @private */ this._sample = options.sample; /** * the private reference to the pitch * @type {number} * @private */ this._pitch = options.pitch; /** * The filter. * @type {Tone.Filter} */ this.filter = new Tone.Filter(options.filter); //connections / setup this._loadBuffers(urls); this.pitch = options.pitch; this.player.chain(this.filter, this.envelope, this.output); this.filterEnvelope.connect(this.filter.frequency); this._readOnly([ 'player', 'filterEnvelope', 'envelope', 'filter' ]); }; Tone.extend(Tone.Sampler, Tone.Instrument); /** * the default parameters * @static */ Tone.Sampler.defaults = { 'sample': 0, 'pitch': 0, 'player': { 'loop': false }, 'envelope': { 'attack': 0.001, 'decay': 0, 'sustain': 1, 'release': 0.1 }, 'filterEnvelope': { 'attack': 0.001, 'decay': 0.001, 'sustain': 1, 'release': 0.5, 'baseFrequency': 20, 'octaves': 10 }, 'filter': { 'type': 'lowpass' } }; /** * load the buffers * @param {Object} urls the urls * @private */ Tone.Sampler.prototype._loadBuffers = function (urls) { if (this.isString(urls)) { this._buffers['0'] = new Tone.Buffer(urls, function () { this.sample = '0'; }.bind(this)); } else { urls = this._flattenUrls(urls); for (var buffName in urls) { this._sample = buffName; var urlString = urls[buffName]; this._buffers[buffName] = new Tone.Buffer(urlString); } } }; /** * Flatten an object into a single depth object. * thanks to https://gist.github.com/penguinboy/762197 * @param {Object} ob * @return {Object} * @private */ Tone.Sampler.prototype._flattenUrls = function (ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if (this.isObject(ob[i])) { var flatObject = this._flattenUrls(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; }; /** * Start the sample and simultaneously trigger the envelopes. * @param {string=} sample The name of the sample to trigger, defaults to * the last sample used. * @param {Time} [time=now] The time when the sample should start * @param {number} [velocity=1] The velocity of the note * @returns {Tone.Sampler} this * @example * sampler.triggerAttack("B.1"); */ Tone.Sampler.prototype.triggerAttack = function (name, time, velocity) { time = this.toSeconds(time); if (name) { this.sample = name; } this.player.start(time); this.envelope.triggerAttack(time, velocity); this.filterEnvelope.triggerAttack(time); return this; }; /** * Start the release portion of the sample. Will stop the sample once the * envelope has fully released. * * @param {Time} [time=now] The time when the note should release * @returns {Tone.Sampler} this * @example * sampler.triggerRelease(); */ Tone.Sampler.prototype.triggerRelease = function (time) { time = this.toSeconds(time); this.filterEnvelope.triggerRelease(time); this.envelope.triggerRelease(time); this.player.stop(this.toSeconds(this.envelope.release) + time); return this; }; /** * The name of the sample to trigger. * @memberOf Tone.Sampler# * @type {number|string} * @name sample * @example * //set the sample to "A.2" for next time the sample is triggered * sampler.sample = "A.2"; */ Object.defineProperty(Tone.Sampler.prototype, 'sample', { get: function () { return this._sample; }, set: function (name) { if (this._buffers.hasOwnProperty(name)) { this._sample = name; this.player.buffer = this._buffers[name]; } else { throw new Error('Sampler does not have a sample named ' + name); } } }); /** * The direction the buffer should play in * @memberOf Tone.Sampler# * @type {boolean} * @name reverse */ Object.defineProperty(Tone.Sampler.prototype, 'reverse', { get: function () { for (var i in this._buffers) { return this._buffers[i].reverse; } }, set: function (rev) { for (var i in this._buffers) { this._buffers[i].reverse = rev; } } }); /** * Repitch the sampled note by some interval (measured * in semi-tones). * @memberOf Tone.Sampler# * @type {Interval} * @name pitch * @example * sampler.pitch = -12; //down one octave * sampler.pitch = 7; //up a fifth */ Object.defineProperty(Tone.Sampler.prototype, 'pitch', { get: function () { return this._pitch; }, set: function (interval) { this._pitch = interval; this.player.playbackRate = this.intervalToFrequencyRatio(interval); } }); /** * Clean up. * @returns {Tone.Sampler} this */ Tone.Sampler.prototype.dispose = function () { Tone.Instrument.prototype.dispose.call(this); this._writable([ 'player', 'filterEnvelope', 'envelope', 'filter' ]); this.player.dispose(); this.filterEnvelope.dispose(); this.envelope.dispose(); this.filter.dispose(); this.player = null; this.filterEnvelope = null; this.envelope = null; this.filter = null; for (var sample in this._buffers) { this._buffers[sample].dispose(); this._buffers[sample] = null; } this._buffers = null; return this; }; return Tone.Sampler; }); Module(function (Tone) { /** * @class Tone.SimpleSynth is composed simply of a Tone.OmniOscillator * routed through a Tone.AmplitudeEnvelope. * <img src="https://docs.google.com/drawings/d/1-1_0YW2Z1J2EPI36P8fNCMcZG7N1w1GZluPs4og4evo/pub?w=1163&h=231"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.SimpleSynth().toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleSynth = function (options) { //get the defaults options = this.defaultArg(options, Tone.SimpleSynth.defaults); Tone.Monophonic.call(this, options); /** * The oscillator. * @type {Tone.OmniOscillator} */ this.oscillator = new Tone.OmniOscillator(options.oscillator); /** * The frequency control. * @type {Frequency} * @signal */ this.frequency = this.oscillator.frequency; /** * The detune control. * @type {Cents} * @signal */ this.detune = this.oscillator.detune; /** * The amplitude envelope. * @type {Tone.AmplitudeEnvelope} */ this.envelope = new Tone.AmplitudeEnvelope(options.envelope); //connect the oscillators to the output this.oscillator.chain(this.envelope, this.output); //start the oscillators this.oscillator.start(); this._readOnly([ 'oscillator', 'frequency', 'detune', 'envelope' ]); }; Tone.extend(Tone.SimpleSynth, Tone.Monophonic); /** * @const * @static * @type {Object} */ Tone.SimpleSynth.defaults = { 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.005, 'decay': 0.1, 'sustain': 0.3, 'release': 1 } }; /** * start the attack portion of the envelope * @param {Time} [time=now] the time the attack should start * @param {number} [velocity=1] the velocity of the note (0-1) * @returns {Tone.SimpleSynth} this * @private */ Tone.SimpleSynth.prototype._triggerEnvelopeAttack = function (time, velocity) { //the envelopes this.envelope.triggerAttack(time, velocity); return this; }; /** * start the release portion of the envelope * @param {Time} [time=now] the time the release should start * @returns {Tone.SimpleSynth} this * @private */ Tone.SimpleSynth.prototype._triggerEnvelopeRelease = function (time) { this.envelope.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleSynth} this */ Tone.SimpleSynth.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'oscillator', 'frequency', 'detune', 'envelope' ]); this.oscillator.dispose(); this.oscillator = null; this.envelope.dispose(); this.envelope = null; this.frequency = null; this.detune = null; return this; }; return Tone.SimpleSynth; }); Module(function (Tone) { /** * @class AMSynth uses the output of one Tone.SimpleSynth to modulate the * amplitude of another Tone.SimpleSynth. The harmonicity (the ratio between * the two signals) affects the timbre of the output signal the most. * Read more about Amplitude Modulation Synthesis on [SoundOnSound](http://www.soundonsound.com/sos/mar00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1p_os_As-N1bpnK8u55gXlgVw3U7BfquLX0Wj57kSZXY/pub?w=1009&h=457"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var synth = new Tone.SimpleAM().toMaster(); * synth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleAM = function (options) { options = this.defaultArg(options, Tone.SimpleAM.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.SimpleSynth} */ this.carrier = new Tone.SimpleSynth(options.carrier); /** * The modulator voice. * @type {Tone.SimpleSynth} */ this.modulator = new Tone.SimpleSynth(options.modulator); /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * The ratio between the carrier and the modulator frequencies. A value of 1 * makes both voices in unison, a value of 0.5 puts the modulator an octave below * the carrier. * @type {Positive} * @signal * @example * //set the modulator an octave above the carrier frequency * simpleAM.harmonicity.value = 2; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * convert the -1,1 output to 0,1 * @type {Tone.AudioToGain} * @private */ this._modulationScale = new Tone.AudioToGain(); /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.modulator.chain(this._modulationScale, this._modulationNode.gain); this.carrier.chain(this._modulationNode, this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); }; Tone.extend(Tone.SimpleAM, Tone.Monophonic); /** * @static * @type {Object} */ Tone.SimpleAM.defaults = { 'harmonicity': 3, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0.01, 'sustain': 1, 'release': 0.5 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.5, 'decay': 0.1, 'sustain': 1, 'release': 0.5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.SimpleAM} this * @private */ Tone.SimpleAM.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.SimpleAM} this * @private */ Tone.SimpleAM.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleAM} this */ Tone.SimpleAM.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationScale.dispose(); this._modulationScale = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.SimpleAM; }); Module(function (Tone) { /** * @class SimpleFM is composed of two Tone.SimpleSynths where one Tone.SimpleSynth modulates * the frequency of a second Tone.SimpleSynth. A lot of spectral content * can be explored using the Tone.FMSynth.modulationIndex parameter. Read more about * frequency modulation synthesis on [SoundOnSound](http://www.soundonsound.com/sos/apr00/articles/synthsecrets.htm). * <img src="https://docs.google.com/drawings/d/1hSU25lLjDk_WJ59DSitQm6iCRpcMWVEAYqBjwmqtRVw/pub?w=902&h=462"> * * @constructor * @extends {Tone.Monophonic} * @param {Object} [options] the options available for the synth * see defaults below * @example * var fmSynth = new Tone.SimpleFM().toMaster(); * fmSynth.triggerAttackRelease("C4", "8n"); */ Tone.SimpleFM = function (options) { options = this.defaultArg(options, Tone.SimpleFM.defaults); Tone.Monophonic.call(this, options); /** * The carrier voice. * @type {Tone.SimpleSynth} */ this.carrier = new Tone.SimpleSynth(options.carrier); this.carrier.volume.value = -10; /** * The modulator voice. * @type {Tone.SimpleSynth} */ this.modulator = new Tone.SimpleSynth(options.modulator); this.modulator.volume.value = -10; /** * the frequency control * @type {Frequency} * @signal */ this.frequency = new Tone.Signal(440, Tone.Type.Frequency); /** * Harmonicity is the ratio between the two voices. A harmonicity of * 1 is no change. Harmonicity = 2 means a change of an octave. * @type {Positive} * @signal * @example * //pitch voice1 an octave below voice0 * synth.harmonicity.value = 0.5; */ this.harmonicity = new Tone.Multiply(options.harmonicity); this.harmonicity.units = Tone.Type.Positive; /** * The modulation index which is in essence the depth or amount of the modulation. In other terms it is the * ratio of the frequency of the modulating signal (mf) to the amplitude of the * modulating signal (ma) -- as in ma/mf. * @type {Positive} * @signal */ this.modulationIndex = new Tone.Multiply(options.modulationIndex); this.modulationIndex.units = Tone.Type.Positive; /** * the node where the modulation happens * @type {GainNode} * @private */ this._modulationNode = this.context.createGain(); //control the two voices frequency this.frequency.connect(this.carrier.frequency); this.frequency.chain(this.harmonicity, this.modulator.frequency); this.frequency.chain(this.modulationIndex, this._modulationNode); this.modulator.connect(this._modulationNode.gain); this._modulationNode.gain.value = 0; this._modulationNode.connect(this.carrier.frequency); this.carrier.connect(this.output); this._readOnly([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); ; }; Tone.extend(Tone.SimpleFM, Tone.Monophonic); /** * @static * @type {Object} */ Tone.SimpleFM.defaults = { 'harmonicity': 3, 'modulationIndex': 10, 'carrier': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'sine' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } }, 'modulator': { 'volume': -10, 'portamento': 0, 'oscillator': { 'type': 'triangle' }, 'envelope': { 'attack': 0.01, 'decay': 0, 'sustain': 1, 'release': 0.5 } } }; /** * trigger the attack portion of the note * * @param {Time} [time=now] the time the note will occur * @param {number} [velocity=1] the velocity of the note * @returns {Tone.SimpleFM} this * @private */ Tone.SimpleFM.prototype._triggerEnvelopeAttack = function (time, velocity) { //the port glide time = this.toSeconds(time); //the envelopes this.carrier.envelope.triggerAttack(time, velocity); this.modulator.envelope.triggerAttack(time); return this; }; /** * trigger the release portion of the note * * @param {Time} [time=now] the time the note will release * @returns {Tone.SimpleFM} this * @private */ Tone.SimpleFM.prototype._triggerEnvelopeRelease = function (time) { this.carrier.triggerRelease(time); this.modulator.triggerRelease(time); return this; }; /** * clean up * @returns {Tone.SimpleFM} this */ Tone.SimpleFM.prototype.dispose = function () { Tone.Monophonic.prototype.dispose.call(this); this._writable([ 'carrier', 'modulator', 'frequency', 'harmonicity', 'modulationIndex' ]); this.carrier.dispose(); this.carrier = null; this.modulator.dispose(); this.modulator = null; this.frequency.dispose(); this.frequency = null; this.modulationIndex.dispose(); this.modulationIndex = null; this.harmonicity.dispose(); this.harmonicity = null; this._modulationNode.disconnect(); this._modulationNode = null; return this; }; return Tone.SimpleFM; }); Module(function (Tone) { //polyfill for getUserMedia navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; /** * @class Tone.ExternalInput is a WebRTC Audio Input. Check * [Media Stream API Support](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_API) * to see which browsers are supported. As of * writing this, Chrome, Firefox, and Opera * support Media Stream. Chrome allows enumeration * of the sources, and access to device name over a * secure (HTTPS) connection. See [https://simpl.info](https://simpl.info/getusermedia/sources/index.html) * vs [http://simple.info](https://simpl.info/getusermedia/sources/index.html) * on a Chrome browser for the difference. * * @constructor * @extends {Tone.Source} * @param {number} [inputNum=0] If multiple inputs are present, select the input number. Chrome only. * @example * //select the third input * var motu = new Tone.ExternalInput(3); * * //opening the input asks the user to activate their mic * motu.open(function(){ * //opening is activates the microphone * //starting lets audio through * motu.start(10); * }); */ Tone.ExternalInput = function () { var options = this.optionsObject(arguments, ['inputNum'], Tone.ExternalInput.defaults); Tone.Source.call(this, options); /** * The MediaStreamNode * @type {MediaStreamAudioSourceNode} * @private */ this._mediaStream = null; /** * The media stream created by getUserMedia. * @type {LocalMediaStream} * @private */ this._stream = null; /** * The constraints argument for getUserMedia * @type {Object} * @private */ this._constraints = { 'audio': { mandatory: { "googEchoCancellation": "false", "googAutoGainControl": "false", "googNoiseSuppression": "false", "googHighpassFilter": "false" }, "optional": [] } }; /** * The input source position in Tone.ExternalInput.sources. * Set before ExternalInput.open(). * @type {Number} * @private */ this._inputNum = options.inputNum; /** * Gates the input signal for start/stop. * Initially closed. * @type {GainNode} * @private */ this._gate = new Tone.Gain(0).connect(this.output); }; Tone.extend(Tone.ExternalInput, Tone.Source); /** * the default parameters * @type {Object} */ Tone.ExternalInput.defaults = { 'inputNum': 0 }; /** * wrapper for getUserMedia function * @param {function} callback * @private */ Tone.ExternalInput.prototype._getUserMedia = function (callback) { if (!Tone.ExternalInput.supported) { throw new Error('browser does not support \'getUserMedia\''); } if (Tone.ExternalInput.sources[this._inputNum]) { this._constraints = { audio: { mandatory: { "googEchoCancellation": "false", "googAutoGainControl": "false", "googNoiseSuppression": "false", "googHighpassFilter": "false" }, optional: [{ sourceId: Tone.ExternalInput.sources[this._inputNum].id }] } }; } navigator.getUserMedia(this._constraints, function (stream) { this._onStream(stream); callback(); }.bind(this), function (err) { callback(err); }); }; /** * called when the stream is successfully setup * @param {LocalMediaStream} stream * @private */ Tone.ExternalInput.prototype._onStream = function (stream) { if (!this.isFunction(this.context.createMediaStreamSource)) { throw new Error('browser does not support the \'MediaStreamSourceNode\''); } //can only start a new source if the previous one is closed if (!this._stream) { this._stream = stream; //Wrap a MediaStreamSourceNode around the live input stream. this._mediaStream = this.context.createMediaStreamSource(stream); //Connect the MediaStreamSourceNode to a gate gain node this._mediaStream.connect(this._gate); } }; /** * Open the media stream * @param {function=} callback The callback function to * execute when the stream is open * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.open = function (callback) { callback = this.defaultArg(callback, Tone.noOp); Tone.ExternalInput.getSources(function () { this._getUserMedia(callback); }.bind(this)); return this; }; /** * Close the media stream * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.close = function () { if (this._stream) { var track = this._stream.getTracks()[this._inputNum]; if (!this.isUndef(track)) { track.stop(); } this._stream = null; } return this; }; /** * Start the stream * @private */ Tone.ExternalInput.prototype._start = function (time) { time = this.toSeconds(time); this._gate.gain.setValueAtTime(1, time); return this; }; /** * Stops the stream. * @private */ Tone.ExternalInput.prototype._stop = function (time) { time = this.toSeconds(time); this._gate.gain.setValueAtTime(0, time); return this; }; /** * Clean up. * @return {Tone.ExternalInput} this */ Tone.ExternalInput.prototype.dispose = function () { Tone.Source.prototype.dispose.call(this); this.close(); if (this._mediaStream) { this._mediaStream.disconnect(); this._mediaStream = null; } this._constraints = null; this._gate.dispose(); this._gate = null; return this; }; /////////////////////////////////////////////////////////////////////////// // STATIC METHODS /////////////////////////////////////////////////////////////////////////// /** * The array of available sources, different depending on whether connection is secure * @type {Array} * @static */ Tone.ExternalInput.sources = []; /** * indicates whether browser supports MediaStreamTrack.getSources (i.e. Chrome vs Firefox) * @type {Boolean} * @private */ Tone.ExternalInput._canGetSources = !Tone.prototype.isUndef(window.MediaStreamTrack) && Tone.prototype.isFunction(MediaStreamTrack.getSources); /** * If getUserMedia is supported by the browser. * @type {Boolean} * @memberOf Tone.ExternalInput# * @name supported * @static * @readOnly */ Object.defineProperty(Tone.ExternalInput, 'supported', { get: function () { return Tone.prototype.isFunction(navigator.getUserMedia); } }); /** * Populates the source list. Invokes the callback with an array of * possible audio sources. * @param {function=} callback Callback to be executed after populating list * @return {Tone.ExternalInput} this * @static * @example * var soundflower = new Tone.ExternalInput(); * Tone.ExternalInput.getSources(selectSoundflower); * * function selectSoundflower(sources){ * for(var i = 0; i < sources.length; i++){ * if(sources[i].label === "soundflower"){ * soundflower.inputNum = i; * soundflower.open(function(){ * soundflower.start(); * }); * break; * } * } * }; */ Tone.ExternalInput.getSources = function (callback) { if (Tone.ExternalInput.sources.length === 0 && Tone.ExternalInput._canGetSources) { MediaStreamTrack.getSources(function (media_sources) { for (var i = 0; i < media_sources.length; i++) { if (media_sources[i].kind === 'audio') { Tone.ExternalInput.sources[i] = media_sources[i]; } } callback(Tone.ExternalInput.sources); }); } else { callback(Tone.ExternalInput.sources); } return this; }; return Tone.ExternalInput; }); Module(function (Tone) { /** * @class Opens up the default source (typically the microphone). * * @constructor * @extends {Tone.ExternalInput} * @example * //mic will feedback if played through master * var mic = new Tone.Microphone(); * mic.open(function(){ * //start the mic at ten seconds * mic.start(10); * }); * //stop the mic * mic.stop(20); */ Tone.Microphone = function () { Tone.ExternalInput.call(this, 0); }; Tone.extend(Tone.Microphone, Tone.ExternalInput); /** * If getUserMedia is supported by the browser. * @type {Boolean} * @memberOf Tone.Microphone# * @name supported * @static * @readOnly */ Object.defineProperty(Tone.Microphone, 'supported', { get: function () { return Tone.ExternalInput.supported; } }); return Tone.Microphone; }); Module(function (Tone) { /** * @class Clip the incoming signal so that the output is always between min and max. * * @constructor * @extends {Tone.SignalBase} * @param {number} min the minimum value of the outgoing signal * @param {number} max the maximum value of the outgoing signal * @example * var clip = new Tone.Clip(0.5, 1); * var osc = new Tone.Oscillator().connect(clip); * //clips the output of the oscillator to between 0.5 and 1. */ Tone.Clip = function (min, max) { //make sure the args are in the right order if (min > max) { var tmp = min; min = max; max = tmp; } /** * The min clip value * @type {Number} * @signal */ this.min = this.input = new Tone.Min(max); this._readOnly('min'); /** * The max clip value * @type {Number} * @signal */ this.max = this.output = new Tone.Max(min); this._readOnly('max'); this.min.connect(this.max); }; Tone.extend(Tone.Clip, Tone.SignalBase); /** * clean up * @returns {Tone.Clip} this */ Tone.Clip.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('min'); this.min.dispose(); this.min = null; this._writable('max'); this.max.dispose(); this.max = null; return this; }; return Tone.Clip; }); Module(function (Tone) { /** * @class Normalize takes an input min and max and maps it linearly to NormalRange [0,1] * * @extends {Tone.SignalBase} * @constructor * @param {number} inputMin the min input value * @param {number} inputMax the max input value * @example * var norm = new Tone.Normalize(2, 4); * var sig = new Tone.Signal(3).connect(norm); * //output of norm is 0.5. */ Tone.Normalize = function (inputMin, inputMax) { /** * the min input value * @type {number} * @private */ this._inputMin = this.defaultArg(inputMin, 0); /** * the max input value * @type {number} * @private */ this._inputMax = this.defaultArg(inputMax, 1); /** * subtract the min from the input * @type {Tone.Add} * @private */ this._sub = this.input = new Tone.Add(0); /** * divide by the difference between the input and output * @type {Tone.Multiply} * @private */ this._div = this.output = new Tone.Multiply(1); this._sub.connect(this._div); this._setRange(); }; Tone.extend(Tone.Normalize, Tone.SignalBase); /** * The minimum value the input signal will reach. * @memberOf Tone.Normalize# * @type {number} * @name min */ Object.defineProperty(Tone.Normalize.prototype, 'min', { get: function () { return this._inputMin; }, set: function (min) { this._inputMin = min; this._setRange(); } }); /** * The maximum value the input signal will reach. * @memberOf Tone.Normalize# * @type {number} * @name max */ Object.defineProperty(Tone.Normalize.prototype, 'max', { get: function () { return this._inputMax; }, set: function (max) { this._inputMax = max; this._setRange(); } }); /** * set the values * @private */ Tone.Normalize.prototype._setRange = function () { this._sub.value = -this._inputMin; this._div.value = 1 / (this._inputMax - this._inputMin); }; /** * clean up * @returns {Tone.Normalize} this */ Tone.Normalize.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._sub.dispose(); this._sub = null; this._div.dispose(); this._div = null; return this; }; return Tone.Normalize; }); Module(function (Tone) { /** * @class Route a single input to the specified output. * * @constructor * @extends {Tone.SignalBase} * @param {number} [outputCount=2] the number of inputs the switch accepts * @example * var route = new Tone.Route(4); * var signal = new Tone.Signal(3).connect(route); * route.select(0); * //signal is routed through output 0 * route.select(3); * //signal is now routed through output 3 */ Tone.Route = function (outputCount) { outputCount = this.defaultArg(outputCount, 2); Tone.call(this, 1, outputCount); /** * The control signal. * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); //make all the inputs and connect them for (var i = 0; i < outputCount; i++) { var routeGate = new RouteGate(i); this.output[i] = routeGate; this.gate.connect(routeGate.selecter); this.input.connect(routeGate); } }; Tone.extend(Tone.Route, Tone.SignalBase); /** * Routes the signal to one of the outputs and close the others. * @param {number} [which=0] Open one of the gates (closes the other). * @param {Time} [time=now] The time when the switch will open. * @returns {Tone.Route} this */ Tone.Route.prototype.select = function (which, time) { //make sure it's an integer which = Math.floor(which); this.gate.setValueAtTime(which, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Route} this */ Tone.Route.prototype.dispose = function () { this._writable('gate'); this.gate.dispose(); this.gate = null; for (var i = 0; i < this.output.length; i++) { this.output[i].dispose(); this.output[i] = null; } Tone.prototype.dispose.call(this); return this; }; ////////////START HELPER//////////// /** * helper class for Tone.Route representing a single gate * @constructor * @extends {Tone} * @private */ var RouteGate = function (num) { /** * the selector * @type {Tone.Equal} */ this.selecter = new Tone.Equal(num); /** * the gate * @type {GainNode} */ this.gate = this.input = this.output = this.context.createGain(); //connect the selecter to the gate gain this.selecter.connect(this.gate.gain); }; Tone.extend(RouteGate); /** * clean up * @private */ RouteGate.prototype.dispose = function () { Tone.prototype.dispose.call(this); this.selecter.dispose(); this.selecter = null; this.gate.disconnect(); this.gate = null; }; ////////////END HELPER//////////// //return Tone.Route return Tone.Route; }); Module(function (Tone) { /** * @class When the gate is set to 0, the input signal does not pass through to the output. * If the gate is set to 1, the input signal passes through. * the gate is initially closed. * * @constructor * @extends {Tone.SignalBase} * @param {Boolean} [open=false] If the gate is initially open or closed. * @example * var sigSwitch = new Tone.Switch(); * var signal = new Tone.Signal(2).connect(sigSwitch); * //initially no output from sigSwitch * sigSwitch.gate.value = 1; * //open the switch and allow the signal through * //the output of sigSwitch is now 2. */ Tone.Switch = function (open) { open = this.defaultArg(open, false); Tone.call(this); /** * The control signal for the switch. * When this value is 0, the input signal will NOT pass through, * when it is high (1), the input signal will pass through. * * @type {Number} * @signal */ this.gate = new Tone.Signal(0); this._readOnly('gate'); /** * thresh the control signal to either 0 or 1 * @type {Tone.GreaterThan} * @private */ this._thresh = new Tone.GreaterThan(0.5); this.input.connect(this.output); this.gate.chain(this._thresh, this.output.gain); //initially open if (open) { this.open(); } }; Tone.extend(Tone.Switch, Tone.SignalBase); /** * Open the switch at a specific time. * * @param {Time} [time=now] The time when the switch will be open. * @returns {Tone.Switch} this * @example * //open the switch to let the signal through * sigSwitch.open(); */ Tone.Switch.prototype.open = function (time) { this.gate.setValueAtTime(1, this.toSeconds(time)); return this; }; /** * Close the switch at a specific time. * * @param {Time} [time=now] The time when the switch will be closed. * @returns {Tone.Switch} this * @example * //close the switch a half second from now * sigSwitch.close("+0.5"); */ Tone.Switch.prototype.close = function (time) { this.gate.setValueAtTime(0, this.toSeconds(time)); return this; }; /** * Clean up. * @returns {Tone.Switch} this */ Tone.Switch.prototype.dispose = function () { Tone.prototype.dispose.call(this); this._writable('gate'); this.gate.dispose(); this.gate = null; this._thresh.dispose(); this._thresh = null; return this; }; return Tone.Switch; }); //UMD if ( typeof define === "function" && define.amd ) { define(function() { return Tone; }); } else if (typeof module === "object") { module.exports = Tone; } else { root.Tone = Tone; } } (this));
DeerMichel/pedalboard
js/tone.js
JavaScript
gpl-3.0
637,440
<?php /* <<<<<<< HEAD V5.16 26 Mar 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). All rights reserved. ======= V5.17 17 May 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). All rights reserved. >>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0 Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. This class provides recordset pagination with First/Prev/Next/Last links. Feel free to modify this class for your own use as it is very basic. To learn how to use it, see the example in adodb/tests/testpaging.php. "Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks(). Please note, this class is entirely unsupported, and no free support requests except for bug reports will be entertained by the author. */ class ADODB_Pager { var $id; // unique id for pager (defaults to 'adodb') var $db; // ADODB connection object var $sql; // sql used var $rs; // recordset generated var $curr_page; // current page number before Render() called, calculated in constructor var $rows; // number of rows per page var $linksPerPage=10; // number of links per page in navigation bar var $showPageLinks; var $gridAttributes = 'width=100% border=1 bgcolor=white'; // Localize text strings here var $first = '<code>|&lt;</code>'; var $prev = '<code>&lt;&lt;</code>'; var $next = '<code>>></code>'; var $last = '<code>>|</code>'; var $moreLinks = '...'; var $startLinks = '...'; var $gridHeader = false; var $htmlSpecialChars = true; var $page = 'Page'; var $linkSelectedColor = 'red'; var $cache = 0; #secs to cache with CachePageExecute() //---------------------------------------------- // constructor // // $db adodb connection object // $sql sql statement // $id optional id to identify which pager, // if you have multiple on 1 page. // $id should be only be [a-z0-9]* // function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false) { global $PHP_SELF; $curr_page = $id.'_curr_page'; if (!empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks $this->sql = $sql; $this->id = $id; $this->db = $db; $this->showPageLinks = $showPageLinks; $next_page = $id.'_next_page'; if (isset($_GET[$next_page])) { $_SESSION[$curr_page] = (integer) $_GET[$next_page]; } if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page $this->curr_page = $_SESSION[$curr_page]; } //--------------------------- // Display link to first page function Render_First($anchor=true) { global $PHP_SELF; if ($anchor) { ?> <a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; <?php } else { print "$this->first &nbsp; "; } } //-------------------------- // Display link to next page function render_next($anchor=true) { global $PHP_SELF; if ($anchor) { ?> <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; <?php } else { print "$this->next &nbsp; "; } } //------------------ // Link to last page // // for better performance with large recordsets, you can set // $this->db->pageExecuteCountRows = false, which disables // last page counting. function render_last($anchor=true) { global $PHP_SELF; if (!$this->db->pageExecuteCountRows) return; if ($anchor) { ?> <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; <?php } else { print "$this->last &nbsp; "; } } //--------------------------------------------------- // original code by "Pablo Costa" <pablo@cbsp.com.br> function render_pagelinks() { global $PHP_SELF; $pages = $this->rs->LastPageNo(); $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages; for($i=1; $i <= $pages; $i+=$linksperpage) { if($this->rs->AbsolutePage() >= $i) { $start = $i; } } $numbers = ''; $end = $start+$linksperpage-1; $link = $this->id . "_next_page"; if($end > $pages) $end = $pages; if ($this->startLinks && $start > 1) { $pos = $start - 1; $numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a> "; } for($i=$start; $i <= $end; $i++) { if ($this->rs->AbsolutePage() == $i) $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font> "; else $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a> "; } if ($this->moreLinks && $end < $pages) $numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a> "; print $numbers . ' &nbsp; '; } // Link to previous page function render_prev($anchor=true) { global $PHP_SELF; if ($anchor) { ?> <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; <?php } else { print "$this->prev &nbsp; "; } } //-------------------------------------------------------- // Simply rendering of grid. You should override this for // better control over the format of the grid // // We use output buffering to keep code clean and readable. function RenderGrid() { global $gSQLBlockRows; // used by rs2html to indicate how many rows to display include_once(ADODB_DIR.'/tohtml.inc.php'); ob_start(); $gSQLBlockRows = $this->rows; rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars); $s = ob_get_contents(); ob_end_clean(); return $s; } //------------------------------------------------------- // Navigation bar // // we use output buffering to keep the code easy to read. function RenderNav() { ob_start(); if (!$this->rs->AtFirstPage()) { $this->Render_First(); $this->Render_Prev(); } else { $this->Render_First(false); $this->Render_Prev(false); } if ($this->showPageLinks){ $this->Render_PageLinks(); } if (!$this->rs->AtLastPage()) { $this->Render_Next(); $this->Render_Last(); } else { $this->Render_Next(false); $this->Render_Last(false); } $s = ob_get_contents(); ob_end_clean(); return $s; } //------------------- // This is the footer function RenderPageCount() { if (!$this->db->pageExecuteCountRows) return ''; $lastPage = $this->rs->LastPageNo(); if ($lastPage == -1) $lastPage = 1; // check for empty rs. if ($this->curr_page > $lastPage) $this->curr_page = 1; return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>"; } //----------------------------------- // Call this class to draw everything. function Render($rows=10) { global $ADODB_COUNTRECS; $this->rows = $rows; if ($this->db->dataProvider == 'informix') $this->db->cursorType = IFX_SCROLL; $savec = $ADODB_COUNTRECS; if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true; if ($this->cache) $rs = $this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page); else $rs = $this->db->PageExecute($this->sql,$rows,$this->curr_page); $ADODB_COUNTRECS = $savec; $this->rs = $rs; if (!$rs) { print "<h3>Query failed: $this->sql</h3>"; return; } if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) $header = $this->RenderNav(); else $header = "&nbsp;"; $grid = $this->RenderGrid(); $footer = $this->RenderPageCount(); $this->RenderLayout($header,$grid,$footer); $rs->Close(); $this->rs = false; } //------------------------------------------------------ // override this to control overall layout and formating function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige') { echo "<table ".$attributes."><tr><td>", $header, "</td></tr><tr><td>", $grid, "</td></tr><tr><td>", $footer, "</td></tr></table>"; } } ?>
khan0407/FinalArcade
lib/adodb/adodb-pager.inc.php
PHP
gpl-3.0
8,269
/* * Copyright (C) 2009-2016 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra 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. * * geOrchestra 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 * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ package org.georchestra.ldapadmin.mailservice; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.georchestra.commons.configuration.GeorchestraConfiguration; import org.springframework.beans.factory.annotation.Autowired; /** * Facade of mail service. * * @author Mauricio Pazos * */ public final class MailService { protected static final Log LOG = LogFactory.getLog(MailService.class.getName()); private EmailFactoryImpl emailFactory; @Autowired private GeorchestraConfiguration georchestraConfiguration; @Autowired public MailService(EmailFactoryImpl emailFactory) { this.emailFactory = emailFactory; } public void sendNewAccountRequiresModeration(ServletContext servletContext, final String uid, final String userName, final String userEmail, final String moderatorEmail) { try { NewAccountRequiresModerationEmail email = this.emailFactory.createNewAccountRequiresModerationEmail(servletContext, userEmail, new String[]{moderatorEmail}); email.sendMsg(userName, uid); } catch (Exception e) { LOG.error(e); } } public void sendAccountCreationInProcess( final ServletContext servletContext, final String uid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - email: " + userEmail); } try{ AccountCreationInProcessEmail email = this.emailFactory.createAccountCreationInProcessEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid ); } catch (Exception e) { LOG.error(e); } } public void sendAccountUidRenamed(final ServletContext servletContext, final String newUid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("Send mail to warn user [email: " + userEmail + "] for its new identifier: " + newUid); } try{ AccountUidRenamedEmail email = this.emailFactory.createAccountUidRenamedEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, newUid ); } catch (Exception e) { LOG.error(e); } } public void sendAccountWasCreated(final ServletContext servletContext, final String uid, final String commonName, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - email: " + userEmail); } try{ AccountWasCreatedEmail email = this.emailFactory.createAccountWasCreatedEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid ); } catch (Exception e) { LOG.error(e); } } /** * Sent an email to the user whit the unique URL required to change his password. * @param servletContext * @param servletContext * * @param uid user id * @param commonName user full name * @param url url where the user can change his password * @param userEmail user email * */ public void sendChangePasswordURL(ServletContext servletContext, final String uid, final String commonName, final String url, final String userEmail) { if(LOG.isDebugEnabled()){ LOG.debug("uid: "+uid+ "- commonName" + commonName + " - url: " + url + " - email: " + userEmail); } try{ ChangePasswordEmail email = this.emailFactory.createChangePasswordEmail(servletContext, new String[]{userEmail}); email.sendMsg(commonName, uid, url); } catch (Exception e) { LOG.error(e); } } }
jusabatier/georchestra
ldapadmin/src/main/java/org/georchestra/ldapadmin/mailservice/MailService.java
Java
gpl-3.0
4,258
<? session_start(); /** * Modificacion Variables Globales Fabian losada 2009-07 * Licencia GNU/GPL */ foreach ($_GET as $key => $valor) ${$key} = $valor; foreach ($_POST as $key => $valor) ${$key} = $valor; $krd = $_SESSION["krd"]; //var_dump($_POST); $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; $codusuario = $_SESSION["codusuario"]; $tpNumRad = $_SESSION["tpNumRad"]; $tpPerRad = $_SESSION["tpPerRad"]; $tpDescRad = $_SESSION["tpDescRad"]; $tpDepeRad = $_SESSION["tpDepeRad"]; $ruta_raiz = ".."; include_once("$ruta_raiz/include/db/ConnectionHandler.php"); $db = new ConnectionHandler("$ruta_raiz"); include_once "$ruta_raiz/include/tx/Historico.php"; include_once "$ruta_raiz/include/tx/Expediente.php"; include("Combos.Class.php"); $obj= new Combos(); $continente=$obj->getContinentes(); $db->debug = true; $encabezadol = "$PHP_SELF?".session_name()."=".session_id()."&dependencia=$dependencia&krd=$krd"; ?> <script> function RegresarV(){ window.location.assign("adminEdificio.php?<?=$encabezado1?>&fechah=$fechah&$orno&adodb_next_page"); } </script> <? /** * Grabar los datos del edificio. */ if( isset( $_POST['btnGrabar'] ) && $_POST['btnGrabar'] != "" ) { //$db->conn->BeginTrans(); /** * Crea el registro con los datos del edificio. */ $q_insertE = "INSERT INTO SGD_EIT_ITEMS( SGD_EIT_CODIGO, SGD_EIT_COD_PADRE,"; $q_insertE .= " SGD_EIT_NOMBRE, SGD_EIT_SIGLA, ID_CONT, ID_PAIS,CODI_DPTO, CODI_MUNI)"; $sec=$db->conn->nextId( 'SEC_EDIFICIO' ); $q_insertE .= " VALUES( '$sec', 0,"; $q_insertE .= " UPPER( '".$_POST['edificioNom']."' ),"; $q_insertE .= " UPPER( '".$_POST['edificioSig']."' ),"; $q_insertE .= " ".$_POST['selCont'].", ".$_POST['selPais'].",".$_POST['selDepto'].", ".$_POST['selMnpio']." )"; echo $muni_us; $listo = $db->conn->Execute( $q_insertE ); /** * Datos de las unidades de almacenamiento del edificio. */ foreach( $_POST as $clavePOST => $valorPOST ) { if( strncmp( $clavePOST, 'nombre_', 7 ) == 0 ) { $nombreUA = $valorPOST; } if( strncmp( $clavePOST, 'sigla_', 6 ) == 0 ) { $siglaUA = $valorPOST; } if( $nombreUA != "" && $siglaUA != "" ) { /* * Crea el registro correspondiente a la unidad de almacenamiento. */ $q_insertUA = "INSERT INTO SGD_EIT_ITEMS( SGD_EIT_CODIGO,SGD_EIT_COD_PADRE, SGD_EIT_NOMBRE,"; $q_insertUA .= " SGD_EIT_SIGLA )"; $q_insertUA .= " VALUES( ".$db->conn->nextId( 'SEC_EDIFICIO' ).", $sec,"; $q_insertUA .= " UPPER( '".$nombreUA."' ), UPPER( '".$siglaUA."' ) )"; if( $listo ) { $listo = $db->conn->Execute( $q_insertUA ); } $nombreUA = ""; $siglaUA = ""; } } if( $listo->EOF ) { // $db->conn->CommitTrans(); ?> <script> window.open('<?=$ruta_raiz?>/archivo/relacionTiposAlmac.php?dependencia=<?=$dependencia?>&krd=<?=$krd?>&tipo=<?=$tipo?>&idEdificio=<?=$idEdificio?>&codp=<?=$sec?>',"Relacion Tipos Almacenamiento","height=350,width=550,scrollbars=yes"); </script> <? } else { $db->conn->RollbackTrans(); } // header( "Location: relacionTiposAlmac.php?".$encabezadol."&idEdificio=".$idEdificio); } ?> <html> <head> <title>INGRESO DE EDIFICIOS</title> <link rel="stylesheet" href="../estilos/orfeo.css"> <script language="JavaScript" src="../js/ajax.js"></script> <script language="JavaScript" type="text/javascript"> function validar() { var band=false; var msg=''; if(document.getElementById( 'selCont' ).value ==0){ band=true; msg+='Seleccione Continente\n'; } if(document.getElementById( 'selPais' ).value==0){ band=true; msg+='Seleccione pa\xEDs\n'; } if(document.getElementById( 'selDepto' ).value==0){ band=true; msg+='Seleccione Departamento\n'; } if(document.getElementById( 'selMnpio' ).value==0){ band=true; msg+='Seleccione Municipio\n'; } if(document.getElementById( 'edificioNom' ).value==''){ band=true; msg+='Debe digitar nombre del edificio\n'; } if(document.getElementById( 'edificioSig' ).value==''){ band=true; msg+='Debe digitar sigla del edificio\n'; } if( document.getElementById( 'numero' ).value == "" || isNaN( document.getElementById( 'numero' ).value ) ) { band=true; msg+= 'Debe ingresar N\xFAmero de Tipos de Almacenamiento.'; } if(band) { alert(msg); return !band } return !band } function mostrarCampos() { if(validar()) { var i; var j = parseInt( document.getElementById( 'numero' ).value ); var obj = document.getElementById('Lista'); var tbl= "\t<table width='100%' border='1'>" + "\t\t<tr>\n" + "\t\t\t<td class='titulos5'> NOMBRE</td>\n" + "\t\t\t<td class='titulos5'>SIGLA</td>\n"+ "\t\t</tr>\n"; for ( i = 0; i < j; i++ ) { tbl+= "\t\t<tr>\n" + "\t\t\t<td class='titulos5'><input type='text' name='nombre_" + i + "' size='40' maxlength='40'></td>\n" + "\t\t\t<td class='titulos5'><input type='text' name='sigla_" + i + "' size='4' maxlength='4'></td>\n" + "\t\t</tr>\n"; } tbl+= "\t\t<tr>\n" + "\t\t\t<td colspan='2' class='titulos5' align='center'><input type='submit' class='botones' value='Grabar' name='btnGrabar' onClick='return validar();'></td>\n" + "\t\t</tr>\n" + "\t</table>\n"; obj.innerHTML=tbl; //document.close() } } var divAutilizar; function pedirCombosDivipola(fuenteDatos, divID,tipo,continente,pais,departamento) { if(xmlHttp) { // obtain a reference to the <div> element on the page divAutilizar = document.getElementById(divID); try { xmlHttp.open("GET", fuenteDatos+"?tipo="+tipo+"&continente="+continente.value+"&pais="+pais.value+"&departamento="+departamento.value); xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null); } //display the error in case of failure catch (e) { alert("Can't connect to server:\n" + e.toString()); } } } //handles the response received from the server function handleServerResponse() { // read the message from the server var xmlResponse = xmlHttp.responseText; // display the HTML output divAutilizar.innerHTML = xmlResponse; } </script> </head> <body bgcolor="#FFFFFF"> <form name="inEdificio" action="<?=$encabezadol?>" method="post" > <table border="0" width="90%" cellpadding="0" class="borde_tab"> <tr> <td height="35" colspan="5" class="titulos2"> <center>INGRESO DE EDIFICIOS</center> </td> </tr> <tr><td valign="middle" class="titulos2">1.Ubicaci&oacute;n</td> <td height="30" class="titulos5" align="center"><b>Continente</b><br><?php echo $continente;?> </td> <td height="30" class="titulos5" align="center"> <b>Pais</b><br> <div id="DivPais"><select class="select" id="selPais"><option value="0">&lt;&lt Seleccione &gt;&gt</select></div> </td> <td height="30" class="titulos5" align="center"><b>Departamento</b><br><div id="DivDepto"><select class="select" id="selDepto"><option value="0">&lt;&lt Seleccione &gt;&gt</select></div></td> <td height="30" class="titulos5" align="center"><b>Municipio</b><br><div id="DivMnpio"><select class="select" id="selMnpio"><option value="0">&lt;&lt Seleccione &gt;&gt</select></div></td> </tr> <tr> <td rowspan="2" valign="middle" class="titulos2">2.Datos</td> <td height="23" class="titulos5" colspan="2"> <div align="left"> Nombre <input type="text" name="edificioNom" id="edificioNom" value="<?php print $_POST['nombre']; ?>" size="40" maxlength="40" align="right"> </div> </td> <td class="titulos5" colspan="2"> <div align="left"> Sigla <input type="text" name="edificioSig" id="edificioSig" value="<?php print $_POST['sigla']; ?>" size="4" maxlength="4" align="right"> </div> </td> </tr> <tr> <td height="26" class="titulos5" colspan="2"> <div align="left"> Ingrese N&uacute;mero de Tipos de Almacenamiento <input type="text" name="numero" id="numero" value="<?php print $_POST['numero']; ?>" size="2" maxlength="2" align="right"> </div> </td> <td class="titulos5" colspan="2"> <input type="button" name="btnMostrarCampos" class="botones_2" value="&gt;&gt;" onClick="mostrarCampos();"> </td> </tr> <tr> <td class="titulos5" colspan="5"><div id="Lista"></div></td> </tr> <tr> <td><input name='SALIR' type="button" class="botones" id="envia22" onClick="opener.regresar();window.close();" value="SALIR" align="middle" ></td> </tr> </table> </form> </body> </html>
tapion/orfeotmp
archivo/ingEdificio.php
PHP
gpl-3.0
9,354
package br.ufpe.ines.decode.observer.control; import java.io.File; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import br.ufpe.ines.decode.decode.CodingExperiment; import br.ufpe.ines.decode.decode.DecodePackage; public class ExperimentManager { protected static ExperimentManager singleton = new ExperimentManager(); private Set<CodingExperiment> loadedExperiments2 = new HashSet<CodingExperiment>(); private List<String> filePaths = new LinkedList<String>(); static final Logger logger = Logger.getLogger(ExperimentManager.class); // private CountDownLatch latchAction = new CountDownLatch(1); public static ExperimentManager getInstance() { if (singleton == null) singleton = new ExperimentManager(); return singleton; } protected ExperimentManager() { } public Set<CodingExperiment> getLoadedExperiments() { return loadedExperiments2; } public void loadDecodeModel(File filePath) { loadedExperiments2.add(load(filePath)); filePaths.add(filePath.getAbsolutePath()); } protected CodingExperiment load(File filePath) { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("decode", new XMIResourceFactoryImpl()); DecodePackage.eINSTANCE.eClass(); URI fileURI = URI.createFileURI(filePath.getAbsolutePath()); Resource resource = resourceSet.getResource(fileURI, true); EObject myModelObject = resource.getContents().get(0); CodingExperiment myWeb = null; if (myModelObject instanceof CodingExperiment) { myWeb = (CodingExperiment) myModelObject; } return myWeb; } public List<String> getFiles() { return filePaths; } public CodingExperiment getLoadedExperiment(String experimentID) { return loadedExperiments2.stream() .filter(e -> e.getElementId().equals(experimentID)) .findFirst().get(); } }
netuh/DecodePlatformPlugin
br.ufpe.ines.decode/bundles/br.ufpe.ines.decode.observer/src/br/ufpe/ines/decode/observer/control/ExperimentManager.java
Java
gpl-3.0
2,240
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de https://trad.spip.net/tradlang_module/paquet-forum?lang_cible=sk // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( // F 'forum_description' => 'Diskusné fóra SPIPu (súkromné a verejné)', 'forum_slogan' => 'Riadenie súkromných aj verejných diskusných fór v SPIPe' ); ?>
phenix-factory/p.henix.be
plugins-dist/forum/lang/paquet-forum_sk.php
PHP
gpl-3.0
472
Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, ENV['TWITTER_CONSUMER_KEY'], ENV['TWITTER_CONSUMER_SECRET'] end
mscoutermarsh/scrumbot
config/initializers/twitter.rb
Ruby
gpl-3.0
146
# -*- coding: utf-8 -*- from ptools import * pdb1f88 = getPDB("1F88") WritePDB(pdb1f88, "1F88.pdb")
glamothe/ptools
Tests/get1F88.py
Python
gpl-3.0
102
/* * This file is part of Log4Jdbc. * * Log4Jdbc 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. * * Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>. * */ package fr.ms.log4jdbc.util.logging.impl; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Date; import fr.ms.log4jdbc.lang.delegate.DefaultStringMakerFactory; import fr.ms.log4jdbc.lang.delegate.StringMakerFactory; import fr.ms.log4jdbc.lang.stringmaker.impl.StringMaker; import fr.ms.log4jdbc.util.logging.Logger; /** * * @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a> * * * @author Marco Semiao * */ public class DefaultLogger implements Logger { private final static String nl = System.getProperty("line.separator"); private final static StringMakerFactory stringMakerFactory = DefaultStringMakerFactory.getInstance(); private final PrintHandler printHandler; private final String name; private String level; private boolean trace; private boolean debug; private boolean info; private boolean warn; private boolean error; private boolean fatal; public DefaultLogger(final PrintHandler printHandler, final String level, final String name) { this.printHandler = printHandler; if (level != null) { if (level.equals("trace")) { trace = true; debug = true; info = true; error = true; } else if (level.equals("debug")) { debug = true; info = true; error = true; } else if (level.equals("info")) { info = true; error = true; } else if (level.equals("warn")) { warn = true; error = true; } else if (level.equals("error")) { error = true; } else if (level.equals("fatal")) { fatal = true; } this.level = level.toUpperCase(); } this.name = name; } public boolean isTraceEnabled() { return trace; } public boolean isDebugEnabled() { return debug; } public boolean isInfoEnabled() { return info; } public boolean isWarnEnabled() { return warn; } public boolean isErrorEnabled() { return error; } public boolean isFatalEnabled() { return fatal; } public void trace(final String message) { trace(message, null); } public void trace(final String message, final Throwable t) { if (isTraceEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.trace(formatMessage); } } public void debug(final String message) { debug(message, null); } public void debug(final String message, final Throwable t) { if (isDebugEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.debug(formatMessage); } } public void info(final String message) { info(message, null); } public void info(final String message, final Throwable t) { if (isInfoEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.info(formatMessage); } } public void warn(final String message) { warn(message, null); } public void warn(final String message, final Throwable t) { if (isWarnEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.warn(formatMessage); } } public void error(final String message) { error(message, null); } public void error(final String message, final Throwable t) { if (isErrorEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.error(formatMessage); } } public void fatal(final String message) { fatal(message, null); } public void fatal(final String message, final Throwable t) { if (isFatalEnabled()) { final String formatMessage = formatMessage(message) + getException(t); printHandler.fatal(formatMessage); } } private String getException(final Throwable t) { String exception = ""; if (t != null) { final StringWriter errors = new StringWriter(); t.printStackTrace(new PrintWriter(errors)); exception = nl + t.getMessage() + nl + errors.toString(); } return exception; } private String formatMessage(final String message) { final Date now = new Date(); final StringMaker newMessage = stringMakerFactory.newString(); newMessage.append("["); newMessage.append(now); newMessage.append("]"); newMessage.append(" ["); newMessage.append(level); newMessage.append("]"); newMessage.append(" ["); newMessage.append(name); newMessage.append("] "); newMessage.append(message); return newMessage.toString(); } public PrintWriter getPrintWriter() { final Writer writerLogger = new WriterLogger(this); // PrintWriter (println) est synchronized et si le logger est desactivé, // cela detruit les perfs :( à revoir return new PrintWriter(writerLogger); } @Override public String toString() { return "DefaultLogger [name=" + name + ", level=" + level + "]"; } }
marcosemiao/log4jdbc
core/log4jdbc-utils/log4jdbc-commons/src/main/java/fr/ms/log4jdbc/util/logging/impl/DefaultLogger.java
Java
gpl-3.0
5,410
using OMInsurance.DataAccess.Core; using OMInsurance.Entities; using System.Collections.Generic; using System.Linq; namespace OMInsurance.DataAccess.Materializers { public class NomernikClientSTOPMaterializer : IMaterializer<NomernikForClient> { private static readonly NomernikClientSTOPMaterializer _instance = new NomernikClientSTOPMaterializer(); public static NomernikClientSTOPMaterializer Instance { get { return _instance; } } public NomernikForClient Materialize(DataReaderAdapter reader) { return Materialize_List(reader).FirstOrDefault(); } public List<NomernikForClient> Materialize_List(DataReaderAdapter reader) { List<NomernikForClient> items = new List<NomernikForClient>(); while (reader.Read()) { NomernikForClient obj = ReadItemFields(reader); items.Add(obj); } return items; } public NomernikForClient ReadItemFields(DataReaderAdapter reader, NomernikForClient item = null) { if (item == null) { item = new NomernikForClient(); } item.Id = reader.GetInt64("ID"); item.SCENARIO = reader.GetString("SCENARIO"); item.S_CARD = reader.GetString("S_CARD"); item.N_CARD = reader.GetString("N_CARD"); item.ENP = reader.GetString("UnifiedPolicyNumber"); item.VSN = reader.GetString("TemporaryPolicyNumber"); item.QZ = reader.GetInt64Null("QZ"); item.DATE_END = reader.GetDateTimeNull("DATE_END"); item.DATE_ARC = reader.GetDateTimeNull("DATE_ARC"); item.IST = reader.GetString("IST"); item.ClientID = reader.GetInt64Null("ClientID"); item.LoadDate = reader.GetDateTime("LoadDate"); item.FileDate = reader.GetDateTime("FileDate"); item.Firstname = reader.GetString("Firstname"); item.Secondname = reader.GetString("Secondname"); item.Lastname = reader.GetString("Lastname"); return item; } } }
openzones/OMI
OMInsurance.DataAccess/Materializers/Nomernik/NomernikClientSTOPMaterializer.cs
C#
gpl-3.0
2,303
package meta; import ast.ExprIdentStar; public class WrImportStatement extends WrStatement { public WrImportStatement(WrExprIdentStar importPackage) { super(importPackage.hidden); } @Override public Object eval(WrEvalEnv ee) { ee.hidden.importPackage( ((ExprIdentStar ) hidden).asString()); return null; } @Override ExprIdentStar getHidden() { return (ExprIdentStar ) hidden; } @Override public void accept(WrASTVisitor visitor, WrEnv env) { ((ExprIdentStar ) hidden).getI().accept(visitor, env); } }
joseoliv/Cyan
meta/WrImportStatement.java
Java
gpl-3.0
528
from node import models from django.forms import ModelForm from . import cdmsportalfunc as cpf from django.core.exceptions import ValidationError from django import forms class MoleculeForm(ModelForm): class Meta: model = models.Molecules fields = '__all__' class SpecieForm(ModelForm): datearchived = forms.DateField( widget=forms.TextInput(attrs={'readonly': 'readonly'}) ) dateactivated = forms.DateField( widget=forms.TextInput(attrs={'readonly': 'readonly'}) ) class Meta: model = models.Species fields = '__all__' class FilterForm(ModelForm): class Meta: model = models.QuantumNumbersFilter fields = '__all__' class XsamsConversionForm(forms.Form): inurl = forms.URLField( label='Input URL', required=False, widget=forms.TextInput( attrs={'size': 50, 'title': 'Paste here a URL that delivers an XSAMS ' 'document.', })) infile = forms.FileField() format = forms.ChoiceField( choices=[("RAD 3D", "RAD 3D"), ("CSV", "CSV")], ) def clean(self): infile = self.cleaned_data.get('infile') inurl = self.cleaned_data.get('inurl') if (infile and inurl): raise ValidationError('Give either input file or URL!') if inurl: try: data = cpf.urlopen(inurl) except Exception as err: raise ValidationError('Could not open given URL: %s' % err) elif infile: data = infile else: raise ValidationError('Give either input file or URL!') try: self.cleaned_data['result'] = cpf.applyStylesheet2File(data) except Exception as err: raise ValidationError('Could not transform XML file: %s' % err) return self.cleaned_data
cpe/VAMDC-VALD
nodes/cdms/node/forms.py
Python
gpl-3.0
1,963
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Glyphs.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "PngImageList" #ifndef NO_RESOURCES #pragma resource "*.dfm" #endif //--------------------------------------------------------------------------- TGlyphsModule * GlyphsModule; //--------------------------------------------------------------------------- __fastcall TGlyphsModule::TGlyphsModule(TComponent* Owner) : TDataModule(Owner) { } //---------------------------------------------------------------------------
pmverma/winscp
source/forms/Glyphs.cpp
C++
gpl-3.0
669
Ext.define('Healthsurvey.view.mobileview.login.ChangePasswordScreenController', { extend : 'Ext.app.ViewController', alias : 'controller.changePasswordScreenController', onChangePasswordClick : function(btn, opts) { debugger; var form = btn.up().up(); if (form.isValid()) { var formData = form.getValues(); delete formData.reTypeNewPassword; var entMask = new Ext.LoadMask({ msg : 'Updating...', target : this.getView() }).show(); Ext.Ajax.request({ timeout : 180000, url : "secure/PasswordGenerator/changePassword", method : 'PUT', waitMsg : 'Updating...', entMask : entMask, jsonData : formData, me : this, success : function(response, sender) { debugger; var responseText = Ext.JSON.decode(response.responseText); if (responseText.response.success) { Ext.Msg.alert("Info", responseText.response.message); sender.me.onResetClick(); } else { Ext.Msg.alert("Info", responseText.response.message); } sender.entMask.hide(); }, failure : function(response, sender) { debugger; Ext.Msg.alert("ERROR", "Cannot connect to server"); sender.entMask.hide(); } }); } }, onResetClick : function(btn, opts) { debugger; this.getView().getForm().reset(); } });
applifireAlgo/appApplifire
healthsurvey/src/main/webapp/app/view/mobileview/login/ChangePasswordScreenController.js
JavaScript
gpl-3.0
1,301
<?php return array( 'param' => array( 'name' => '核心模块', 'description' => '直通车模块', 'author' => 'oShine', 'version' => '1.0', 'indexShow' => array( 'link' => 'main/default/index', ), ), 'config' => array( 'modules' => array( 'ztc' => array( 'class' => 'application\modules\ztc\ZtcModule' ) ), 'components' => array( 'messages' => array( 'extensionPaths' => array( 'ztc' => 'application.modules.ztc.language' ) ) ), ), );
ouyangjunqiu/CPSProject
system/modules/ztc/install/config.php
PHP
gpl-3.0
681
"""Clean db Revision ID: 4f8bd7cac829 Revises: 3f249e0d2769 Create Date: 2014-01-09 14:03:13.997656 """ # revision identifiers, used by Alembic. revision = '4f8bd7cac829' down_revision = '3f249e0d2769' from alembic import op import sqlalchemy as sa def upgrade(): ''' Drop the columns calendar_multiple_meetings and calendar_regional_meetings and rename meeting_region into meeting_location. ''' op.drop_column('calendars', 'calendar_multiple_meetings') op.drop_column('calendars', 'calendar_regional_meetings') op.alter_column( 'meetings', column_name='meeting_region', name='meeting_location', type_=sa.Text, existing_type=sa.String(100)) def downgrade(): ''' Add the columns calendar_multiple_meetings and calendar_regional_meetings and rename meeting_location into meeting_region. ''' op.add_column( 'calendars', sa.Column( 'calendar_multiple_meetings', sa.Boolean, default=False, nullable=False ) ) op.add_column( 'calendars', sa.Column( 'calendar_regional_meetings', sa.Boolean, default=False, nullable=False ) ) op.alter_column( 'meetings', column_name='meeting_location', name='meeting_region', type_=sa.String(100), existing_type=sa.Text)
fedora-infra/fedocal
alembic/versions/4f8bd7cac829_clean_db.py
Python
gpl-3.0
1,420
<?php namespace classes; class Render { //Private properties. private $templator, $template, $data; //Set the templator. public function __construct(BaseTemplator $templator, $template, array $data = []) { $this->templator = $templator; $this->setTemplate($template); $this->data = $data; } //Set the template that we will inject the data into. public function setTemplate($template) { //No template? if(!is_string($template)){ throw new \exception\InvalidArgument('Expecting $template to be string. %s given.', typeof($template)); } //Does it exist? if(!file_exists($template)){ throw new \exception\ResourceMissing('Given template (%s) must be an existing file.', $template); } //Set the template. $this->template = $template; //Enable chaining. return $this; } //Generate the output. public function generate() { //Store references to the required variables under obscure names. $___data =& $this->data; $___path =& $this->template; //Create the templator function that we will bind to the templator. $templator = function()use(&$___data, &$___path){ $t = $templator = $this; extract($___data); unset($___data); ob_start(); require($___path); $r = new OutputData(ob_get_contents(), $t->getHeaders()); ob_end_clean(); return $r; }; //Bind it. $templator = $templator->bindTo($this->templator); //Call it. return $templator(); } }
Tuxion/tuxion.framework
framework/system/classes/Render.php
PHP
gpl-3.0
1,602
Joomla 3.6.4 = 5e60174db2edd61c1c32011464017d84 Joomla 3.7.0 = c7eeeb362de64acba3e76fd13e0ad6af Joomla 3.4.1 = 399117bc209c7f4eb16f72bfef504db7
gohdan/DFC
known_files/hashes/media/editors/codemirror/mode/yaml/yaml.min.js
JavaScript
gpl-3.0
144
/* * Java2R: A library to connect Java and R * Copyright (C) 2009 Sankha Narayan Guria * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package sngforge.java2r; /** * Exception due to error in initialization of <code>RFactory</code> * @author Sankha Narayan Guria * @version 1.0 */ public class RFactoryException extends Exception { /** * Constructs an instance of <code>RFactoryException</code> with the specified detail message. * @param msg The detail message. */ public RFactoryException(String msg) { super(msg); } }
sankha93/java2r
source/src/sngforge/java2r/RFactoryException.java
Java
gpl-3.0
1,182
package pers.wzq.hb.util.table; import org.apache.poi.ss.usermodel.Cell; /** * excel表格格式化接口 * * @author RP_S * @since 2017年9月28日 */ public interface CellFormatter { /** * 使用自定义方式,格式化表格内容<br> * 可在table表格上自定义属性,编程转换成excel单元格样式 * * @param tableCell table表格 * @param cell excel表格 */ void formatCell(TableCell tableCell, Cell cell); }
srpgit/hb
hb/src/main/java/pers/wzq/hb/util/table/CellFormatter.java
Java
gpl-3.0
473
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages * * Copyright (C) 2014 German Research Center for Artificial Intelligence (DFKI) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package de.dfki.kiara.tcp; import de.dfki.kiara.InvalidAddressException; import de.dfki.kiara.Transport; import de.dfki.kiara.TransportAddress; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; /** * * @author Dmitri Rubinstein <dmitri.rubinstein@dfki.de> */ public class TcpBlockAddress implements TransportAddress { private final TcpBlockTransport transport; private final String hostName; private final int port; private final InetAddress address; public TcpBlockAddress(TcpBlockTransport transport, URI uri) throws InvalidAddressException, UnknownHostException { if (transport == null) { throw new NullPointerException("transport"); } if (uri == null) { throw new NullPointerException("uri"); } if (!"tcp".equals(uri.getScheme()) && !"tcps".equals(uri.getScheme())) { throw new InvalidAddressException("only tcp and tcps scheme is allowed"); } this.transport = transport; this.hostName = uri.getHost(); this.port = uri.getPort(); this.address = InetAddress.getByName(this.hostName); } public TcpBlockAddress(TcpBlockTransport transport, String hostName, int port) throws UnknownHostException { if (transport == null) { throw new NullPointerException("transport"); } if (hostName == null) { throw new NullPointerException("hostName"); } this.transport = transport; this.hostName = hostName; this.port = port; this.address = InetAddress.getByName(hostName); } @Override public Transport getTransport() { return transport; } @Override public int getPort() { return port; } @Override public String getHostName() { return hostName; } @Override public boolean acceptsTransportConnection(TransportAddress transportAddress) { if (transportAddress == null) { throw new NullPointerException("transportAddress"); } if (!(transportAddress instanceof TcpBlockAddress)) { return false; } TcpBlockAddress other = (TcpBlockAddress) transportAddress; if (!other.address.equals(this.address)) { final String otherHostName = other.getHostName(); final String thisHostName = getHostName(); if (!otherHostName.equals(thisHostName) && !"0.0.0.0".equals(thisHostName)) { return false; } } if (other.getPort() != getPort()) { return false; } return true; } @Override public boolean acceptsConnection(TransportAddress transportAddress) { return acceptsTransportConnection(transportAddress); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof TcpBlockAddress)) { return false; } TcpBlockAddress other = (TcpBlockAddress) obj; // FIXME is following always correct ? if (other.getTransport() != getTransport()) { return false; } return (other.address.equals(this.address) || other.hostName.equals(this.hostName)) && other.port == this.port; } @Override public String toString() { // FIXME what to do with different flavors of tcp (tcp, tcps) ? return getTransport().getName() + "://" + hostName + ":" + port; } }
dmrub/kiara-java
KIARA/src/main/java/de/dfki/kiara/tcp/TcpBlockAddress.java
Java
gpl-3.0
4,424
'use strict'; function Boot() { } Boot.prototype = { preload: function () { this.load.image('preloader', 'assets/preloader.gif'); }, create: function () { this.game.input.maxPointers = 1; this.game.state.start('preload'); } }; module.exports = Boot;
robomatix/one-minute-shoot-em-up-v2
game/states/boot.js
JavaScript
gpl-3.0
273
/************************************************************************** * * * Grov - Google Reader offline viewer * * * * Copyright (C) 2010, Dmitry Konishchev * * http://konishchevdmitry.blogspot.com/ * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * **************************************************************************/ #ifndef GROV_HEADER_CLIENT_READER_TASK #define GROV_HEADER_CLIENT_READER_TASK #include <grov/common.hpp> #include "task.hxx" namespace grov { namespace client { namespace reader { /// Base class for all tasks that we need to process. class Task: public QObject { Q_OBJECT public: Task(QObject* parent = NULL); ~Task(void); private: /// Is task finished. bool finished; public: /// Processes the task. virtual void process(void) = 0; protected: /// Returns true if task cancelled. /// /// @ATTENTION /// Must be used only in destructors - in other methods the return /// value is undefined. bool is_cancelled(void); /// Emits error() signal end finish the task. void failed(const QString& message); /// Asynchronously deletes the task. void finish(void); /// Processes a child task. void process_task(Task* task); signals: /// Emitted when task cancelled. void cancelled(void); /// This signal task emits when processing fails. void error(const QString& message); public slots: /// Cancels the task. virtual void cancel(void); private slots: /// Called when child task emits error() signal. void child_task_error(const QString& message); }; }}} #endif
KonishchevDmitry/grov
grov/client/reader/task.hpp
C++
gpl-3.0
2,617
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2020 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "porousBafflePressureFvPatchField.H" #include "surfaceFields.H" #include "momentumTransportModel.H" #include "addToRunTimeSelectionTable.H" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::porousBafflePressureFvPatchField::porousBafflePressureFvPatchField ( const fvPatch& p, const DimensionedField<scalar, volMesh>& iF ) : fixedJumpFvPatchField<scalar>(p, iF), phiName_("phi"), rhoName_("rho"), D_(0), I_(0), length_(0) {} Foam::porousBafflePressureFvPatchField::porousBafflePressureFvPatchField ( const fvPatch& p, const DimensionedField<scalar, volMesh>& iF, const dictionary& dict ) : fixedJumpFvPatchField<scalar>(p, iF), phiName_(dict.lookupOrDefault<word>("phi", "phi")), rhoName_(dict.lookupOrDefault<word>("rho", "rho")), D_(dict.lookup<scalar>("D")), I_(dict.lookup<scalar>("I")), length_(dict.lookup<scalar>("length")) { fvPatchField<scalar>::operator= ( Field<scalar>("value", dict, p.size()) ); } Foam::porousBafflePressureFvPatchField::porousBafflePressureFvPatchField ( const porousBafflePressureFvPatchField& ptf, const fvPatch& p, const DimensionedField<scalar, volMesh>& iF, const fvPatchFieldMapper& mapper ) : fixedJumpFvPatchField<scalar>(ptf, p, iF, mapper), phiName_(ptf.phiName_), rhoName_(ptf.rhoName_), D_(ptf.D_), I_(ptf.I_), length_(ptf.length_) {} Foam::porousBafflePressureFvPatchField::porousBafflePressureFvPatchField ( const porousBafflePressureFvPatchField& ptf ) : fixedJumpFvPatchField<scalar>(ptf), phiName_(ptf.phiName_), rhoName_(ptf.rhoName_), D_(ptf.D_), I_(ptf.I_), length_(ptf.length_) {} Foam::porousBafflePressureFvPatchField::porousBafflePressureFvPatchField ( const porousBafflePressureFvPatchField& ptf, const DimensionedField<scalar, volMesh>& iF ) : fixedJumpFvPatchField<scalar>(ptf, iF), phiName_(ptf.phiName_), rhoName_(ptf.rhoName_), D_(ptf.D_), I_(ptf.I_), length_(ptf.length_) {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void Foam::porousBafflePressureFvPatchField::updateCoeffs() { if (updated()) { return; } const surfaceScalarField& phi = db().lookupObject<surfaceScalarField>(phiName_); const fvsPatchField<scalar>& phip = patch().patchField<surfaceScalarField, scalar>(phi); scalarField Un(phip/patch().magSf()); if (phi.dimensions() == dimDensity*dimVelocity*dimArea) { Un /= patch().lookupPatchField<volScalarField, scalar>(rhoName_); } scalarField magUn(mag(Un)); const momentumTransportModel& turbModel = db().lookupObject<momentumTransportModel> ( IOobject::groupName ( momentumTransportModel::typeName, internalField().group() ) ); jump_ = -sign(Un) *( D_*turbModel.nu(patch().index()) + I_*0.5*magUn )*magUn*length_; if (internalField().dimensions() == dimPressure) { jump_ *= patch().lookupPatchField<volScalarField, scalar>(rhoName_); } if (debug) { scalar avePressureJump = gAverage(jump_); scalar aveVelocity = gAverage(mag(Un)); Info<< patch().boundaryMesh().mesh().name() << ':' << patch().name() << ':' << " Average pressure drop :" << avePressureJump << " Average velocity :" << aveVelocity << endl; } fixedJumpFvPatchField<scalar>::updateCoeffs(); } void Foam::porousBafflePressureFvPatchField::write(Ostream& os) const { fixedJumpFvPatchField<scalar>::write(os); writeEntryIfDifferent<word>(os, "phi", "phi", phiName_); writeEntryIfDifferent<word>(os, "rho", "rho", rhoName_); writeEntry(os, "D", D_); writeEntry(os, "I", I_); writeEntry(os, "length", length_); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { makePatchTypeField ( fvPatchScalarField, porousBafflePressureFvPatchField ); } // ************************************************************************* //
will-bainbridge/OpenFOAM-dev
src/MomentumTransportModels/momentumTransportModels/derivedFvPatchFields/porousBafflePressure/porousBafflePressureFvPatchField.C
C++
gpl-3.0
5,473
#!/usr/bin/python # -*- coding: utf-8 -*- """ Takes Google's json encoded spreadsheet and prints a python dictionary keyed by the values in the first column of the SS. ©2017 J. J. Crump, GNU general public license """ import urllib2 from pprint import pprint import re import json # This is the url of a sample google spreadsheet that I've published to the web. The url returns a prettyprinted json string: ssURL = "https://spreadsheets.google.com/feeds/list/1OPNQC3xBp3iQTpjVfd6cpvvA0BpHWhb3QiNOvGFZ9z8/od6/public/basic?prettyprint=true&alt=json" response = urllib2.urlopen(ssURL) jsonIn = response.read() pyDict = json.loads(jsonIn) entryList = pyDict['feed']['entry'] fields = ["name", "city", "state", "zip"] SSdict = {} def parsestring(rowstring, fields): """yields tuples of (fieldname, fieldvalue)""" i = iter(fields[1:]) field = i.next() start = end = 0 try: while True: lastfield = field field = i.next() if rowstring.find(field) == -1: field = lastfield continue end = rowstring.find(field) yield lastfield, re.sub('^.*?:', '', rowstring[start:end].strip().strip(',')).strip() start = end except StopIteration: start = rowstring.find(field) yield lastfield, re.sub('^.*?:', '', rowstring[start:].strip().strip(',')).strip() for e in entryList: entrydict = dict([x for x in parsestring(e['content']['$t'], fields)]) entrykey = e['title']['$t'] SSdict[entrykey] = entrydict #print stringIn pprint(SSdict)
jjon/Google-Spreadsheet-python-scripts
GSheet2Python.py
Python
gpl-3.0
1,622
<!-- select2 from array --> <div @include('crud::inc.field_wrapper_attributes') > <label>{!! $field['label'] !!}</label> <select name="{{ $field['name'] }}@if (isset($field['allows_multiple']) && $field['allows_multiple']==true)[]@endif" style="width: 100%" @include('crud::inc.field_attributes', ['default_class' => 'form-control select2_from_array']) @if (isset($field['allows_multiple']) && $field['allows_multiple']==true)multiple @endif > @if (isset($field['allows_null']) && $field['allows_null']==true) <option value="">-</option> @endif @if (count($field['options'])) @foreach ($field['options'] as $key => $value) @if((old(square_brackets_to_dots($field['name'])) && ( $key == old(square_brackets_to_dots($field['name'])) || (is_array(old(square_brackets_to_dots($field['name']))) && in_array($key, old(square_brackets_to_dots($field['name'])))))) || (null === old(square_brackets_to_dots($field['name'])) && ((isset($field['value']) && ( $key == $field['value'] || ( is_array($field['value']) && in_array($key, $field['value']) ) )) || (isset($field['default']) && ($key == $field['default'] || ( is_array($field['default']) && in_array($key, $field['default']) ) ) )) )) <option value="{{ $key }}" selected>{{ $value }}</option> @else <option value="{{ $key }}">{{ $value }}</option> @endif @endforeach @endif </select> {{-- HINT --}} @if (isset($field['hint'])) <p class="help-block">{!! $field['hint'] !!}</p> @endif </div> {{-- ########################################## --}} {{-- Extra CSS and JS for this particular field --}} {{-- If a field type is shown multiple times on a form, the CSS and JS will only be loaded once --}} @if ($crud->checkIfFieldIsFirstOfItsType($field)) {{-- FIELD CSS - will be loaded in the after_styles section --}} @push('crud_fields_styles') <!-- include select2 css--> <link href="{{ asset('vendor/adminlte/bower_components/select2/dist/css/select2.min.css') }}" rel="stylesheet" type="text/css" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css" rel="stylesheet" type="text/css" /> @endpush {{-- FIELD JS - will be loaded in the after_scripts section --}} @push('crud_fields_scripts') <!-- include select2 js--> <script src="{{ asset('vendor/adminlte/bower_components/select2/dist/js/select2.min.js') }}"></script> <script> jQuery(document).ready(function($) { // trigger select2 for each untriggered select2 box $('.select2_from_array').each(function (i, obj) { if (!$(obj).hasClass("select2-hidden-accessible")) { $(obj).select2({ theme: "bootstrap" }).on('select2:unselect', function(e) { if ($(this).attr('multiple') && $(this).val().length == 0) { $(this).val(null).trigger('change'); } }); } }); }); </script> @endpush @endif {{-- End of Extra CSS and JS --}} {{-- ########################################## --}}
lejubila/piGardenWeb
vendor/backpack/crud/src/resources/views/fields/select2_from_array.blade.php
PHP
gpl-3.0
4,030
<?php /** * @package base * @version 0.4.0.0 * @author Roman Konertz <konertz@open-lims.org> * @copyright (c) 2008-2016 by Roman Konertz * @license GPLv3 * * This file is part of Open-LIMS * Available at http://www.open-lims.org * * This program is free software; * you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; * version 3 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ /** * System Messages Admin IO Class * @package base */ class AdminSystemMessageIO { public static function home() { define(SYSTEM_MESSAGE_ENTRIES_PER_PAGE, 6); $system_message_array = SystemMessage::list_entries(); if (!$_GET['page']) { $page = 1; } else { $page = $_GET['page']; } $entry_count = count($system_message_array); $number_of_pages = ceil($entry_count/SYSTEM_MESSAGE_ENTRIES_PER_PAGE); $template = new HTMLTemplate("base/admin/system_message/list.html"); $paramquery = $_GET; $paramquery['action'] = "add"; unset($paramquery['nextpage']); $params = http_build_query($paramquery,'','&#38;'); $template->set_var("add_params", $params); if (is_array($system_message_array) and count($system_message_array) >= 1) { $template->set_var("no_entry",false); $result = array(); $counter = 0; if (count($system_message_array) < ($page*SYSTEM_MESSAGE_ENTRIES_PER_PAGE)) { $max_for = (count($system_message_array) % SYSTEM_MESSAGE_ENTRIES_PER_PAGE) - 1; } else { $max_for = SYSTEM_MESSAGE_ENTRIES_PER_PAGE-1; } for ($i=0;$i<=$max_for;$i++) { $entry = ($page*SYSTEM_MESSAGE_ENTRIES_PER_PAGE)+$i-SYSTEM_MESSAGE_ENTRIES_PER_PAGE; // Erzeugt Entry-ID $value = $system_message_array[$entry]; $system_message = new SystemMessage($value); $user = new User($system_message->get_user_id()); $datetime_handler = new DatetimeHandler($system_message->get_datetime()); $content = str_replace("\n", "<br />", $system_message->get_content()); $content = str_replace("\\", "", $content); $result[$counter]['user'] = $user->get_full_name(false); $result[$counter]['datetime'] = $datetime_handler->get_date()." at ".$datetime_handler->get_time(); $result[$counter]['content'] = $content; $paramquery = $_GET; $paramquery['action'] = "edit"; $paramquery['id'] = $value; unset($paramquery['nextpage']); $params = http_build_query($paramquery,'','&#38;'); $result[$counter]['edit_params'] = $params; $paramquery = $_GET; $paramquery['action'] = "delete"; $paramquery['id'] = $value; unset($paramquery['nextpage']); $params = http_build_query($paramquery,'','&#38;'); $result[$counter]['delete_params'] = $params; $counter++; } $template->set_var("message_array", $result); } else { $template->set_var("no_entry",true); } if ($number_of_pages > 1) { $template->set_var("page_bar",Common_IO::page_bar($page, $number_of_pages, $_GET)); } else { $template->set_var("page_bar",""); } $template->output(); } public static function create() { global $user; if ($_GET['nextpage'] == 1) { $page_1_passed = true; if (!$_POST['content']) { $page_1_passed = false; $error = "You must enter a text"; } } else { $page_1_passed = false; $error = ""; } if ($page_1_passed == false) { $template = new HTMLTemplate("base/admin/system_message/add.html"); $paramquery = $_GET; $paramquery['nextpage'] = "1"; $params = http_build_query($paramquery,'','&#38;'); $template->set_var("params",$params); if ($error) { $template->set_var("error", $error); } else { $template->set_var("error", ""); } if ($_POST['content']) { $template->set_var("content", $_POST['content']); } else { $template->set_var("content", ""); } $template->output(); } else { $paramquery = $_GET; unset($paramquery['nextpage']); unset($paramquery['action']); $params = http_build_query($paramquery); $system_message = new SystemMessage(null); if ($system_message->create($user->get_user_id(), $_POST['content'])) { Common_IO::step_proceed($params, "Add System Message", "Operation Successful", null); } else { Common_IO::step_proceed($params, "Add System Message", "Operation Failed" ,null); } } } /** * @throws SystemMessageIDMissingException */ public static function delete() { if ($_GET['id']) { $system_message = new SystemMessage($_GET['id']); if ($_GET['sure'] != "true") { $template = new HTMLTemplate("base/admin/system_message/delete.html"); $paramquery = $_GET; $paramquery['sure'] = "true"; $params = http_build_query($paramquery); $template->set_var("yes_params", $params); $paramquery = $_GET; unset($paramquery['sure']); unset($paramquery['action']); unset($paramquery['id']); $params = http_build_query($paramquery,'','&#38;'); $template->set_var("no_params", $params); $template->output(); } else { $paramquery = $_GET; unset($paramquery['sure']); unset($paramquery['action']); unset($paramquery['id']); $params = http_build_query($paramquery,'','&#38;'); if ($system_message->delete()) { Common_IO::step_proceed($params, "Delete System Message", "Operation Successful" ,null); } else { Common_IO::step_proceed($params, "Delete System Message", "Operation Failed" ,null); } } } else { throw new SystemMessageIDMissingException(); } } /** * @throws SystemMessageIDMissingException */ public static function edit() { if ($_GET['id']) { $system_message = new SystemMessage($_GET['id']); if ($_GET['nextpage'] == 1) { $page_1_passed = true; if (!$_POST['content']) { $page_1_passed = false; $error = "You must enter a text"; } } else { $page_1_passed = false; $error = ""; } if ($page_1_passed == false) { $template = new HTMLTemplate("base/admin/system_message/edit.html"); $paramquery = $_GET; $paramquery['nextpage'] = "1"; $params = http_build_query($paramquery,'','&#38;'); $template->set_var("params",$params); if ($error) { $template->set_var("error", $error); } else { $template->set_var("error", ""); } $content = str_replace("\\", "", $system_message->get_content()); if ($_POST['content']) { $template->set_var("content", $_POST['content']); } else { $template->set_var("content", $content); } $template->output(); } else { $paramquery = $_GET; unset($paramquery['nextpage']); unset($paramquery['action']); $params = http_build_query($paramquery); if ($system_message->set_content($_POST['content'])) { Common_IO::step_proceed($params, "Add System Message", "Operation Successful", null); } else { Common_IO::step_proceed($params, "Add System Message", "Operation Failed" ,null); } } } else { throw new SystemMessageIDMissingException(); } } public static function handler() { switch($_GET['action']): case "add": self::create(); break; case "edit": self::edit(); break; case "delete": self::delete(); break; default: self::home(); break; endswitch; } } ?>
open-lims/open-lims
www/core/modules/base/io/admin/admin_system_message.io.php
PHP
gpl-3.0
8,401
package net.minecraft.server; import javax.annotation.Nullable; public abstract class AttributeBase implements IAttribute { private final IAttribute a; private final String b; private final double c; private boolean d; protected AttributeBase(@Nullable IAttribute iattribute, String s, double d0) { this.a = iattribute; this.b = s; this.c = d0; if (s == null) { throw new IllegalArgumentException("Name cannot be null!"); } } public String getName() { return this.b; } public double b() { return this.c; } public boolean c() { return this.d; } public AttributeBase a(boolean flag) { this.d = flag; return this; } @Nullable public IAttribute d() { return this.a; } public int hashCode() { return this.b.hashCode(); } public boolean equals(Object object) { return object instanceof IAttribute && this.b.equals(((IAttribute) object).getName()); } }
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/AttributeBase.java
Java
gpl-3.0
1,057
<?php // This file is part of the Carrington Text Theme for WordPress // http://carringtontheme.com // // Copyright (c) 2008-2009 Crowd Favorite, Ltd. All rights reserved. // http://crowdfavorite.com // // Released under the GPL license // http://www.opensource.org/licenses/gpl-license.php // // ********************************************************************** // 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. // ********************************************************************** if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); } if (CFCT_DEBUG) { cfct_banner(__FILE__); } global $previousday, $authordata; $previousday = -1; ?> <div id="post-content-<?php the_ID() ?>" <?php post_class('hentry full') ?>> <div class="post-content-left"> <div class="cal"> <p class="month"><?php the_time('M') ?></p> <p class="year"><?php the_time('j') ?></p> </div> <div class="post-content-left-meta"> <address class="author vcard full-author"> <p> <?php printf(__('<span class="by">By</span> %s', 'carrington-text'), '<a class="url fn" href="'.get_author_link(false, get_the_author_ID(), $authordata->user_nicename).'" title="View all posts by ' . attribute_escape($authordata->display_name) . '">'.get_the_author().'</a>') ?> </p> </address> <p><!--<p class="comments-link">--><?php comments_popup_link(__('No Comments', 'carrington-text'), __('1 Comment', 'carrington-text'), __('% Comments', 'carrington-text')); ?></p> <p class="filed categories"><?php printf(__('Categories: %s', 'carrington-text'), get_the_category_list(', ')) ?></p> <?php the_tags(__('<p class="filed tags">Tags: ', 'carrington-text'), ', ', '</p>'); ?> <!--/filed--> </div> </div> <div class="post-content-right"> <div class="post-head"> <h1 class="entry-title full-title"><a href="<?php the_permalink() ?>" title="Permanent link to <?php the_title_attribute() ?>" rel="bookmark" rev="post-<?php the_ID(); ?>"><?php the_title() ?></a></h1> </div> <div class="entry-content full-content"> <?php the_content('<span class="more-link">'.__('Continued...', 'carrington-text').'</span>'); $args = array( 'before' => '<p class="pages-link">'. __('Pages: ', 'carrington-text'), 'after' => "</p>\n", 'next_or_number' => 'number' ); wp_link_pages($args); ?> <div class="clear"></div> </div><!--/entry-content--> </div> <div class="clear"></div> <div class="by-line"> <?php edit_post_link(__('Edit', 'carrington-text'), '<div class="entry-editlink">', '</div>'); ?> </div><!--/by-line--> </div><!-- .post -->
loulaner/wordpress
wp-content/themes/dewdrop/content/content-default.php
PHP
gpl-3.0
2,726
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('tgl_indo')) { function dateinsert($data) { $garing="/"; $cek=strpos($data,$garing); if($cek!=null) { $x=explode("/", $data); $date="$x[2]-$x[0]-$x[1]"; return $date; } else { return $data; } } }
qwords/evote
application/helpers/dateinsert_helper.php
PHP
gpl-3.0
351
/* * Copyright (C) 2015 ikonstas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pltag.parser.semantics.discriminative; import pltag.parser.params.Vec; /** * * @author konstas */ public class Feature { private final Vec vec; private final int index; public Feature(Vec probVec, int index) { this.vec = probVec; this.index = index; } public int getIndex() { return index; } public double getValue() { return vec.getCount(index); } public void setValue(double value) { vec.setUnsafe(index, value); } public void increment(double value) { setValue(getValue() + value); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Feature other = (Feature) obj; if (this.vec != other.vec && (this.vec == null || !this.vec.equals(other.vec))) { return false; } return this.index == other.index; } @Override public int hashCode() { int hash = 7; hash = 83 * hash + (this.vec != null ? this.vec.hashCode() : 0); hash = 83 * hash + this.index; return hash; } @Override public String toString() { return String.valueOf(index); } }
sinantie/PLTAG
src/pltag/parser/semantics/discriminative/Feature.java
Java
gpl-3.0
2,104
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :character do name 'Tyrol Ericson' property 'I made it up' end end
erumble/sir_judgington
spec/factories/characters.rb
Ruby
gpl-3.0
179
<?php /* Gibbon, Flexible & Open School System Copyright (C) 2010, Ross Parker This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ use Gibbon\Module\Credentials\CredentialsCredentialGateway; include '../../gibbon.php'; $gibbonPersonID = $_GET['gibbonPersonID'] ?? ''; $search = $_GET['search'] ?? ''; $allStudents = $_GET['allStudents'] ?? ''; $credentialsCredentialID = $_GET['credentialsCredentialID'] ?? ''; $URL = $session->get('absoluteURL').'/index.php?q=/modules/'.getModuleName($_POST['address'])."/credentials_student_delete.php&gibbonPersonID=$gibbonPersonID&search=$search&allStudents=$allStudents&credentialsCredentialID=".$credentialsCredentialID; $URLDelete = $session->get('absoluteURL').'/index.php?q=/modules/'.getModuleName($_POST['address'])."/credentials_student.php&gibbonPersonID=$gibbonPersonID&search=$search&allStudents=$allStudents"; if (isActionAccessible($guid, $connection2, '/modules/Credentials/credentials_student_delete.php') == false) { //Fail 0 $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Proceed! if (($credentialsCredentialID == '') or ( $gibbonPersonID == '')) { echo __m('Fatal error loading this page!'); } else { $credentialsCredentialGateway = $container->get(CredentialsCredentialGateway::class); $credential = $credentialsCredentialGateway->getById($credentialsCredentialID); if (!$credential) { //Fail 2 $URL .= '&return=error2'; header("Location: {$URL}"); } else { //Write to database $credentialsCredentialGateway->delete($credentialsCredentialID); //Success 0 $URLDelete = $URLDelete.'&return=success0'; header("Location: {$URLDelete}"); } } }
GibbonEdu/module-credentials
Credentials/credentials_student_deleteProcess.php
PHP
gpl-3.0
2,382
/* Glyph.java * Component: ProperJavaRDP * * Revision: $Revision: 12 $ * Author: $Author: miha_vitorovic $ * Date: $Date: 2007-05-11 13:49:09 +0200 (Fri, 11 May 2007) $ * * Copyright (c) 2005 Propero Limited * * Purpose: Represents data for individual glyphs, used for drawing text * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * (See gpl.txt for details of the GNU General Public License.) * */ package net.propero.rdp; // import java.awt.*; // import java.awt.image.*; public class Glyph { private int font = 0; private int character = 0; private int offset = 0; private int baseline = 0; private int width = 0; private int height = 0; private byte[] fontdata = null; /** * Construct a Glyph object * * @param font * Font ID for Glyph * @param character * Character ID for Glyph * @param offset * x-offset of Glyph data for drawing * @param baseline * y-offset of Glyph data for drawing * @param width * Width of Glyph, in pixels * @param height * Height of Glyph, in pixels * @param fontdata * Data detailing Glyph's graphical representation */ public Glyph(int font, int character, int offset, int baseline, int width, int height, byte[] fontdata) { this.font = font; this.character = character; this.offset = offset; this.baseline = baseline; this.width = width; this.height = height; this.fontdata = fontdata; } /** * Retrieve the font ID for this Glyph * * @return Font ID */ public int getFont() { return this.font; } /** * Retrive y-offset of Glyph data * * @return y-offset */ public int getBaseLine() { return this.baseline; } /** * Return character ID of this Glyph * * @return ID of character represented by this Glyph */ public int getCharacter() { return this.character; } /** * Retrive x-offset of Glyph data * * @return x-offset */ public int getOffset() { return this.offset; } /** * Return width of Glyph * * @return Glyph width, in pixels */ public int getWidth() { return this.width; } /** * Return height of Glyph * * @return Glyph height, in pixels */ public int getHeight() { return this.height; } /** * Graphical data for this Glyph * * @return Data defining graphical representation of this Glyph */ public byte[] getFontData() { return this.fontdata; } }
jakobadam/rdp
src/net/propero/rdp/Glyph.java
Java
gpl-3.0
3,279
<?php /** * @package Arastta eCommerce * @copyright Copyright (C) 2015-2016 Arastta Association. All rights reserved. (arastta.org) * @credits See CREDITS.txt for credits and other copyright notices. * @license GNU General Public License version 3; see LICENSE.txt */ class ModelSystemEmailtemplate extends Model { public function editEmailTemplate($email_template, $email_template_description) { $this->trigger->fire('pre.admin.emailtemplate.edit', array(&$email_template_description)); $item = explode("_", $email_template); $query = $this->db->query("SELECT id FROM " . DB_PREFIX . "email WHERE type = '" . $item[0] ."' AND text_id = '" . (int)$item[1] ."'"); $email_id = $query->row['id']; $this->db->query("DELETE FROM " . DB_PREFIX . "email_description WHERE email_id = '" . (int)$email_id . "'"); foreach ($email_template_description as $language_id => $value) { $this->db->query("INSERT INTO " . DB_PREFIX . "email_description SET email_id = '" . (int)$email_id . "', name = '". $this->db->escape($value['name']) . "', description = '". $this->db->escape($value['description']) . "', status = '1', language_id = '". (int)$language_id . "'"); } $this->trigger->fire('post.admin.emailtemplate.edit', array(&$email_template_description)); } public function getEmailTemplate($email_template) { $item = explode("_", $email_template); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "email AS e LEFT JOIN " . DB_PREFIX . "email_description AS ed ON ed.email_id = e.id WHERE e.type = '" . $item[0] . "' AND e.text_id = '" . $item[1] . "'"); foreach ($query->rows as $result) { $email_template_data[$result['language_id']] = array( 'text' => $result['text'], 'text_id' => $result['text_id'], 'type' => $result['type'], 'context' => $result['context'], 'name' => $result['name'], 'description' => $result['description'], 'status' => $result['status'] ); } return $email_template_data; } public function getEmailTemplates($data = array()) { $sql = "SELECT * FROM `" . DB_PREFIX . "email` AS e"; $isWhere = 0; $_sql = array(); if (isset($data['filter_name']) && !is_null($data['filter_name'])) { $isWhere = 1; $sql .= " LEFT JOIN `" . DB_PREFIX . "email_description` AS ed ON e.id = ed.email_id "; $_sql[] = "ed.name LIKE '" . $this->db->escape($data['filter_name']) . "%'"; } if (isset($data['filter_text']) && !is_null($data['filter_text'])) { $isWhere = 1; $_sql[] = "e.text LIKE '" . $this->db->escape($data['filter_text']) . "%'"; } if (isset($data['filter_context']) && !is_null($data['filter_context'])) { $isWhere = 1; $_sql[] = "e.context LIKE '" . $this->db->escape($data['filter_context']) . "%'"; } if (isset($data['filter_type']) && !is_null($data['filter_type'])) { $isWhere = 1; $filterType = $this->getEmailTypes($data['filter_type']); $_sql[] = "e.type = '" . $this->db->escape($filterType) . "'"; } if (isset($data['filter_status']) && !is_null($data['filter_status'])) { $isWhere = 1; $_sql[] = "e.status LIKE '" . $this->db->escape($data['filter_status']) . "%'"; } if ($isWhere) { $sql .= " WHERE " . implode(" AND ", $_sql); } $sort_data = array( 'name', 'sort_order' ); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql .= " ORDER BY " . $data['sort']; } else { $sql .= " ORDER BY e.type"; } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql .= " DESC"; } else { $sql .= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit']; } $query = $this->db->query($sql); if (!empty($query->num_rows)) { foreach ($query->rows as $key => $email_temp) { if ($email_temp['type'] == 'order') { $result = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_status` WHERE order_status_id ='". $email_temp['text_id'] ."' AND language_id ='" . $this->config->get('config_language_id') ."'") ; if (!empty($result->num_rows) && !empty($result->row['name'])) { $query->rows[$key]['text'] = $result->row['name']; } } } } return $query->rows; } protected function getEmailTypes($item) { $result = array ( 'order', 'customer', 'affiliate', 'review', 'contact', 'cron', 'mail' ); if ($item < 1 || $item > 7) { $item = 1; } return $result[$item-1]; } public function getEmailTemplatesStores($email_template) { $manufacturer_store_data = array(); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "manufacturer_to_store WHERE email_template = '" . (int)$email_template . "'"); foreach ($query->rows as $result) { $manufacturer_store_data[] = $result['store_id']; } return $manufacturer_store_data; } public function getTotalEmailTemplates($data) { $sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "email AS e"; $isWhere = 0; $_sql = array(); if (isset($data['filter_name']) && !is_null($data['filter_name'])) { $isWhere = 1; $sql .= " LEFT JOIN `" . DB_PREFIX . "email_description` AS ed ON e.id = ed.email_id "; $_sql[] = "ed.name LIKE '" . $this->db->escape($data['filter_name']) . "%'"; } if (isset($data['filter_text']) && !is_null($data['filter_text'])) { $isWhere = 1; $_sql[] = "e.text LIKE '" . $this->db->escape($data['filter_text']) . "%'"; } if (isset($data['filter_context']) && !is_null($data['filter_context'])) { $isWhere = 1; $_sql[] = "e.context LIKE '" . $this->db->escape($data['filter_context']) . "%'"; } if (isset($data['filter_type']) && !is_null($data['filter_type'])) { $isWhere = 1; $filterType = $this->getEmailTypes($data['filter_type']); $_sql[] = "e.type = '" . $this->db->escape($filterType) . "'"; } if (isset($data['filter_status']) && !is_null($data['filter_status'])) { $isWhere = 1; $_sql[] = "e.status LIKE '" . $this->db->escape($data['filter_status']) . "%'"; } if ($isWhere) { $sql .= " WHERE " . implode(" AND ", $_sql); } $query = $this->db->query($sql); return $query->row['total']; } public function getShortCodes($email_template) { $item = explode("_", $email_template); $result = array(); switch ($item[0]) { case 'admin': $codes = $this->emailtemplate->getLoginFind(); break; case 'affiliate': $codes = $this->emailtemplate->getAffiliateFind(); break; case 'contact': $codes = $this->emailtemplate->getContactFind(); break; case 'customer': $codes = $this->emailtemplate->getCustomerFind(); break; case 'order': $codes = $this->emailtemplate->getOrderAllFind(); break; case 'reviews': $codes = $this->emailtemplate->getReviewFind(); break; case 'voucher': $codes = $this->emailtemplate->getVoucherFind(); break; case 'invoice': $codes = $this->emailtemplate->getInvoiceFind(); break; case 'stock': $codes = $this->emailtemplate->getStockFind(); break; case 'return': $codes = $this->emailtemplate->getReturnFind(); break; } foreach ($codes as $code) { $result[] = array( 'code' => $code, 'text' => $this->language->get($code) ); } return $result; } public function getDemoData() { $this->load->language('mail/shortcode'); $data = $this->language->all(); $this->trigger->fire('post.emailtemplate.demo.data', array(&$data)); return $data; } }
denisdulici/arastta
admin/model/system/email_template.php
PHP
gpl-3.0
9,435
/*global assert: false, refute: false */ var buster = require("buster"), huddle = require("../lib/huddle.js"), resources; buster.testCase('Huddle', { setUp: function () { resources = new huddle.Huddle(); }, "Empty input": function () { resources.read(''); assert.equals(resources.write(), ''); }, "Doctype should be preserved": function () { resources.read('<!DOCTYPE html>'); assert.equals(resources.write(), '<!DOCTYPE html>'); }, "Multi line doctype": function () { resources.read('<!DOCTYPE html line1\nline2>'); assert.equals(resources.write(), '<!DOCTYPE html line1\nline2>'); }, "Singleton tag": function () { resources.read('<div/>'); assert.equals(resources.write(), '<div/>'); }, "Strip whitespace": function () { resources.read(' <div/>'); assert.equals(resources.write(), '<div/>'); }, "Preserve whitespace": function () { resources = new huddle.Huddle({ignoreWhitespace: false}); resources.read(' <div/>'); assert.equals(resources.write(), ' <div/>'); }, "Open/Close tag without body": function () { resources.read('<div></div>'); assert.equals(resources.write(), '<div/>'); }, "Open/Close tag with body": function () { resources.read('<div>Test</div>'); assert.equals(resources.write(), '<div>Test</div>'); }, "Tag with attributes": function () { resources.read('<div a1="v1" a2="v2"/>'); assert.equals(resources.write(), '<div a1="v1" a2="v2"/>'); }, "Stylesheet link tag": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.write(), '<link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['app']['a.css'], 'text/css'); }, "Multiple stylesheet link tags": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css"/><link href="b.less" rel="stylesheet/less" type="text/css"/>'); assert.equals(resources.write(), '<link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['app']['a.css'], 'text/css'); assert.equals(resources.getStylesheets()['app']['b.less'], 'text/less'); }, "Stylesheet with module": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-module="mymod"/>'); assert.equals(resources.write(), '<link href="mymod.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['mymod']['a.css'], 'text/css'); refute(resources.getStylesheets()['app']); }, "Multiple stylesheet link tags with modules": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-module="mylib"/><link href="b.less" rel="stylesheet/less" type="text/css"/>'); assert.equals(resources.write(), '<link href="mylib.css" rel="stylesheet" type="text/css"/><link href="app.css" rel="stylesheet" type="text/css"/>'); assert.equals(resources.getStylesheets()['mylib']['a.css'], 'text/css'); assert.equals(resources.getStylesheets()['app']['b.less'], 'text/less'); }, "Drop stylesheet link tag": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-drop=""/>'); assert.equals(resources.write(), ''); refute(resources.getStylesheets()['app']); }, "Include remote stylesheet": function () { resources.read('<link href="a.css" rel="stylesheet" type="text/css" data-remote="b.css"/>'); assert.equals(resources.write(), '<link href="b.css" rel="stylesheet" type="text/css"/>'); refute(resources.getStylesheets()['app']); }, "Script tag": function () { resources.read('<script type="text/javascript" src="a.js"></script>'); assert.equals(resources.write(), '<script type="text/javascript" src="app.js"></script>'); assert.equals(resources.getScripts()['app']['a.js'], 'text/javascript'); }, "Multiple script tags with modules": function () { resources.read('<script type="text/javascript" src="a.js"></script><script type="text/javascript" src="b.js" data-module="mylib"></script>'); assert.equals(resources.write(), '<script type="text/javascript" src="app.js"></script><script type="text/javascript" src="mylib.js"></script>'); assert.equals(resources.getScripts()['app']['a.js'], 'text/javascript'); assert.equals(resources.getScripts()['mylib']['b.js'], 'text/javascript'); }, "Drop script tag": function () { resources.read('<script type="text/javascript" src="a.js" data-drop=""/>'); assert.equals(resources.write(), ''); refute(resources.getScripts()['app']); }, "Include remote scripts": function () { resources.read('<script type="text/javascript" src="a.js" data-remote="b.js"/>'); assert.equals(resources.write(), '<script type="text/javascript" src="b.js"></script>'); refute(resources.getScripts()['app']); } });
robgietema/huddle
test/huddle-test.js
JavaScript
gpl-3.0
5,229
// // // Convertahedron, convert beteen what polyptyth/poly can understand. // Please consult http://www.laidout.org about where to send any // correspondence about this software. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // For more details, consult the COPYING file in the top directory. // // Copyright (C) 2011-2012 by Tom Lechner #include <lax/fileutils.h> #include "poly.h" using namespace LaxFiles; using namespace Laxkit; using namespace Polyptych; //Right now, convert between "idat", obj, and off void usage() { Polyhedron poly; cerr <<"convertahedron -h"<<endl; cerr <<"convertahedron [-i informat] infilename [-o outformat] [-c] outfilename"<<endl; cerr <<"\nThe \"-h\" option displays this help."<<endl; cerr <<"Current input formats are: "<<poly.InFileFormats()<<endl; cerr <<"Current output formats are: "<<poly.OutFileFormats()<<endl; cerr <<"\nFor the second run format, options must be given in specified order."<<endl; cerr <<"The format for infilename is hopefully found automatically, but can be specified by -i."<<endl; cerr <<"Format for out is determined by the extension, or can be explicitly specified with -o."<<endl; cerr <<"If outfilename exists, it will not be clobbered, unless -c is specified."<<endl; } void Arrg() { cerr <<"Not enough arguments!!"<<endl<<endl; usage(); exit(1); } int main(int argc, char **argv) { if (argc==1 || (argc>1 && (!strcasecmp(argv[1],"-h") || !strcasecmp(argv[1],"--help")))) { usage(); exit(0); } int i=1; const char *infile=NULL, *outfile=NULL, *informat=NULL, *outformat=NULL; int clobber=0; if (argc<=i) Arrg(); if (!strcmp(argv[i],"-i")) { informat=argv[i]; i++; } if (argc<=i) Arrg(); infile=argv[i]; i++; Polyhedron poly; int status=1; char *error=NULL; if (informat) { if (!strcasecmp(informat,"idat")) status=poly.dumpInFile(infile,&error); else { FILE *f=fopen(infile,"r"); if (!f) { cerr <<"Could not open "<<infile<<" for reading!"<<endl; exit(1); } if (!strcasecmp(informat,"off")) status=poly.dumpInOFF(f,&error); else if (!strcasecmp(informat,"obj")) status=poly.dumpInObj(f,&error); fclose(f); } } else status=poly.dumpInFile(infile,&error); if (status!=0) { if (error) cerr<<error<<endl; cerr <<"Error reading in "<<infile<<"!"<<endl; exit(1); } cerr <<"Done reading in.."<<endl; if (argc<=i) Arrg(); if (!strcmp(argv[i],"-o")) { outformat=argv[i]; i++; } if (argc<=i) Arrg(); if (!strcmp(argv[i],"-c")) { clobber=1; i++; } if (argc<=i) Arrg(); outfile=argv[i]; if (!outformat) outformat=strrchr(outfile,'.'); if (outformat) outformat++; if (!outfile) Arrg(); if (!outformat) { cerr <<"Missing or unknown output format!"<<endl; exit(1); } if (!clobber && file_exists(outfile,0,NULL)) { cerr <<"Not overwriting "<<outfile<<", use -c if you must."<<endl; exit(1); } if (error) { delete[] error; error=NULL; } status=poly.dumpOutFile(outfile,outformat,&error); if (error) cerr <<"Errors encountered:\n"<<error<<endl; if (status) { cerr <<"Error interrupted output."<<endl; return 1; } cout <<"Done!"<<endl; return 0; }
Laidout/laidout
src/polyptych/src/convertahedron.cc
C++
gpl-3.0
3,355
#-*- encoding: utf-8 -*- from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, RequestContext, render from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.urlresolvers import reverse from membro_profile.models import MembroProfile from submissao.models import Submissao def some_view(request): if not request.user.is_authenticated(): return HttpResponse("You are logged in.") else: return HttpResponse("You are not logged in.") # Create your views here. def register(request): context = RequestContext(request) registered = False if request.method == 'POST': membro_form = MembroForm(data=request.POST) membro_profile_form = MembroProfileForm(data=request.POST) if membro_form.is_valid() and membro_profile_form.is_valid(): membro = membro_form.save() membro.set_password(membro.password) membro.save() membro_profile = membro_profile_form.save(commit=False) membro_profile.user = membro if 'avatar' in request.FILES: membro_profile.picture = request.FILES['avatar'] membro_profile.save() registered = True else: print (membro_form.errors, membro_profile_form.errors) else: membro_form = MembroForm() membro_profile_form = MembroProfileForm() return render_to_response( 'profile/register.html', # {'membro_form': membro_form, 'registered': registered}, {'membro_form': membro_form, 'membro_profile_form': membro_profile_form, 'registered': registered}, context) def membro_login(request): context = RequestContext(request) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] membro = authenticate(username=username,password=password) if membro: if membro.is_active: login(request, membro) return HttpResponseRedirect('/') else: return HttpResponse('Sua conta ainda não foi liberada.') else: print ("Login e senha invalidos: {0}, {1}".format(username, password)) return HttpResponse("Login ou Senha, Invalidos") else: # return render_to_response('profile/404.html', {}, context) return render_to_response('profile/login.html', {}, context) @login_required def user_logout(request): # Since we know the user is logged in, we can now just log them out. logout(request) # Take the user back to the homepage. return HttpResponseRedirect('/') @login_required def profile(request): context = RequestContext(request) print (context) usuario = User.objects.get(username=request.user) membro = MembroProfile.objects.get(user=usuario) if membro: return render_to_response('profile/profile.html', {'m':membro}, context) else: return HttpResponse('Inscrição não encontrado') @login_required def edit_profile(request): membro = request.user form = EditProfileForm( request.POST or None, initial={ 'first_name': membro.first_name, 'last_name': membro.last_name, 'cpf': membro.membroprofile.cpf, } ) if form.is_valid(): membro.first_name = request.POST['first_name'] membro.last_name = request.POST['last_name'] membro.cpf = request.POST['cpf'] membro.save() return HttpResponseRedirect('%s'%(reverse('profile'))) context = { "form": form } return render(request, 'profile/editar.html', context) #from submissao.models import Submissao def index(request): context = RequestContext(request) print (str(request.user) == 'AnonymousUser') if str(request.user) == 'AnonymousUser': return render_to_response('profile/login.html', context) else: queryset = Submissao.objects.filter(autor_id=request.user.membroprofile.id or None) if request.user.is_authenticated(): membro = MembroProfile.objects.filter(user__username=request.user).latest('user').user context["membro"] = membro context['lista_resumos'] = queryset return render_to_response('profile/index.html', context) else: return render_to_response('profile/login.html', context)
pixies/academic
membro_profile/views.py
Python
gpl-3.0
4,644
/* eMafiaServer - Settings.java GNU GENERAL PUBLIC LICENSE V3 Copyright (C) 2012 Matthew 'Apocist' Davis */ package com.inverseinnovations.eMafiaServer.includes.classes; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.Properties; import com.inverseinnovations.eMafiaServer.*; import com.inverseinnovations.eMafiaServer.includes.StringFunctions; /**Server user-definable settings to be loaded from file*/ public class Settings { public Base Base; Properties p = new Properties(); boolean loadError = false; // Server config variables //Keep in mind that on a live host, you'll want to bind to the outbound IP or host name, not localhost or 127.0.0.1, etc. 0 should work just fine public String SERVER_HOST; public int SERVER_PORT; public String SERVER_ADDRESS;//default is "localhost" public int SERVER_MAX_CLIENTS;//default is "256" is is how many players can connect at once public int CLIENT_BUILD; // Connection timeout for activity-less connections (in seconds) public int CONN_TIMEOUT; //MySql Config public String MYSQL_URL; public String MYSQL_USER; public String MYSQL_PASS; public String APIKEY; public String APIURL; public String GAMEMASTERNAME; public String GAMEMASTERPASS; public int LOGGING; /** Initialize and attempting to load server settings from settings.ini. * If setting or file doesn't exist, will make file and choose default settings during this session. */ public Settings(Base base){ this.Base = base; try {p.load(new FileInputStream("settings.ini"));} catch (Exception e) { loadError = true; Base.Console.config("Unable to read from settings.ini, attempting to make a new one."); PrintWriter writer; try { writer = new PrintWriter("settings.ini", "UTF-8"); writer.println("# Server config variables"); writer.println("#SERVER_HOST is the ip address other users connect to the server with."); writer.println("#Keep in mind that on a live host, you'll want to bind to the outbound IP or host name, not localhost or 127.0.0.1, etc."); writer.println("SERVER_HOST= 0"); writer.println("SERVER_PORT= 1234");//1234 is dev server - 3689 is public server(Apo normally keeps public server up and running) writer.println("SERVER_ADDRESS= localhost"); writer.println("SERVER_MAX_CLIENTS= 256"); writer.println("CLIENT_BUILD= 1");//Used for Client update control writer.println(); writer.println("# Connection timeout for activity-less connections (in seconds)"); writer.println("CONN_TIMEOUT= 1200"); writer.println(); writer.println("MYSQL_ADDR= 127.0.0.1"); writer.println("MYSQL_PORT= 3306"); writer.println("MYSQL_DBNAME= mafiamud"); writer.println("MYSQL_USER= *****"); writer.println("MYSQL_PASS= *****"); writer.println(); writer.println("# SC2Mafia Forum Settings"); writer.println("APIKEY= *****");//Getting permission for Oops to release the key publicly writer.println("APIURL= http://sc2mafia.com/forum/api.php"); writer.println("GAMEMASTERNAME= eMafia Game Master");//Any account really works..this is just a dedicated bot writer.println("GAMEMASTERPASS= *****"); writer.println(); writer.println("# Logging Level:"); writer.println("#OMIT = Only log Severe errors, Warnings, and Config settings"); writer.println("#NORMAL = Log everything but the small details"); writer.println("#EXPAND = Log everything including the small details"); writer.println("#DEBUG= Every tid bit is displayed, may include sensitive data such as encrypted passwords and cause exessive garbage."); writer.println("LOGGING= DEBUG"); writer.close(); } catch (Exception e2) { Base.Console.warning("Error: Unable to create a settings file, will continue to run with default"); } } SERVER_HOST = loadVariableFromSettings("SERVER_HOST","0"); SERVER_PORT = loadVariableFromSettings("SERVER_PORT",1234); SERVER_ADDRESS = loadVariableFromSettings("SERVER_ADDRESS","localhost"); SERVER_MAX_CLIENTS = loadVariableFromSettings("SERVER_MAX_CLIENTS",256); CLIENT_BUILD = loadVariableFromSettings("CLIENT_BUILD",5); CONN_TIMEOUT = loadVariableFromSettings("CONN_TIMEOUT",1200); //"jdbc:mysql://192.168.1.80:3306/mafiamud"; MYSQL_URL = "jdbc:mysql://"+loadVariableFromSettings("MYSQL_ADDR","127.0.0.1")+":"+loadVariableFromSettings("MYSQL_PORT",3306)+"/"+loadVariableFromSettings("MYSQL_DBNAME","mafiamud"); MYSQL_USER = loadVariableFromSettings("MYSQL_USER","*****"); MYSQL_PASS = loadVariableFromSettings("MYSQL_PASS","*****"); APIKEY = loadVariableFromSettings("APIKEY","g9nZkHeE"); APIURL = loadVariableFromSettings("APIURL","http://sc2mafia.com/forum/api.php"); GAMEMASTERNAME = loadVariableFromSettings("GAMEMASTERNAME","eMafia Game Master"); GAMEMASTERPASS = loadVariableFromSettings("GAMEMASTERPASS","*****"); switch(loadVariableFromSettings("LOGGING","NORMAL").toUpperCase()){ case "OMIT":LOGGING = 0;break; case "NORMAL":LOGGING = 1;break; case "EXPAND":LOGGING = 2;break; case "DEBUG":LOGGING = 3;break; default:LOGGING = 1;break; } } /** Attempt to retrieve the set String from settings.ini * @param varName * @param defaultValue * @return settings or defaultValue if non-exisitant */ private String loadVariableFromSettings(String varName, String defaultValue){ if(!loadError){ String var = p.getProperty(varName); if(var != null && !var.equals("")){ return var; } } return defaultValue; } /** Attempt to retrieve the set int from settings.ini * @param varName * @param defaultValue * @return settings or defaultValue if non-exisitant */ private int loadVariableFromSettings(String varName, int defaultValue){ if(!loadError){ String var = p.getProperty(varName); if(var != null && !var.equals("")){ if(StringFunctions.isInteger(var)){ return Integer.parseInt(var); } } } return defaultValue; } }
apocist/eMafiaServer
src/com/inverseinnovations/eMafiaServer/includes/classes/Settings.java
Java
gpl-3.0
6,028
# -*- coding: utf-8 -*- class ImproperlyConfigured(Exception): pass class TaskHandlingError(Exception): pass
Outernet-Project/artexinweb
artexinweb/exceptions.py
Python
gpl-3.0
121
/* * This file is part of MystudiesMyteaching application. * * MystudiesMyteaching application 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. * * MystudiesMyteaching application 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 MystudiesMyteaching application. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; describe('Event time span filter', function () { var eventTimeSpanFilter; beforeEach(module('directives.weekFeed')); beforeEach(module('ngResource')); beforeEach(function () { module(function ($provide) { $provide.constant('StateService', { getStateFromDomain: function () { } }); $provide.constant('LanguageService', { getLocale: function () { return 'en'; } }); }); }); beforeEach(inject(function ($filter) { eventTimeSpanFilter = $filter('eventTimeSpan'); })); it('Will show only startdate with english format', function () { var startDate = moment([2014, 2, 12, 13, 40]); var result = eventTimeSpanFilter(startDate); expect(result).toEqual('3/12/2014 13:40'); }); });
UH-StudentServices/mystudies-myteaching-frontend
main/test/spec/unit/directives/weekFeed/eventTimeSpanFilterEnSpec.js
JavaScript
gpl-3.0
1,516
(function () { 'use strict'; function Cat(name, color) { this.name = name; this.color = color; } Cat.prototype.age = 4; var huesitos = new Cat('huesitos', 'amarillo claro'); display(huesitos.__proto__); display(Cat.prototype ); display(huesitos.__proto__ == Cat.prototype ); Cat.prototype = { age: 5}; display(Cat.prototype); } ());
zaiboot/javascript-playground
public/prototypes/demo03/demo.js
JavaScript
gpl-3.0
409
#include "app.h" int main(int argc, char *argv[]) { return App{}.run(argc, argv); }
benwaffle/gtorrent
src/main.cc
C++
gpl-3.0
88
module ApplicationHelper #added helpers back after rails 3 upgrade def get_calibrator_name( calibrator_id ) Calibrator.find( calibrator_id ).a_name end def get_calibrator_name_from_item( item_id ) Calibrator.find( Event.where("item_id=#{item_id}").order("created_at DESC").limit(1).first.calibrator_id ).a_name end def get_calibrator_id_from_item( item_id ) item = Item.find( item_id ) item.events.first( order: 'created_at DESC').calibrator_id end def get_item_count Item.all.count end def get_rough_due_cal_count #return a list of items due cal based on a 365 day assumption Item.find( :all, :conditions => ["last_calibrated_on < ? and inCal = ?", 1.year.ago, false]).count end def get_in_cal_count Item.all( :conditions => [ "inCal = ?", true ] ).count end def get_inactive_count Item.all( :conditions => ["inactive = ?", 1]).count end def get_item_description_from_id( an_id ) Item.find(an_id).description end def get_item_org_sn_from_id( an_id ) Item.find(an_id).org_sn end def get_image_tag_from_item_id( an_id ) my_item = Item.find( an_id ) raw( "#{image_tag( my_item.picture.url(:small), :border=> 0)}" ) end end
bserviss/railscalibrate
app/helpers/application_helper.rb
Ruby
gpl-3.0
1,242
#include <apertium_xml2cpp.h> #include <string> #include <iostream> namespace apertium { namespace xml2cpp { } // namespace xml2cpp } // namespace apertium
andreisfrent/apertium-transfer-xmlcpp
src/error/Error.cc
C++
gpl-3.0
157
// Decompiled with JetBrains decompiler // Type: Wb.Lpw.Platform.Protocol.LogCodes.Services.Inventory.GetAllTransactionTimesCS.Warning // Assembly: Wb.Lpw.Protocol, Version=2.13.83.0, Culture=neutral, PublicKeyToken=null // MVID: A621984F-C936-438B-B744-D121BF336087 // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Wb.Lpw.Protocol.dll namespace Wb.Lpw.Platform.Protocol.LogCodes.Services.Inventory.GetAllTransactionTimesCS { public abstract class Warning { } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/Wb.Lpw.Protocol/LogCodes/Services/Inventory/GetAllTransactionTimesCS/Warning.cs
C#
gpl-3.0
575
export class HttpClient { private static defaultHeaders: { [key: string]: string } = { "Accept": "application/json" }; private setRequestHeaders(httpRequest: XMLHttpRequest, headers: { [key: string]: string } = {}) { const h = { ...HttpClient.defaultHeaders, ...headers }; for (const name in h) { if (h.hasOwnProperty(name)) { httpRequest.setRequestHeader(name, h[name]); } } } request(url: string, method: string, complete: (data: any) => void, error: (httpRequest: XMLHttpRequest) => void = null) { const httpRequest = new XMLHttpRequest(); if (!httpRequest) { return false; } httpRequest.onreadystatechange = function () { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { complete(JSON.parse(httpRequest.responseText) || httpRequest.responseText); } else { if (error) { error(httpRequest); } else { throw new Error("There was a problem with the request."); } } } }; httpRequest.open(method, url); this.setRequestHeaders(httpRequest); httpRequest.send(); } get(url: string, complete: (data: any) => void, error: (httpRequest: XMLHttpRequest) => void = null) { this.request(url, "GET", complete, error); } }
ThULB/dbt
src/main/media/ts/_http/client.ts
TypeScript
gpl-3.0
1,345
namespace Grove.CardsLibrary { using System.Collections.Generic; using AI.TargetingRules; using AI.TimingRules; using Effects; using Modifiers; public class GatherCourage : CardTemplateSource { public override IEnumerable<CardTemplate> GetCards() { yield return Card .Named("Gather Courage") .ManaCost("{G}") .Type("Instant") .Text( "{Convoke}{I}(Your creatures can help cast this spell. Each creature you tap while casting this spell pays for {1} or one mana of that creature's color.){/I}{EOL}Target creature gets +2/+2 until end of turn.") .FlavorText("\"Even your shadow is too foul to tolerate.\"") .SimpleAbilities(Static.Convoke) .Cast(p => { p.Text = "Target creature gets +2/+2 until end of turn."; p.Effect = () => new ApplyModifiersToTargets( () => new AddPowerAndToughness(2, 2) {UntilEot = true}); p.TargetSelector.AddEffect(trg => trg.Is.Creature().On.Battlefield()); p.TargetingRule(new EffectPumpInstant(2, 2)); p.TimingRule(new PumpTargetCardTimingRule()); }); } } }
pinky39/grove
source/Grove/CardsLibrary/GatherCourage.cs
C#
gpl-3.0
1,184
<?php /** * Base Routing Class * * This class represents a type of base controller class with default REST and Controller functions. */ abstract class Route { //! callback $beforeRenderCallback This callback will get called before render process in afterRoute function protected $beforeRenderCallback = NULL; /** * List a subset of records * * Per default it sets JSON to true */ public function listing() { \App::set("JSON", TRUE); \App::set("ACTION", "list"); \Helper\Routing::instance()->generateListingResult(); } /** * index action * * Do nothing except render an index view */ public function index() { /* NOP */ } /** * REST GET */ public function get() { \App::set("ACTION", "show"); \Helper\Routing::instance()->generateShowResult(); } public function post() { \App::set("ACTION", "show"); } public function put() { \App::set("ACTION", "show"); } public function patch() { \App::set("ACTION", "show"); } public function delete() { \App::set("ACTION", "list"); } public function head() { \App::set("ACTION", "show"); } /** * before route action * * Called in front of every action * Defines some render constants */ public function beforeRoute() { list($prepath, $controller, $action) = explode("/", App::get("PATH")); App::set("PREPATH", $prepath); /* UNUSED! */ App::set("CONTROLLER", $controller); App::set("ACTION", $action); App::set("RENDERTEMPLATE", FALSE); App::set("CURRENTTITLE", FALSE); App::set("JSON", App::get("AJAX")); App::log(App::SEVERITY_TRACE, "Default route desired to [$controller] => [$action] from [" . App::get("PATH") . "](" . (App::get("AJAX") ? "AJAX" : "SYNC") . ")"); } /** * after route action * * Called after every action * Rehash the final view and render it */ public function afterRoute() { $this->setContent(); $this->setTitle(); if ($this->beforeRenderCallback !== NULL && is_callable($this->beforeRenderCallback)) $this->beforeRenderCallback(); $this->render(); } //! Set the HTML title constant from action or CURRENTTITLE constant protected function setTitle() { $currentTitle = App::get("CURRENTTITLE"); $controllerName = App::get("CONTROLLER"); App::set("CURRENTTITLE", $currentTitle ? $currentTitle : ucfirst(strtolower($controllerName ? $controllerName : "home"))); } //! Calculate the render view if RENDERTEMPLATE is not set protected function setContent() { $renderTemplate = App::get("RENDERTEMPLATE"); $controllerName = App::get("CONTROLLER"); $actionName = App::get("ACTION"); $targetTemplate = implode(DIRECTORY_SEPARATOR, [ $controllerName ? $controllerName : "home", $actionName ? $actionName : "index" ]) . ".htm"; App::set("CONTENT", $renderTemplate ? $renderTemplate : $targetTemplate); } //! Render the final view regarding the JSON constant protected function render() { $layout = App::get("JSON") === TRUE ? App::get("CONTENT") : "layout.htm"; App::log(App::SEVERITY_TRACE, "Render file $layout" . ($layout == "layout.htm" ? " with subset " . App::get("CONTENT") : "")); echo Template::instance()->render($layout); } }
Kagurame/osb
src/server_stream/core/class/route.php
PHP
gpl-3.0
3,601
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. An additional term under section # 7 of the GPL is included in the LICENSE file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta import json import csv import pytz from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template.response import TemplateResponse from django.core.urlresolvers import reverse from django.template import RequestContext from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import Group, Permission from django.shortcuts import render, get_object_or_404 from django.db.models import Q from django.views.decorators.cache import cache_page from Map.models import * from Map import utils, signals from core.utils import get_config from POS.models import POS # Decorator to check map permissions. Takes request and map_id # Permissions are 0 = None, 1 = View, 2 = Change # When used without a permission=x specification, requires Change access def require_map_permission(permission=2): def _dec(view_func): def _view(request, map_id, *args, **kwargs): current_map = get_object_or_404(Map, pk=map_id) if current_map.get_permission(request.user) < permission: raise PermissionDenied else: return view_func(request, map_id, *args, **kwargs) _view.__name__ = view_func.__name__ _view.__doc__ = view_func.__doc__ _view.__dict__ = view_func.__dict__ return _view return _dec @login_required @require_map_permission(permission=1) def get_map(request, map_id): """Get the map and determine if we have permissions to see it. If we do, then return a TemplateResponse for the map. If map does not exist, return 404. If we don't have permission, return PermissionDenied. """ current_map = get_object_or_404(Map, pk=map_id) context = { 'map': current_map, 'access': current_map.get_permission(request.user), } return TemplateResponse(request, 'map.html', context) @login_required @require_map_permission(permission=1) def map_checkin(request, map_id): # Initialize json return dict json_values = {} current_map = get_object_or_404(Map, pk=map_id) # AJAX requests should post a JSON datetime called loadtime # back that we use to get recent logs. if 'loadtime' not in request.POST: return HttpResponse(json.dumps({'error': "No loadtime"}), mimetype="application/json") time_string = request.POST['loadtime'] if time_string == 'null': return HttpResponse(json.dumps({'error': "No loadtime"}), mimetype="application/json") load_time = datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S.%f") load_time = load_time.replace(tzinfo=pytz.utc) if request.is_igb_trusted: dialog_html = _checkin_igb_trusted(request, current_map) if dialog_html is not None: json_values.update({'dialogHTML': dialog_html}) log_list = MapLog.objects.filter(timestamp__gt=load_time, visible=True, map=current_map) log_string = render_to_string('log_div.html', {'logs': log_list}) json_values.update({'logs': log_string}) return HttpResponse(json.dumps(json_values), mimetype="application/json") @login_required @require_map_permission(permission=1) def map_refresh(request, map_id): """ Returns an HttpResponse with the updated systemJSON for an asynchronous map refresh. """ if not request.is_ajax(): raise PermissionDenied current_map = get_object_or_404(Map, pk=map_id) if request.is_igb: char_cache_key = 'char_%s_location' % request.eve_charid old_location = cache.get(char_cache_key) if old_location: my_sys = get_object_or_404(System, pk=old_location[0]) my_sys.remove_active_pilot(request.eve_charid) my_sys.add_active_pilot(request.user.username, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) result = None result = [ datetime.strftime(datetime.now(pytz.utc), "%Y-%m-%d %H:%M:%S.%f"), utils.MapJSONGenerator(current_map, request.user).get_systems_json() ] # TODO update active pilots # get users current system #map_sys = get_object_or_404(MapSystem, pk=ms_id) # if this system is on the map, update. Otherwise, don't.. #remove_active_pilot(request.eve_charid) #map_sys.remove_active_pilot(request.eve_charid) #map_sys.add_active_pilot(request.user.username, request.eve_charid, # request.eve_charname, request.eve_shipname, # request.eve_shiptypename) return HttpResponse(json.dumps(result)) def log_movement(oldSys, newSys, charName, shipType, current_map, user): # get msid for oldsys # print oldSys # print newSys try: oldSysMapId = current_map.systems.filter(system=oldSys).all()[0] newSysMapId = current_map.systems.filter(system=newSys).all()[0] # BUG wh = Wormhole.objects.filter(top__in=[oldSysMapId,newSysMapId],bottom__in=[oldSysMapId,newSysMapId]).all()[0] # get current ship size #print shipType shipSize = Ship.objects.get(shipname=shipType).shipmass # get old mass if wh.mass_amount != None: wh.mass_amount = (wh.mass_amount + shipSize) else: wh.mass_amount = shipSize wh.save() except: print "Hole didn't exist yet" # jumplog jl = JumpLog.objects.create(user_id=user.id, char_name=charName, src=oldSys, dest=newSys) jl.save() def _checkin_igb_trusted(request, current_map): """ Runs the specific code for the case that the request came from an igb that trusts us, returns None if no further action is required, returns a string containing the html for a system add dialog if we detect that a new system needs to be added """ # XXX possibly where the logging needs to happen can_edit = current_map.get_permission(request.user) == 2 current_location = (request.eve_systemid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) char_cache_key = 'char_%s_location' % request.eve_charid old_location = cache.get(char_cache_key) result = None #print old_location if old_location != current_location: current_system = get_object_or_404(System, pk=current_location[0]) if old_location: old_system = get_object_or_404(System, pk=old_location[0]) old_system.remove_active_pilot(request.eve_charid) log_movement(old_system, current_system, request.eve_charname, request.eve_shiptypename, current_map, request.user) #XXX vtadd current_system.add_active_pilot(request.user.username, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) request.user.get_profile().update_location(current_system.pk, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) cache.set(char_cache_key, current_location, 60 * 5) #Conditions for the system to be automagically added to the map. if (can_edit and old_location and old_system in current_map and current_system not in current_map and not _is_moving_from_kspace_to_kspace(old_system, current_system) ): context = { 'oldsystem': current_map.systems.filter( system=old_system).all()[0], 'newsystem': current_system, 'wormholes': utils.get_possible_wh_types(old_system, current_system), } if request.POST.get('silent', 'false') != 'true': result = render_to_string('igb_system_add_dialog.html', context, context_instance=RequestContext(request)) else: new_ms = current_map.add_system(request.user, current_system, '', context['oldsystem']) k162_type = WormholeType.objects.get(name="K162") new_ms.connect_to(context['oldsystem'], k162_type, k162_type) result = 'silent' # maybe fixes else: cache.set(char_cache_key, current_location, 60 * 5) return result def _is_moving_from_kspace_to_kspace(old_system, current_system): """ returns whether we are moving through kspace :param old_system: :param current_system: :return: """ return old_system.is_kspace() and current_system.is_kspace() def get_system_context(ms_id, user): map_system = get_object_or_404(MapSystem, pk=ms_id) if map_system.map.get_permission(user) == 2: can_edit = True else: can_edit = False #If map_system represents a k-space system get the relevant KSystem object if map_system.system.is_kspace(): system = map_system.system.ksystem else: system = map_system.system.wsystem scan_threshold = datetime.now(pytz.utc) - timedelta( hours=int(get_config("MAP_SCAN_WARNING", None).value) ) interest_offset = int(get_config("MAP_INTEREST_TIME", None).value) interest_threshold = (datetime.now(pytz.utc) - timedelta(minutes=interest_offset)) scan_warning = system.lastscanned < scan_threshold if interest_offset > 0: interest = (map_system.interesttime and map_system.interesttime > interest_threshold) else: interest = map_system.interesttime # Include any SiteTracker fleets that are active st_fleets = map_system.system.stfleets.filter(ended=None).all() locations = cache.get('sys_%s_locations' % map_system.system.pk) if not locations: locations = {} return {'system': system, 'mapsys': map_system, 'scanwarning': scan_warning, 'isinterest': interest, 'stfleets': st_fleets, 'locations': locations, 'can_edit': can_edit} @login_required @require_map_permission(permission=2) def add_system(request, map_id): """ AJAX view to add a system to a current_map. Requires POST containing: topMsID: map_system ID of the parent map_system bottomSystem: Name of the new system topType: WormholeType name of the parent side bottomType: WormholeType name of the new side timeStatus: Wormhole time status integer value massStatus: Wormhole mass status integer value topBubbled: 1 if Parent side bubbled bottomBubbled: 1 if new side bubbled friendlyName: Friendly name for the new map_system """ if not request.is_ajax(): raise PermissionDenied try: # Prepare data current_map = Map.objects.get(pk=map_id) top_ms = MapSystem.objects.get(pk=request.POST.get('topMsID')) bottom_sys = System.objects.get( name=request.POST.get('bottomSystem') ) top_type = WormholeType.objects.get( name=request.POST.get('topType') ) bottom_type = WormholeType.objects.get( name=request.POST.get('bottomType') ) time_status = int(request.POST.get('timeStatus')) mass_status = int(request.POST.get('massStatus')) if request.POST.get('topBubbled', '0') != "0": top_bubbled = True else: top_bubbled = False if request.POST.get('bottomBubbled', '0') != "0": bottom_bubbled = True else: bottom_bubbled = False # Add System bottom_ms = current_map.add_system( request.user, bottom_sys, request.POST.get('friendlyName'), top_ms ) # Add Wormhole bottom_ms.connect_to(top_ms, top_type, bottom_type, top_bubbled, bottom_bubbled, time_status, mass_status) current_map.clear_caches() return HttpResponse() except ObjectDoesNotExist: return HttpResponse(status=400) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def remove_system(request, map_id, ms_id): """ Removes the supplied map_system from a map. """ system = get_object_or_404(MapSystem, pk=ms_id) system.remove_system(request.user) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_details(request, map_id, ms_id): """ Returns a html div representing details of the System given by ms_id in map map_id """ if not request.is_ajax(): raise PermissionDenied return render(request, 'system_details.html', get_system_context(ms_id, request.user)) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_menu(request, map_id, ms_id): """ Returns the html for system menu """ if not request.is_ajax(): raise PermissionDenied return render(request, 'system_menu.html', get_system_context(ms_id, request.user)) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_tooltips(request, map_id): """ Returns the system tooltips for map_id """ if not request.is_ajax(): raise PermissionDenied cache_key = 'map_%s_sys_tooltip' % map_id cached_tips = cache.get(cache_key) if not cached_tips: ms_list = MapSystem.objects.filter(map_id=map_id)\ .select_related('parent_wormhole', 'system__region')\ .iterator() new_tips = render_to_string('system_tooltip.html', {'map_systems': ms_list}, RequestContext(request)) cache.set(cache_key, new_tips, 60) return HttpResponse(new_tips) else: return HttpResponse(cached_tips) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def wormhole_tooltips(request, map_id): """Takes a POST request from AJAX with a Wormhole ID and renders the wormhole tooltip for that ID to response. """ if not request.is_ajax(): raise PermissionDenied cache_key = 'map_%s_wh_tooltip' % map_id cached_tips = cache.get(cache_key) if not cached_tips: cur_map = get_object_or_404(Map, pk=map_id) ms_list = MapSystem.objects.filter(map=cur_map).all() whs = Wormhole.objects.filter(top__in=ms_list).all() new_tips = render_to_string('wormhole_tooltip.html', {'wormholes': whs}, RequestContext(request)) cache.set(cache_key, new_tips, 60) return HttpResponse(new_tips) else: return HttpResponse(cached_tips) # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def collapse_system(request, map_id, ms_id): """ Mark the system as collapsed. """ if not request.is_ajax(): raise PermissionDenied map_sys = get_object_or_404(MapSystem, pk=ms_id) parent_wh = map_sys.parent_wormhole parent_wh.collapsed = True parent_wh.save() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def resurrect_system(request, map_id, ms_id): """ Unmark the system as collapsed. """ if not request.is_ajax(): raise PermissionDenied map_sys = get_object_or_404(MapSystem, pk=ms_id) parent_wh = map_sys.parent_wormhole parent_wh.collapsed = False parent_wh.save() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def mark_scanned(request, map_id, ms_id): """Takes a POST request from AJAX with a system ID and marks that system as scanned. """ if request.is_ajax(): map_system = get_object_or_404(MapSystem, pk=ms_id) map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() return HttpResponse() else: raise PermissionDenied # noinspection PyUnusedLocal @login_required() def manual_location(request, map_id, ms_id): """Takes a POST request form AJAX with a System ID and marks the user as being active in that system. """ if not request.is_ajax(): raise PermissionDenied user_locations = cache.get('user_%s_locations' % request.user.pk) if user_locations: old_location = user_locations.pop(request.user.pk, None) if old_location: old_sys = get_object_or_404(System, pk=old_location[0]) old_sys.remove_active_pilot(request.user.pk) map_sys = get_object_or_404(MapSystem, pk=ms_id) map_sys.system.add_active_pilot(request.user.username, request.user.pk, 'OOG Browser', 'Unknown', 'Unknown') request.user.get_profile().update_location(map_sys.system.pk, request.user.pk, 'OOG Browser', 'Unknown', 'Unknown') map_sys.map.clear_caches() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def set_interest(request, map_id, ms_id): """Takes a POST request from AJAX with an action and marks that system as having either utcnow or None as interesttime. The action can be either "set" or "remove". """ if request.is_ajax(): action = request.POST.get("action", "none") if action == "none": raise Http404 system = get_object_or_404(MapSystem, pk=ms_id) if action == "set": system.interesttime = datetime.now(pytz.utc) system.save() return HttpResponse() if action == "remove": system.interesttime = None system.save() return HttpResponse() system.map.clear_caches() return HttpResponse(status=418) else: raise PermissionDenied def _update_sig_from_tsv(signature, row): COL_SIG = 0 COL_SIG_TYPE = 3 COL_SIG_GROUP = 2 COL_SIG_SCAN_GROUP = 1 COL_SIG_STRENGTH = 4 COL_DISTANCE = 5 info = row[COL_SIG_TYPE] updated = False sig_type = None if (row[COL_SIG_SCAN_GROUP] == "Cosmic Signature" or row[COL_SIG_SCAN_GROUP] == "Cosmic Anomaly" ): try: sig_type = SignatureType.objects.get( longname=row[COL_SIG_GROUP]) except: sig_type = None else: sig_type = None if sig_type: updated = True if sig_type: signature.sigtype = sig_type signature.updated = updated or signature.updated if info: signature.info = info if signature.info == None: signature.info = '' return signature # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def bulk_sig_import(request, map_id, ms_id): """ GET gets a bulk signature import form. POST processes it, creating sigs with blank info and type for each sig ID detected. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) k = 0 if request.method == 'POST': reader = csv.reader(request.POST.get('paste', '').decode( 'utf-8').splitlines(), delimiter="\t") COL_SIG = 0 COL_STRENGTH = 4 for row in reader: # To prevent pasting of POSes into the sig importer, make sure # the strength column is present try: test_var = row[COL_STRENGTH] except IndexError: return HttpResponse('A valid signature paste was not found', status=400) if k < 75: sig_id = utils.convert_signature_id(row[COL_SIG]) sig = Signature.objects.get_or_create(sigid=sig_id, system=map_system.system)[0] sig = _update_sig_from_tsv(sig, row) sig.modified_by = request.user sig.save() signals.signature_update.send_robust(sig, user=request.user, map=map_system.map, signal_strength=row[COL_STRENGTH]) k += 1 map_system.map.add_log(request.user, "Imported %s signatures for %s(%s)." % (k, map_system.system.name, map_system.friendlyname), True) map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() return HttpResponse() else: return TemplateResponse(request, "bulk_sig_form.html", {'mapsys': map_system}) @login_required @require_map_permission(permission=2) def toggle_sig_owner(request, map_id, ms_id, sig_id=None): if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.toggle_ownership(request.user) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def edit_signature(request, map_id, ms_id, sig_id=None): """ GET gets a pre-filled edit signature form. POST updates the signature with the new information and returns a blank add form. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) # If the user can't edit signatures, return a blank response if map_system.map.get_permission(request.user) != 2: return HttpResponse() action = None if sig_id != None: signature = get_object_or_404(Signature, pk=sig_id) created = False if not signature.owned_by: signature.toggle_ownership(request.user) if request.method == 'POST': form = SignatureForm(request.POST) if form.is_valid(): ingame_id = utils.convert_signature_id(form.cleaned_data['sigid']) if sig_id == None: signature, created = Signature.objects.get_or_create( system=map_system.system, sigid=ingame_id) signature.sigid = ingame_id signature.updated = True signature.info = form.cleaned_data['info'] if request.POST['sigtype'] != '': sigtype = form.cleaned_data['sigtype'] else: sigtype = None signature.sigtype = sigtype signature.modified_by = request.user signature.save() map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() if created: action = 'Created' else: action = 'Updated' if signature.owned_by: signature.toggle_ownership(request.user) map_system.map.add_log(request.user, "%s signature %s in %s (%s)" % (action, signature.sigid, map_system.system.name, map_system.friendlyname)) signals.signature_update.send_robust(signature, user=request.user, map=map_system.map) else: return TemplateResponse(request, "edit_sig_form.html", {'form': form, 'system': map_system, 'sig': signature}) form = SignatureForm() if sig_id == None or action == 'Updated': return TemplateResponse(request, "add_sig_form.html", {'form': form, 'system': map_system}) else: return TemplateResponse(request, "edit_sig_form.html", {'form': SignatureForm(instance=signature), 'system': map_system, 'sig': signature}) # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=1) @cache_page(1) def get_signature_list(request, map_id, ms_id): """ Determines the proper escalationThreshold time and renders system_signatures.html """ if not request.is_ajax(): raise PermissionDenied system = get_object_or_404(MapSystem, pk=ms_id) escalation_downtimes = int(get_config("MAP_ESCALATION_BURN", request.user).value) return TemplateResponse(request, "system_signatures.html", {'system': system, 'downtimes': escalation_downtimes}) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def mark_signature_cleared(request, map_id, ms_id, sig_id): """ Marks a signature as having its NPCs cleared. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.clear_rats() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def escalate_site(request, map_id, ms_id, sig_id): """ Marks a site as having been escalated. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.escalate() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def activate_signature(request, map_id, ms_id, sig_id): """ Marks a site activated. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.activate() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def delete_signature(request, map_id, ms_id, sig_id): """ Deletes a signature. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) sig = get_object_or_404(Signature, pk=sig_id) sig.delete() map_system.map.add_log(request.user, "Deleted signature %s in %s (%s)." % (sig.sigid, map_system.system.name, map_system.friendlyname)) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def manual_add_system(request, map_id, ms_id): """ A GET request gets a blank add system form with the provided MapSystem as top system. The form is then POSTed to the add_system view. """ if request.is_igb_trusted: current_system = System.objects.get(name=request.eve_systemname) else: current_system = "" top_map_system = get_object_or_404(MapSystem, pk=ms_id) systems = System.objects.all() wormholes = WormholeType.objects.all() return render(request, 'add_system_box.html', {'topMs': top_map_system, 'sysList': systems, 'whList': wormholes,'newsystem': current_system}) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def edit_system(request, map_id, ms_id): """ A GET request gets the edit system dialog pre-filled with current information. A POST request saves the posted data as the new information. POST values are friendlyName, info, and occupied. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) if request.method == 'GET': occupied = map_system.system.occupied.replace("<br />", "\n") info = map_system.system.info.replace("<br />", "\n") return TemplateResponse(request, 'edit_system.html', {'mapsys': map_system, 'occupied': occupied, 'info': info} ) if request.method == 'POST': map_system.friendlyname = request.POST.get('friendlyName', '') if ( (map_system.system.info != request.POST.get('info', '')) or (map_system.system.occupied != request.POST.get('occupied', '')) ): map_system.system.info = request.POST.get('info', '') map_system.system.occupied = request.POST.get('occupied', '') map_system.system.save() map_system.save() map_system.map.add_log(request.user, "Edited System: %s (%s)" % (map_system.system.name, map_system.friendlyname)) return HttpResponse() raise PermissionDenied # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def edit_wormhole(request, map_id, wh_id): """ A GET request gets the edit wormhole dialog pre-filled with current info. A POST request saves the posted data as the new info. POST values are topType, bottomType, massStatus, timeStatus, topBubbled, and bottomBubbled. """ if not request.is_ajax(): raise PermissionDenied wormhole = get_object_or_404(Wormhole, pk=wh_id) if request.method == 'GET': return TemplateResponse(request, 'edit_wormhole.html', {'wormhole': wormhole} ) if request.method == 'POST': manualShipMassAdd = request.POST.get('massAdd',0) if manualShipMassAdd != "": addedMass = Ship.objects.get(shipname=manualShipMassAdd).shipmass wormhole.mass_amount = (wormhole.mass_amount + addedMass) wormhole.mass_status = int(request.POST.get('massStatus', 0)) wormhole.time_status = int(request.POST.get('timeStatus', 0)) wormhole.top_type = get_object_or_404( WormholeType, name=request.POST.get('topType', 'K162') ) wormhole.bottom_type = get_object_or_404( WormholeType, name=request.POST.get('bottomType', 'K162') ) wormhole.top_bubbled = request.POST.get('topBubbled', '1') == '1' wormhole.bottom_bubbled = request.POST.get('bottomBubbled', '1') == '1' wormhole.save() wormhole.map.add_log(request.user, ("Updated the wormhole between %s(%s) and %s(%s)." % (wormhole.top.system.name, wormhole.top.friendlyname, wormhole.bottom.system.name, wormhole.bottom.friendlyname))) return HttpResponse() raise PermissiondDenied @permission_required('Map.add_map') def create_map(request): """ This function creates a map and then redirects to the new map. """ if request.method == 'POST': form = MapForm(request.POST) if form.is_valid(): new_map = form.save() new_map.add_log(request.user, "Created the %s map." % new_map.name) new_map.add_system(request.user, new_map.root, "Root", None) return HttpResponseRedirect(reverse('Map.views.get_map', kwargs={'map_id': new_map.pk})) else: return TemplateResponse(request, 'new_map.html', {'form': form}) else: form = MapForm return TemplateResponse(request, 'new_map.html', {'form': form, }) def _sort_destinations(destinations): """ Takes a list of destination tuples and returns the same list, sorted in order of the jumps. """ results = [] onVal = 0 for dest in destinations: if len(results) == 0: results.append(dest) else: while onVal <= len(results): if onVal == len(results): results.append(dest) onVal = 0 break else: if dest[1] > results[onVal][1]: onVal += 1 else: results.insert(onVal, dest) onVal = 0 break return results # noinspection PyUnusedLocal @require_map_permission(permission=1) def destination_list(request, map_id, ms_id): """ Returns the destinations of interest tuple for K-space systems and a blank response for w-space systems. """ if not request.is_ajax(): raise PermissionDenied destinations = Destination.objects.filter(Q(user=None) | Q(user=request.user)) map_system = get_object_or_404(MapSystem, pk=ms_id) try: system = KSystem.objects.get(pk=map_system.system.pk) rf = utils.RouteFinder() result = [] for destination in destinations: result.append((destination.system, rf.route_length(system, destination.system) - 1, round(rf.ly_distance(system, destination.system), 3) )) except ObjectDoesNotExist: return HttpResponse() return render(request, 'system_destinations.html', {'system': system, 'destinations': _sort_destinations(result)}) # noinspection PyUnusedLocal def site_spawns(request, map_id, ms_id, sig_id): """ Returns the spawns for a given signature and system. """ sig = get_object_or_404(Signature, pk=sig_id) spawns = SiteSpawn.objects.filter(sigtype=sig.sigtype).all() if spawns[0].sysclass != 0: spawns = SiteSpawn.objects.filter(sigtype=sig.sigtype, sysclass=sig.system.sysclass).all() return render(request, 'site_spawns.html', {'spawns': spawns}) ######################### #Settings Views # ######################### @permission_required('Map.map_admin') def general_settings(request): """ Returns and processes the general settings section. """ npc_threshold = get_config("MAP_NPC_THRESHOLD", None) pvp_threshold = get_config("MAP_PVP_THRESHOLD", None) scan_threshold = get_config("MAP_SCAN_WARNING", None) interest_time = get_config("MAP_INTEREST_TIME", None) escalation_burn = get_config("MAP_ESCALATION_BURN", None) if request.method == "POST": scan_threshold.value = int(request.POST['scanwarn']) interest_time.value = int(request.POST['interesttimeout']) pvp_threshold.value = int(request.POST['pvpthreshold']) npc_threshold.value = int(request.POST['npcthreshold']) escalation_burn.value = int(request.POST['escdowntimes']) scan_threshold.save() interest_time.save() pvp_threshold.save() npc_threshold.save() escalation_burn.save() return HttpResponse() return TemplateResponse( request, 'general_settings.html', {'npcthreshold': npc_threshold.value, 'pvpthreshold': pvp_threshold.value, 'scanwarn': scan_threshold.value, 'interesttimeout': interest_time.value, 'escdowntimes': escalation_burn.value} ) @permission_required('Map.map_admin') def sites_settings(request): """ Returns the site spawns section. """ return TemplateResponse(request, 'spawns_settings.html', {'spawns': SiteSpawn.objects.all()}) @permission_required('Map.map_admin') def add_spawns(request): """ Adds a site spawn. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def delete_spawns(request, spawn_id): """ Deletes a site spawn. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_spawns(request, spawn_id): """ Alters a site spawn. """ return HttpResponse() def destination_settings(request, user=None): """ Returns the destinations section. """ if not user: dest_list = Destination.objects.filter(user=None) else: dest_list = Destination.objects.filter(Q(user=None) | Q(user=request.user)) return TemplateResponse(request, 'dest_settings.html', {'destinations': dest_list, 'user_context': user}) def add_destination(request, dest_user=None): """ Add a destination. """ if not dest_user and not request.user.has_perm('Map.map_admin'): raise PermissionDenied system = get_object_or_404(KSystem, name=request.POST['systemName']) Destination(system=system, user=dest_user).save() return HttpResponse() def add_personal_destination(request): """ Add a personal destination. """ return add_destination(request, dest_user=request.user) def delete_destination(request, dest_id): """ Deletes a destination. """ destination = get_object_or_404(Destination, pk=dest_id) if not request.user.has_perm('Map.map_admin') and not destination.user: raise PermissionDenied if destination.user and not request.user == destination.user: raise PermissionDenied destination.delete() return HttpResponse() @permission_required('Map.map_admin') def sigtype_settings(request): """ Returns the signature types section. """ return TemplateResponse(request, 'sigtype_settings.html', {'sigtypes': SignatureType.objects.all()}) # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_sigtype(request, sigtype_id): """ Alters a signature type. """ return HttpResponse() @permission_required('Map.map_admin') def add_sigtype(request): """ Adds a signature type. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def delete_sigtype(request, sigtype_id): """ Deletes a signature type. """ return HttpResponse() @permission_required('Map.map_admin') def map_settings(request, map_id): """ Returns and processes the settings section for a map. """ saved = False subject = get_object_or_404(Map, pk=map_id) if request.method == 'POST': name = request.POST.get('name', None) explicit_perms = request.POST.get('explicitperms', False) if not name: return HttpResponse('The map name cannot be blank', status=400) subject.name = name subject.explicitperms = explicit_perms for group in Group.objects.all(): MapPermission.objects.filter(group=group, map=subject).delete() setting = request.POST.get('map-%s-group-%s-permission' % ( subject.pk, group.pk), 0) if setting != 0: MapPermission(group=group, map=subject, access=setting).save() subject.save() saved = True groups = [] for group in Group.objects.all(): if MapPermission.objects.filter(map=subject, group=group).exists(): perm = MapPermission.objects.get(map=subject, group=group).access else: perm = 0 groups.append((group,perm)) return TemplateResponse(request, 'map_settings_single.html', {'map': subject, 'groups': groups, 'saved': saved}) @permission_required('Map.map_admin') def delete_map(request, map_id): """ Deletes a map. """ subject = get_object_or_404(Map, pk=map_id) subject.delete() return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_map(request, map_id): """ Alters a map. """ return HttpResponse('[]') @permission_required('Map.map_admin') def global_permissions(request): """ Returns and processes the global permissions section. """ if not request.is_ajax(): raise PermissionDenied group_list = [] admin_perm = Permission.objects.get(codename="map_admin") unrestricted_perm = Permission.objects.get(codename="map_unrestricted") add_map_perm = Permission.objects.get(codename="add_map") if request.method == "POST": for group in Group.objects.all(): if request.POST.get('%s_unrestricted' % group.pk, None): if unrestricted_perm not in group.permissions.all(): group.permissions.add(unrestricted_perm) else: if unrestricted_perm in group.permissions.all(): group.permissions.remove(unrestricted_perm) if request.POST.get('%s_add' % group.pk, None): if add_map_perm not in group.permissions.all(): group.permissions.add(add_map_perm) else: if add_map_perm in group.permissions.all(): group.permissions.remove(add_map_perm) if request.POST.get('%s_admin' % group.pk, None): if admin_perm not in group.permissions.all(): group.permissions.add(admin_perm) else: if admin_perm in group.permissions.all(): group.permissions.remove(admin_perm) return HttpResponse() for group in Group.objects.all(): entry = { 'group': group, 'admin': admin_perm in group.permissions.all(), 'unrestricted': unrestricted_perm in group.permissions.all(), 'add_map': add_map_perm in group.permissions.all() } group_list.append(entry) return TemplateResponse(request, 'global_perms.html', {'groups': group_list}) @require_map_permission(permission=2) def purge_signatures(request, map_id, ms_id): if not request.is_ajax(): raise PermissionDenied mapsys = get_object_or_404(MapSystem, pk=ms_id) if request.method == "POST": mapsys.system.signatures.all().delete() return HttpResponse() else: return HttpResponse(status=400)
viarr/eve-wspace
evewspace/Map/views.py
Python
gpl-3.0
43,116
<?php function check_htaccess_files($files) { global $config; $files_qty = count($files); foreach($files as $file_idx => $filename) { echo (($file_idx + 1)." / ". $files_qty ." ".$filename."\n"); $file_contents_string = file_get_contents($filename); if (!check_hash($file_contents_string, $filename)) { $pos = stripos($file_contents_string, "AddHandler"); if (false !== $pos) { $begin = $pos - 50; if ($begin < 0) $begin = 0; write_detection ("htaccess_addhandler.txt", $filename); write_detection ("htaccess_addhandler.txt", substr($file_contents_string, $begin, 100)); write_detection ("htaccess_addhandler.txt", "\n"); } $pos = stripos($file_contents_string, "AddType"); if (false !== $pos) { $begin = $pos - 50; if ($begin < 0) $begin = 0; write_detection ("htaccess_addtype.txt", $filename); write_detection ("htaccess_addtype.txt", substr($file_contents_string, $begin, 100)); write_detection ("htaccess_addtype.txt", "\n"); } } } return 1; } ?>
gohdan/DFC
includes/functions_htaccess.php
PHP
gpl-3.0
1,048
<h1>Manage admins</h1> <? if(isset($message) && $message != '') { ?> <p><b><i><?= $message ?></i></b></p> <? } ?> <form action="man_admin.php?action=add_admin" method="post"> Username: <input type="text" name="username"> <br><input type="submit" value="Promote user to admin"> </form> <table> <tr> <th>Username</th> <th>Delete</th> </tr> <? foreach($admins as $id => $admin) { ?> <tr> <td><?= $admin[0] ?></td> <td><a href="man_admin.php?action=delete&id=<?= $id ?>">Delete</a></td> </tr> <? } ?> </table>
uakfdotb/mastering
page/root/man_admin.php
PHP
gpl-3.0
515
# frozen_string_literal: true # Examples for Prawn basic concepts. # require_relative '../example_helper' filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename, page_size: 'FOLIO') do package 'basic_concepts' do |p| p.example 'creation', eval_source: false, full_source: true p.example 'origin' p.example 'cursor' p.example 'other_cursor_helpers' p.example 'adding_pages' p.example 'measurement' p.example 'view', eval_source: false, full_source: true p.intro do prose <<-TEXT This chapter covers the minimum amount of functionality you'll need to start using Prawn. If you are new to Prawn this is the first chapter to read. Once you are comfortable with the concepts shown here you might want to check the Basics section of the Graphics, Bounding Box and Text sections. The examples show: TEXT list( 'How to create new pdf documents in every possible way', 'Where the origin for the document coordinates is. What are Bounding '\ 'Boxes and how they interact with the origin', 'How the cursor behaves', 'How to start new pages', 'What the base unit for measurement and coordinates is and how to use '\ 'other convenient measures', "How to build custom view objects that use Prawn's DSL" ) end end end
BeGe78/esood
vendor/bundle/ruby/3.0.0/gems/prawn-2.4.0/manual/basic_concepts/basic_concepts.rb
Ruby
gpl-3.0
1,438
<?php /** * This class holds only some of the application related functions, * particularly the ones that are easier to code when addressed with an * application ID. */ class ApplicationsController extends AppController { /** * Determines whether users are authorized for actions * * @param array $user Contains information about the logged in user * @return boolean Whether the user is authorized for an action */ public function isAuthorized($user) { if (parent::isAuthorized($user)) { return true; } // teachers (and admins) only if ($user['role'] === 'teacher') { // check for ownership of absence $application_id = $this->request->params['pass'][0]; $this->Application->id = $application_id; $absence_id = $this->Application->field('absence_id'); return $this->Application->Absence->isOwnedBy($absence_id, $user['id']); } $this->Session->setFlash('You are not authorized for that action', 'error'); return false; } /** * Marks the applicant user as the fulfiller of an absence and deletes * any other applications for the same absence * * @param string $id The accepted application (references a user and absence) * @return void */ public function accept($id = null) { // auth module ensures ownership, so no need to check here $this->Application->id = $id; if (!$this->Application->exists()) { throw new NotFoundException(__('Invalid application')); } // give the sub the absence $application = $this->Application->findById($id); $applicant_id = $application['Application']['user_id']; $absence_id = $application['Application']['absence_id']; $this->Application->Absence->id = $absence_id; $this->Application->Absence->set('fulfiller_id', $applicant_id); $this->Application->Absence->save(); // clear the other applications if ($this->Application->deleteAll(array('Application.absence_id' => $absence_id))) { $this->Session->setFlash('Application accepted', 'success'); // generate notification $this->_create_notification('application_accepted', $absence_id, $applicant_id, $this->Auth->user('id')); } else { $this->Session->setFlash('The application could not be accepted', 'error'); } $this->redirect($this->referer()); } /** * Deletes an application for an absence * * @param string $id The application to delete * @return void */ public function reject($id = null) { // auth module ensures ownership, so no need to check here $this->Application->id = $id; if (!$this->Application->exists()) { throw new NotFoundException(__('Invalid application')); } // get information for the notification $application = $this->Application->findById($id); $applicant_id = $application['Application']['user_id']; $absence_id = $application['Application']['absence_id']; if ($this->Application->delete($id)) { $this->Session->setFlash('Application rejected', 'success'); // generate notification $this->_create_notification('application_rejected', $absence_id, $applicant_id, $this->Auth->user('id')); } else { $this->Session->setFlash('The application could not be rejected', 'error'); } $this->redirect($this->referer()); } }
jahabrewer/plentyofsubs
Controller/ApplicationsController.php
PHP
gpl-3.0
3,178
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Cancel an order * * @package order * @copyright 2013 Antonio Espinosa <aespinosa@teachnova.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once('../../../config.php'); require_once($CFG->dirroot . '/local/order/registry/lib.php'); require_once($CFG->dirroot . '/local/order/admin/lib.php'); $orderid = required_param('orderid', PARAM_INT); $return = optional_param('return', '/', PARAM_URL); $confirm = optional_param('confirm', 0, PARAM_BOOL); require_login(SITEID, false); local_order_require_capability('manage'); $returnurl = new moodle_url($return); $order = local_order::read($orderid); if (empty($order)) { redirect($returnurl, $this->get_string('error_order_not_found')); } $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $pageurl = new moodle_url('/local/order/admin/order_cancel.php', array('orderid' => $orderid, 'return' => $return, 'confirm' => $confirm)); $PAGE->set_url($pageurl); $PAGE->set_title(get_string('title_admin_order_cancel', 'local_order')); $PAGE->set_heading(get_string('heading_admin_order_cancel', 'local_order')); $confirmurl = new moodle_url('/local/order/admin/order_cancel.php', array('orderid' => $orderid, 'return' => $return, 'confirm' => 1)); if ($confirm and confirm_sesskey()) { // Validate order $errors = $order->cancel(); if (empty($errors)) { redirect($returnurl, get_string('order_cancelled', 'local_order')); } else { $errormsg = $this->get_string('error_order_can_not_cancel'); foreach ($errors as $error) { $errormsg .= $this->get_string('error_order_can_not_cancel_by_error', $error); } redirect($returnurl, $errormsg); } } else { // Ask for comfirmation echo $OUTPUT->header(); echo $OUTPUT->box_start('', 'local_order'); echo $OUTPUT->heading(get_string('heading_admin_order_cancel', 'local_order')); $formcontinue = new single_button($confirmurl, get_string('yes')); $formcancel = new single_button($returnurl, get_string('no'), 'get'); $strorder = new StdClass(); $strorder->uniqueid = $order->entry->uniqueid; echo $OUTPUT->confirm(get_string('confirmation_cancel', 'local_order', $strorder), $formcontinue, $formcancel); echo $OUTPUT->box_end(); echo $OUTPUT->footer(); }
Cohaerentis/moodle_local_order
admin/order_cancel.php
PHP
gpl-3.0
3,226
from datetime import datetime import uuid class Torrent(object): def __init__(self): self.tracker = None self.url = None self.title = None self.magnet = None self.seeders = None self.leechers = None self.size = None self.date = None self.details = None self.uuid = uuid.uuid4().hex self._remove = False @property def human_age(self): if self.date: age = datetime.now() - self.date return "%s days" % (int(age.total_seconds()/(60*60*24))) else: return "Unknown" @property def human_size(self): if self.size: if self.size > 1000000000: return "%.2f GB" % (self.size / 1000000000) elif self.size > 1000000: return "%.2f MB" % (self.size/1000000) else: return "%s KB" % (self.size/1000) @property def html_friendly_title(self): return self.title.replace('.', '.&#8203;').replace('[', '&#8203;[').replace(']', ']&#8203;') def __unicode__(self): return "%s Size: %s Seeders: %s Age: %s %s" % (self.title.ljust(60)[0:60], str(self.human_size).ljust(12), str(self.seeders).ljust(6), self.human_age, self.tracker) def __str__(self): return self.__unicode__()
stopstop/duvet
duvet/objects.py
Python
gpl-3.0
1,485
/* * Copyright (c) 2015 Brandon Lyon * * This file is part of Emerge Game Engine (Emerge) * * Emerge is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Emerge 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 Emerge. If not, see <http://www.gnu.org/licenses/>. */ package net.etherous.emerge.manager.config; import java.io.File; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @XmlAccessorType (XmlAccessType.FIELD) public class NativeNode { // Name of the native file (Required) @XmlAttribute (name = "name", required = true) String name; // The native's target platform (Optional. Can be inferred. May not be needed) @XmlAttribute (name = "plat", required = false) String platform; // The native's target architecture (Optional. Can be inferred. May not be needed) @XmlAttribute (name = "arch", required = false) String architecture; // File path to the native. Can be either absolute or relative to EMERGE_HOME (Optional. Can be inferred) @XmlAttribute (name = "path", required = false) String path; public NativeNode () { } public String getName () { return this.name; } public void setName (final String name) { this.name = name; } public String getPlatform () { return this.platform; } public void setPlatform (final String platform) { this.platform = platform; } public String getArchitecture () { return this.architecture; } public void setArchitecture (final String architecture) { this.architecture = architecture; } public String getPath () { return this.path; } public void setPath (final String path) { this.path = path; } public File getFile (final File defaultPath) { final String path = this.getPath (); if (path != null) return new File (path); return new File (defaultPath, this.name); } }
Etherous/Emerge
manager/src/main/java/net/etherous/emerge/manager/config/NativeNode.java
Java
gpl-3.0
2,483