From 9a02db39cb107527e8c3028d654ff72be686e93a Mon Sep 17 00:00:00 2001 From: Mandar Chitre Date: Sun, 14 Oct 2018 02:20:32 +0800 Subject: [PATCH 01/68] Fixed problem with calling platform.shutdown() from agents causing a deadlock --- VERSION | 2 +- src/main/java/org/arl/fjage/Agent.java | 15 ++++++++------- src/main/java/org/arl/fjage/Platform.java | 22 ++++++++++++++-------- 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/VERSION b/VERSION index 62a4b90c..8df077e0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.4.3-SNAPSHOT +1.5-SNAPSHOT diff --git a/src/main/java/org/arl/fjage/Agent.java b/src/main/java/org/arl/fjage/Agent.java index c675698e..fc515237 100644 --- a/src/main/java/org/arl/fjage/Agent.java +++ b/src/main/java/org/arl/fjage/Agent.java @@ -58,9 +58,9 @@ public class Agent implements Runnable, TimestampProvider { * Agent methods that take a timeout parameter. */ public static final long BLOCKING = -1; - + /////////////////////// Log levels - + protected static final Level ALL = Level.ALL; protected static final Level FINEST = Level.FINEST; protected static final Level FINER = Level.FINER; @@ -110,14 +110,14 @@ protected void init() { protected void shutdown() { // do nothing } - + /** * Called by the container if the agent terminates abnormally. This method may * be optionally overridden to provide special handling of malfunctioning agents. * This method is called before the shutdown() method is called to terminate * the agent. The behaviors of the agent are no longer active once this method * is called. - * + * * @param ex exception that caused the agent to die. */ protected void die(Throwable ex) { @@ -134,7 +134,7 @@ protected void die(Throwable ex) { public AgentID getAgentID() { return aid; } - + /** * Gets the name of the agent. * @@ -160,6 +160,7 @@ public void setLogLevel(Level level) { * {@link #wake()} method. */ protected synchronized void block() { + if (state == AgentState.FINISHING) return; if (!unblocked) { unblocked = true; if (restartBehaviors) return; @@ -311,7 +312,7 @@ public long nanoTime() { /** * Convenience method to create agent id for the named agent. - * + * * @return agent id for the named agent. */ public AgentID agent(String name) { @@ -672,7 +673,7 @@ public AgentID[] agentsForService(Enum service) { /** * Log a message at an INFO level. - * + * * @param msg message to log. */ public void println(Object msg) { diff --git a/src/main/java/org/arl/fjage/Platform.java b/src/main/java/org/arl/fjage/Platform.java index fb93058e..99bb5937 100644 --- a/src/main/java/org/arl/fjage/Platform.java +++ b/src/main/java/org/arl/fjage/Platform.java @@ -109,10 +109,16 @@ public void start() { * Terminates all containers on the platform. */ public void shutdown() { - for (Container c: containers) { - if (c != null) c.shutdown(); - } - running = false; + Thread t = new Thread() { + @Override + public void run() { + for (Container c: containers) { + if (c != null) c.shutdown(); + } + running = false; + } + }; + t.start(); } /** @@ -152,7 +158,7 @@ public String getHostname() { /** * Gets a network interface that the platform is bound to. - * + * * @return bound network interface, null if no binding. */ public NetworkInterface getNetworkInterface() { @@ -161,16 +167,16 @@ public NetworkInterface getNetworkInterface() { /** * Sets the network interface to bind to. - * + * * @param name name of the network interface. */ public void setNetworkInterface(String name) throws SocketException { nif = NetworkInterface.getByName(name); } - + /** * Sets the network interface to bind to. - * + * * @param nif network interface. */ public void setNetworkInterface(NetworkInterface nif) { From abb5d65d1fcbff9b48f458f817f5719ebd35b046 Mon Sep 17 00:00:00 2001 From: Mandar Chitre Date: Sun, 14 Oct 2018 02:21:17 +0800 Subject: [PATCH 02/68] Removed deprecated rmi package --- src/main/java/org/arl/fjage/rmi/Gateway.java | 330 ----------------- .../org/arl/fjage/rmi/MasterContainer.java | 244 ------------- .../org/arl/fjage/rmi/RemoteContainer.java | 116 ------ .../arl/fjage/rmi/RemoteContainerProxy.java | 105 ------ .../org/arl/fjage/rmi/SlaveContainer.java | 338 ------------------ src/main/java/org/arl/fjage/rmi/package.html | 5 - 6 files changed, 1138 deletions(-) delete mode 100644 src/main/java/org/arl/fjage/rmi/Gateway.java delete mode 100644 src/main/java/org/arl/fjage/rmi/MasterContainer.java delete mode 100644 src/main/java/org/arl/fjage/rmi/RemoteContainer.java delete mode 100644 src/main/java/org/arl/fjage/rmi/RemoteContainerProxy.java delete mode 100644 src/main/java/org/arl/fjage/rmi/SlaveContainer.java delete mode 100644 src/main/java/org/arl/fjage/rmi/package.html diff --git a/src/main/java/org/arl/fjage/rmi/Gateway.java b/src/main/java/org/arl/fjage/rmi/Gateway.java deleted file mode 100644 index f9f18197..00000000 --- a/src/main/java/org/arl/fjage/rmi/Gateway.java +++ /dev/null @@ -1,330 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.rmi; - -import java.io.IOException; -import java.rmi.NotBoundException; -import org.arl.fjage.*; - -/** - * Gateway to communicate with agents from Java classes. Only agents in a master - * or slave container can be accessed using this gateway. - * - * @deprecated As of release 1.4, replaced by {@link org.arl.fjage.remote.Gateway}. - * - * @author Mandar Chitre - */ -@Deprecated -public class Gateway { - - /////////////////////// Constants - - /** - * Represents a non-blocking timeout of 0 seconds. Can be used with all - * Agent methods that take a timeout parameter. - */ - public static final long NON_BLOCKING = 0; - - /** - * Represents a blocking timeout of infinite time. Can be used with all - * Agent methods that take a timeout parameter. - */ - public static final long BLOCKING = -1; - - //////////// Private attributes - - private SlaveContainer container; - private Agent agent; - - /////////// Interface methods - - /** - * Creates a gateway connecting to a specified master container. The platform specified - * is this call should not be started previously, and will be automatically started - * by the gateway. - * - * @param platform platform to use - * @param url URL of master platform to connect to. - */ - public Gateway(Platform platform, String url) throws IOException, NotBoundException { - init(platform, url); - } - - /** - * Creates a gateway connecting to a specified master container. - * - * @param url URL of master platform to connect to. - */ - public Gateway(String url) throws IOException, NotBoundException { - Platform platform = new RealTimePlatform(); - init(platform, url); - } - - private void init(Platform platform, String url) throws IOException, NotBoundException { - container = new SlaveContainer(platform, "Gateway@"+hashCode(), url); - agent = new Agent() { - private Message rsp; - private Object sync = new Object(); - @Override - public Message receive(final MessageFilter filter, final long timeout) { - if (Thread.currentThread().getId() == tid) return super.receive(filter, timeout); - synchronized (sync) { - rsp = null; - try { - add(new OneShotBehavior() { - @Override - public void action() { - rsp = receive(filter, timeout); - synchronized (sync) { - sync.notify(); - } - } - }); - sync.wait(); - } catch (InterruptedException ex) { - // ignore exception - } - return rsp; - } - } - }; - container.add("GatewayAgent@"+hashCode(), agent); - platform.start(); - } - - /** - * Closes the gateway. The gateway functionality may not longer be accessed after - * this method is called. - */ - public void shutdown() { - if (container != null) container.shutdown(); - agent = null; - container = null; - } - - /** - * Sends a message to the recipient indicated in the message. The recipient - * may be an agent or a topic. - * - * @param m message to be sent. - */ - public void send(final Message m) { - agent.add(new OneShotBehavior() { - @Override - public void action() { - agent.send(m); - } - }); - } - - /** - * Returns a message received by the gateway and matching the given filter. - * This method blocks until timeout if no message available. - * - * @param filter message filter. - * @param timeout timeout in milliseconds. - * @return received message matching the filter, null on timeout. - */ - public synchronized Message receive(final MessageFilter filter, final long timeout) { - return agent.receive(filter, timeout); - } - - /** - * Returns a message received by the gateway. This method is non-blocking. - * - * @return received message, null if none available. - */ - public final Message receive() { - return receive((MessageFilter)null, 0); - } - - /** - * Returns a message received by the agent. This method blocks until timeout if no - * message available. - * - * @param timeout timeout in milliseconds. - * @return received message, null on timeout. - */ - public Message receive(long timeout) { - return receive((MessageFilter)null, timeout); - } - - /** - * Returns a message of a given class received by the gateway. This method is non-blocking. - * - * @param cls the class of the message of interest. - * @return received message of the given class, null if none available. - */ - public Message receive(final Class cls) { - return receive(cls, 0); - } - - /** - * Returns a message of a given class received by the gateway. This method blocks until - * timeout if no message available. - * - * @param cls the class of the message of interest. - * @param timeout timeout in milliseconds. - * @return received message of the given class, null on timeout. - */ - public Message receive(final Class cls, long timeout) { - return receive(new MessageFilter() { - @Override - public boolean matches(Message m) { - return cls.isInstance(m); - } - }, timeout); - } - - /** - * Returns a response message received by the gateway. This method is non-blocking. - * - * @param m original message to which a response is expected. - * @return received response message, null if none available. - */ - public Message receive(final Message m) { - return receive(m, 0); - } - - /** - * Returns a response message received by the gateway. This method blocks until - * timeout if no message available. - * - * @param m original message to which a response is expected. - * @param timeout timeout in milliseconds. - * @return received response message, null on timeout. - */ - public Message receive(final Message m, long timeout) { - return receive(new MessageFilter() { - private String mid = m.getMessageID(); - @Override - public boolean matches(Message m) { - String s = m.getInReplyTo(); - if (s == null) return false; - return s.equals(mid); - } - }, timeout); - } - - /** - * Sends a request and waits for a response. This method blocks until timeout - * if no response is received. - * - * @param msg message to send. - * @param timeout timeout in milliseconds. - * @return received response message, null on timeout. - */ - public Message request(Message msg, long timeout) { - send(msg); - return receive(msg, timeout); - } - - /** - * Returns an object representing the named topic. - * - * @param topic name of the topic. - * @return object representing the topic. - */ - public AgentID topic(String topic) { - return agent.topic(topic); - } - - /** - * Returns an object representing the named topic. - * - * @param topic name of the topic. - * @return object representing the topic. - */ - public AgentID topic(Enum topic) { - return agent.topic(topic); - } - - /** - * Returns an object representing the notification topic for an agent. - * - * @param topic agent to get notification topic for. - * @return object representing the topic. - */ - public AgentID topic(AgentID topic) { - return agent.topic(topic); - } - - /** - * Subscribes the gateway to receive all messages sent to the given topic. - * - * @param topic the topic to subscribe to. - * @return true if the subscription is successful, false otherwise. - */ - public boolean subscribe(AgentID topic) { - return agent.subscribe(topic); - } - - /** - * Unsubscribes the gateway from a given topic. - * - * @param topic the topic to unsubscribe. - * @return true if the unsubscription is successful, false otherwise. - */ - public boolean unsubscribe(AgentID topic) { - return agent.unsubscribe(topic); - } - - /** - * Finds an agent that provides a named service. If multiple agents are registered - * to provide a given service, any of the agents' id may be returned. - * - * @param service the named service of interest. - * @return an agent id for an agent that provides the service. - */ - public AgentID agentForService(String service) { - return container.agentForService(service); - } - - /** - * Finds an agent that provides a named service. If multiple agents are registered - * to provide a given service, any of the agents' id may be returned. - * - * @param service the named service of interest. - * @return an agent id for an agent that provides the service. - */ - public AgentID agentForService(Enum service) { - return container.agentForService(service.getClass().getName()+"."+service.toString()); - } - - /** - * Finds all agents that provides a named service. - * - * @param service the named service of interest. - * @return an array of agent ids representing all agent that provide the service. - */ - public AgentID[] agentsForService(String service) { - return container.agentsForService(service); - } - - /** - * Finds all agents that provides a named service. - * - * @param service the named service of interest. - * @return an array of agent ids representing all agent that provide the service. - */ - public AgentID[] agentsForService(Enum service) { - return container.agentsForService(service.getClass().getName()+"."+service.toString()); - } - - ////////////// Private methods - - @Override - public void finalize() { - shutdown(); - } - -} - diff --git a/src/main/java/org/arl/fjage/rmi/MasterContainer.java b/src/main/java/org/arl/fjage/rmi/MasterContainer.java deleted file mode 100644 index 406a0750..00000000 --- a/src/main/java/org/arl/fjage/rmi/MasterContainer.java +++ /dev/null @@ -1,244 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.rmi; - -import java.io.IOException; -import java.rmi.*; -import java.rmi.server.UnicastRemoteObject; -import java.rmi.registry.LocateRegistry; -import java.util.*; -import java.util.concurrent.*; -import java.util.logging.Level; - -import org.arl.fjage.*; - -/** - * Master container supporting multiple remote slave containers. Agents in linked - * master and slave containers function as if they were in the same container, - * i.e., are able to communicate with each other through messaging, topics and - * directory services. - * - * @deprecated As of release 1.4, replaced by {@link org.arl.fjage.remote.MasterContainer}. - * - * @author Mandar Chitre - */ -@Deprecated -public class MasterContainer extends Container implements RemoteContainer { - - ////////////// Private attributes - - private Map slaves = new ConcurrentHashMap(); - private String myurl = null; - private RemoteContainerProxy proxy = null; - private int containerPort = 0; - - ////////////// Constructors - - /** - * Creates a master container. - * - * @param platform platform on which the container runs. - */ - public MasterContainer(Platform platform) throws IOException { - super(platform); - enableRMI(); - } - - /** - * Creates a master container, runs its container stub on a specified port. - * - * @param platform platform on which the container runs. - * @param port port on which the container's stub runs. - */ - public MasterContainer(Platform platform, int port) throws IOException { - super(platform); - containerPort = port; - enableRMI(); - } - - /** - * Creates a named master container. - * - * @param platform platform on which the container runs. - * @param name name of the container. - */ - public MasterContainer(Platform platform, String name) throws IOException { - super(platform, name); - enableRMI(); - } - - /** - * Creates a named master container, runs its container stub on a specified port. - * - * @param platform platform on which the container runs. - * @param name of the container. - * @param port port on which the container's stub runs. - */ - public MasterContainer(Platform platform, String name, int port) throws IOException { - super(platform, name); - containerPort = port; - enableRMI(); - } - - /////////////// Container interface methods to override - - @Override - public String getURL() { - return myurl; - } - - @Override - protected boolean isDuplicate(AgentID aid) { - if (super.isDuplicate(aid)) return true; - if (slaves.size() > 0) { - Iterator it = slaves.values().iterator(); - while (it.hasNext()) { - RemoteContainer c = it.next(); - try { - if (c.containsAgent(aid)) return true; - } catch (RemoteException ex) { - logRemoteException(ex); - it.remove(); - } - } - } - return false; - } - - @Override - public boolean send(Message m) { - return send(m, true); - } - - @Override - public boolean send(Message m, boolean relay) { - if (!running) return false; - AgentID aid = m.getRecipient(); - if (aid == null) return false; - if (aid.isTopic()) { - super.send(m, false); - if (!relay) return true; - if (slaves.size() > 0) { - Iterator it = slaves.values().iterator(); - while (it.hasNext()) { - RemoteContainer c = it.next(); - try { - c.send(m, false); - } catch (RemoteException ex) { - logRemoteException(ex); - it.remove(); - } - } - } - return true; - } else { - if (super.send(m, false)) return true; - if (!relay) return false; - if (slaves.size() > 0) { - Iterator it = slaves.values().iterator(); - while (it.hasNext()) { - RemoteContainer c = it.next(); - try { - if (c.send(m, false)) return true; - } catch (RemoteException ex) { - logRemoteException(ex); - it.remove(); - } - } - } - return false; - } - } - - @Override - public void shutdown() { - if (!running) return; - super.shutdown(); - if (slaves.size() > 0) { - for (RemoteContainer c: slaves.values()) { - try { - c.shutdown(); - } catch (RemoteException ex) { - logRemoteException(ex); - } - } - slaves.clear(); - } - if (proxy != null) { - try { - UnicastRemoteObject.unexportObject(proxy, true); - Naming.unbind(myurl); - } catch (Exception ex) { - logRemoteException(ex); - } finally { - proxy = null; - } - } - } - - @Override - public boolean attachSlave(String url) { - try { - RemoteContainer c = (RemoteContainer)Naming.lookup(url); - slaves.put(url, c); - log.info("Slave "+url+" attached"); - return true; - } catch (Exception ex) { - logRemoteException(ex); - return false; - } - } - - @Override - public boolean detachSlave(String url) { - if (slaves.remove(url) != null) { - log.info("Slave "+url+" detached"); - return true; - } - return false; - } - - @Override - public String toString() { - String s = getClass().getName()+"@"+name; - s += "/master/"+platform; - return s; - } - - /////////////// Private methods - - private void enableRMI() throws IOException { - int port = platform.getPort(); - String hostname = platform.getHostname(); - System.setProperty("java.rmi.server.hostname", hostname); - myurl = "//"+hostname+":"+port+"/fjage/"+name; - log.info("Container URL: "+myurl); - log.info("Starting local registry..."); - try { - LocateRegistry.createRegistry(port); - } catch (java.rmi.server.ExportException ex) { - log.info("Could not create registry, perhaps one is already running!"); - } - if (containerPort != 0) { - proxy = new RemoteContainerProxy(this, containerPort); - } - else { - proxy = new RemoteContainerProxy(this); - } - Naming.rebind(myurl, proxy); - } - - private void logRemoteException(Exception ex) { - //log.log(Level.WARNING, "Call to slave container failed", ex); - log.info("Lost connection to slave container: "+ex.getMessage()); - } - -} diff --git a/src/main/java/org/arl/fjage/rmi/RemoteContainer.java b/src/main/java/org/arl/fjage/rmi/RemoteContainer.java deleted file mode 100644 index b287a3a3..00000000 --- a/src/main/java/org/arl/fjage/rmi/RemoteContainer.java +++ /dev/null @@ -1,116 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.rmi; - -import java.rmi.*; -import org.arl.fjage.*; - -/** - * RMI interface for remote containers. - * - * @deprecated As of release 1.4, this interface is no longer valid. - * - * @author Mandar Chitre - */ -@Deprecated -public interface RemoteContainer extends Remote { - - /** - * Gets the remote access URL of the container. - * - * @return the URL of the container. - */ - public String getURL() throws RemoteException; - - /** - * Attaches a slave container to the master container. Implemented only by - * master containers. - * - * @param url URL of the slave container. - * @return true on success, false otherwise. - */ - public boolean attachSlave(String url) throws RemoteException; - - /** - * Detaches a slave container from the master container. Implemented only by - * master containers. - * - * @param url URL of the slave container. - * @return true on success, false otherwise. - */ - public boolean detachSlave(String url) throws RemoteException; - - /** - * Checks if an agent exists in the container. - * - * @param aid agent id to check. - * @return true if the agent exists, false otherwise. - */ - public boolean containsAgent(AgentID aid) throws RemoteException; - - /** - * Registers an agent in the directory service as a provider of a named service. - * - * @param aid id of agent providing the service. - * @param service name of the service. - * @return true on success, false on failure. - */ - public boolean register(AgentID aid, String service) throws RemoteException; - - /** - * Deregisters an agent as a provider of a specific service. - * - * @param aid id of agent to deregister. - * @param service name of the service to deregister. - * @return true on success, false on failure. - */ - public boolean deregister(AgentID aid, String service) throws RemoteException; - - /** - * Deregisters an agent as a provider of all services. - * - * @param aid id of agent to deregister. - */ - public void deregister(AgentID aid) throws RemoteException; - - /** - * Finds an agent providing a named service. - * - * @param service name of the service. - * @return agent id for service provider, null if none found. - */ - public AgentID agentForService(String service) throws RemoteException; - - /** - * Finds all agents providing a named service. - * - * @param service name of the service. - * @return an array of agent ids for service providers, null if none found. - */ - public AgentID[] agentsForService(String service) throws RemoteException; - - /** - * Sends a message. The message is sent to the recipient specified in the - * message. - * - * @param m message to deliver - * @param relay enable relaying to associated remote containers. - * @return true if delivered, false otherwise. - */ - public boolean send(Message m, boolean relay) throws RemoteException; - - /** - * Terminates the container and all agents in it. - */ - public void shutdown() throws RemoteException; - -} - diff --git a/src/main/java/org/arl/fjage/rmi/RemoteContainerProxy.java b/src/main/java/org/arl/fjage/rmi/RemoteContainerProxy.java deleted file mode 100644 index 3b4fe3c8..00000000 --- a/src/main/java/org/arl/fjage/rmi/RemoteContainerProxy.java +++ /dev/null @@ -1,105 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.rmi; - -import java.rmi.RemoteException; -import java.rmi.server.UnicastRemoteObject; -import org.arl.fjage.*; - -/** - * RMI proxy to avoid having {@link MasterContainer} and {@link SlaveContainer} - * implement the {@link java.rmi.server.UnicastRemoteObject} interface. - * - * @deprecated As of release 1.4, this class is no longer valid. - * @see org.arl.fjage.Container - * - * @author Mandar Chitre - */ -@Deprecated -public class RemoteContainerProxy extends UnicastRemoteObject implements RemoteContainer { - - private static final long serialVersionUID = 1L; - - /////////// Private attributes - - private RemoteContainer delegate; - - /////////// Constructor - - RemoteContainerProxy(RemoteContainer delegate) throws RemoteException { - super(); - this.delegate = delegate; - } - - RemoteContainerProxy(RemoteContainer delegate, int port) throws RemoteException { - super(port); - this.delegate = delegate; - } - - /////////// Delegated methods - - @Override - public String getURL() throws RemoteException { - return delegate.getURL(); - } - - @Override - public boolean attachSlave(String url) throws RemoteException { - return delegate.attachSlave(url); - } - - @Override - public boolean detachSlave(String url) throws RemoteException { - return delegate.detachSlave(url); - } - - @Override - public boolean containsAgent(AgentID aid) throws RemoteException { - return delegate.containsAgent(aid); - } - - @Override - public boolean register(AgentID aid, String service) throws RemoteException { - return delegate.register(aid, service); - } - - @Override - public boolean deregister(AgentID aid, String service) throws RemoteException { - return delegate.deregister(aid, service); - } - - @Override - public void deregister(AgentID aid) throws RemoteException { - delegate.deregister(aid); - } - - @Override - public AgentID agentForService(String service) throws RemoteException { - return delegate.agentForService(service); - } - - @Override - public AgentID[] agentsForService(String service) throws RemoteException { - return delegate.agentsForService(service); - } - - @Override - public boolean send(Message m, boolean relay) throws RemoteException { - return delegate.send(m, relay); - } - - @Override - public void shutdown() throws RemoteException { - delegate.shutdown(); - } - -} - diff --git a/src/main/java/org/arl/fjage/rmi/SlaveContainer.java b/src/main/java/org/arl/fjage/rmi/SlaveContainer.java deleted file mode 100644 index 087b5aaa..00000000 --- a/src/main/java/org/arl/fjage/rmi/SlaveContainer.java +++ /dev/null @@ -1,338 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.rmi; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.Socket; -import java.net.URL; -import java.rmi.*; -import java.rmi.server.UnicastRemoteObject; -import java.rmi.registry.LocateRegistry; -import java.util.logging.Level; - -import org.arl.fjage.*; - -/** - * Slave container attached to a master container. Agents in linked - * master and slave containers function as if they were in the same container, - * i.e., are able to communicate with each other through messaging, topics and - * directory services. - * - * @deprecated As of release 1.4, replaced by {@link org.arl.fjage.remote.SlaveContainer}. - * - * @author Mandar Chitre - */ -@Deprecated -public class SlaveContainer extends Container implements RemoteContainer { - - ////////////// Private attributes - - private RemoteContainer master; - private String myurl = null; - private String masterUrl = null; - private RemoteContainerProxy proxy = null; - private int containerPort = 0; - - ////////////// Constructors - - /** - * Creates a slave container. - * - * @param platform platform on which the container runs. - * @param url URL of master platform to connect to. - */ - public SlaveContainer(Platform platform, String url) throws IOException, NotBoundException { - super(platform); - if (platform.getNetworkInterface() == null) determineNetworkInterface(url); - enableRMI(true); - masterUrl = url; - attach(url); - } - - - /** - * Creates a slave container, runs its container stub on a specified port. - * - * @param platform platform on which the container runs. - * @param port port on which the container's stub runs. - * @param url URL of master platform to connect to. - */ - public SlaveContainer(Platform platform, int port, String url) throws IOException, NotBoundException { - super(platform); - if (platform.getNetworkInterface() == null) determineNetworkInterface(url); - containerPort = port; - enableRMI(true); - masterUrl = url; - attach(url); - } - - /** - * Creates a named slave container. - * - * @param platform platform on which the container runs. - * @param name name of the container. - * @param url URL of master platform to connect to. - */ - public SlaveContainer(Platform platform, String name, String url) throws IOException, NotBoundException { - super(platform, name); - if (platform.getNetworkInterface() == null) determineNetworkInterface(url); - enableRMI(true); - masterUrl = url; - attach(url); - } - - /** - * Creates a named slave container, runs its container stub on a specified port. - * - * @param platform platform on which the container runs. - * @param name name of the container. - * @param port port on which the container's stub runs. - * @param url URL of master platform to connect to. - */ - public SlaveContainer(Platform platform, String name, int port, String url) throws IOException, NotBoundException { - super(platform, name); - if (platform.getNetworkInterface() == null) determineNetworkInterface(url); - containerPort = port; - enableRMI(true); - masterUrl = url; - attach(url); - } - - /////////////// Container interface methods to override - - @Override - public String getURL() { - return myurl; - } - - @Override - protected boolean isDuplicate(AgentID aid) { - if (super.isDuplicate(aid)) return true; - try { - if (master == null && !reattach()) return false; - if (master.containsAgent(aid)) return true; - } catch (RemoteException ex) { - logRemoteException(ex); - } - return false; - } - - @Override - public boolean send(Message m) { - return send(m, true); - } - - @Override - public boolean send(Message m, boolean relay) { - if (!running) return false; - if (master == null && !reattach()) return false; - AgentID aid = m.getRecipient(); - if (aid == null) return false; - if (aid.isTopic()) { - if (relay) { - try { - return master.send(m, true); - } catch (RemoteException ex) { - logRemoteException(ex); - } - } - super.send(m, false); - return true; - } else { - if (super.send(m, false)) return true; - if (!relay) return false; - try { - return master.send(m, true); - } catch (RemoteException ex) { - logRemoteException(ex); - return false; - } - } - } - - @Override - public synchronized boolean register(AgentID aid, String service) { - if (master == null && !reattach()) return false; - try { - return master.register(aid, service); - } catch (RemoteException ex) { - logRemoteException(ex); - return false; - } - } - - @Override - public synchronized AgentID agentForService(String service) { - if (master == null && !reattach()) return null; - try { - return master.agentForService(service); - } catch (RemoteException ex) { - logRemoteException(ex); - return null; - } - } - - @Override - public synchronized AgentID[] agentsForService(String service) { - if (master == null && !reattach()) return null; - try { - return master.agentsForService(service); - } catch (RemoteException ex) { - logRemoteException(ex); - return null; - } - } - - @Override - public synchronized boolean deregister(AgentID aid, String service) { - if (master == null && !reattach()) return false; - try { - return master.deregister(aid, service); - } catch (RemoteException ex) { - logRemoteException(ex); - return false; - } - } - - @Override - public synchronized void deregister(AgentID aid) { - if (master == null && !reattach()) return; - try { - master.deregister(aid); - } catch (RemoteException ex) { - logRemoteException(ex); - } - } - - @Override - public void shutdown() { - super.shutdown(); - try { - if (master != null) master.detachSlave(myurl); - } catch (RemoteException ex) { - log.warning("Unable to detach from master during shutdown, perhaps master has already shutdown"); - } - disableRMI(); - } - - @Override - public boolean attachSlave(String url) { - throw new UnsupportedOperationException("Cannot attach slave to slave"); - } - - @Override - public boolean detachSlave(String url) { - throw new UnsupportedOperationException("Cannot detach slave from slave"); - } - - @Override - public String getState() { - if (!running) return "Not running"; - if (master == null) return "Running, connecting to "+masterUrl+"..."; - return "Running, connected to "+masterUrl; - } - - @Override - public String toString() { - String s = getClass().getName()+"@"+name; - s += "/slave/"+platform; - return s; - } - - /////////////// Private methods - - private void determineNetworkInterface(String url) { - try { - URL u = new URL("http:"+url); - String server = u.getHost(); - int port = u.getPort(); - Socket s = new Socket(server, port); - InetAddress a = s.getLocalAddress(); - s.close(); - NetworkInterface nif = NetworkInterface.getByInetAddress(a); - log.info("Binding to network interface "+nif.getDisplayName()); - if (nif != null) platform.setNetworkInterface(nif); - } catch (Exception ex) { - log.warning("Could not determine network interface to bind to: "+ex.getMessage()); - } - } - - private void enableRMI(boolean localNamingOK) throws IOException { - int port = platform.getPort(); - String hostname = platform.getHostname(); - System.setProperty("java.rmi.server.hostname", hostname); - myurl = "//"+hostname+":"+port+"/fjage/"+name; - log.info("Container URL: "+myurl); - try { - // test if a registry is already running - Naming.lookup(myurl); - } catch (ConnectException ex) { - // if not, perhaps start one... - log.info("Unable to find RMI registry..."); - if (localNamingOK) { - log.info("Starting local RMI registry!"); - LocateRegistry.createRegistry(port); - } - } catch (NotBoundException e) { - // do nothing, since this is fine - } - if (containerPort != 0) { - proxy = new RemoteContainerProxy(this, containerPort); - } - else { - proxy = new RemoteContainerProxy(this); - } - Naming.rebind(myurl, proxy); - } - - private void disableRMI() { - try { - if (proxy != null) UnicastRemoteObject.unexportObject(proxy, true); - Naming.unbind(myurl); - } catch (Exception ex) { - // ignore - } - master = null; - proxy = null; - } - - private void attach(String url) throws IOException, NotBoundException { - master = (RemoteContainer)Naming.lookup(url); - if (!master.attachSlave(myurl)) { - master = null; - throw new RemoteException("Master cannot bind to us"); - } - log.info("Attached to "+url); - } - - private void logRemoteException(Exception ex) { - //log.log(Level.WARNING, "Call to master container failed", ex); - log.warning("Lost connection to master: "+ex.toString()); - disableRMI(); - } - - private boolean reattach() { - log.info("Trying to reconnect..."); - try { - enableRMI(false); - attach(masterUrl); - } catch (Exception ex1) { - log.info("Connection failed: "+ex1.toString()); - disableRMI(); - return false; - } - return true; - } - -} - diff --git a/src/main/java/org/arl/fjage/rmi/package.html b/src/main/java/org/arl/fjage/rmi/package.html deleted file mode 100644 index 752a8a64..00000000 --- a/src/main/java/org/arl/fjage/rmi/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -Support for multi-container deployments using RMI (deprecated). - - From 42df786d0ef4ba9daa00a617745664063a5254ed Mon Sep 17 00:00:00 2001 From: Mandar Chitre Date: Sun, 14 Oct 2018 02:23:29 +0800 Subject: [PATCH 03/68] Refactoring of shell package (WIP) --- .../arl/fjage/shell/BaseGroovyScript.groovy | 609 ------------------ .../arl/fjage/shell/ConcurrentBinding.java | 35 - .../org/arl/fjage/shell/GroovyBoot.java | 106 --- .../arl/fjage/shell/GroovyScriptEngine.java | 313 --------- .../org/arl/fjage/shell/ProtectedBinding.java | 35 - .../org/arl/fjage/shell/SwingShell.groovy | 429 ------------ .../groovy/org/arl/fjage/shell/fshrc.groovy | 330 ---------- .../org/arl/fjage/shell/ConsoleShell.java | 269 +++----- .../org/arl/fjage/shell/EchoScriptEngine.java | 95 +++ .../org/arl/fjage/shell/MessageListener.java | 29 - .../java/org/arl/fjage/shell/OutputShell.java | 85 --- .../java/org/arl/fjage/shell/OutputType.java | 23 - .../org/arl/fjage/shell/ScriptEngine.java | 73 ++- .../java/org/arl/fjage/shell/Services.java | 17 +- src/main/java/org/arl/fjage/shell/Shell.java | 44 +- .../java/org/arl/fjage/shell/ShellAgent.java | 335 +--------- .../java/org/arl/fjage/shell/TcpShell.java | 292 --------- src/main/java/org/arl/fjage/shell/Term.java | 85 --- .../java/org/arl/fjage/shell/WebServer.java | 130 ---- .../java/org/arl/fjage/shell/WebShell.java | 284 -------- 20 files changed, 298 insertions(+), 3320 deletions(-) delete mode 100644 src/main/groovy/org/arl/fjage/shell/BaseGroovyScript.groovy delete mode 100644 src/main/groovy/org/arl/fjage/shell/ConcurrentBinding.java delete mode 100644 src/main/groovy/org/arl/fjage/shell/GroovyBoot.java delete mode 100644 src/main/groovy/org/arl/fjage/shell/GroovyScriptEngine.java delete mode 100644 src/main/groovy/org/arl/fjage/shell/ProtectedBinding.java delete mode 100644 src/main/groovy/org/arl/fjage/shell/SwingShell.groovy delete mode 100644 src/main/groovy/org/arl/fjage/shell/fshrc.groovy create mode 100644 src/main/java/org/arl/fjage/shell/EchoScriptEngine.java delete mode 100644 src/main/java/org/arl/fjage/shell/MessageListener.java delete mode 100644 src/main/java/org/arl/fjage/shell/OutputShell.java delete mode 100644 src/main/java/org/arl/fjage/shell/OutputType.java delete mode 100644 src/main/java/org/arl/fjage/shell/TcpShell.java delete mode 100644 src/main/java/org/arl/fjage/shell/Term.java delete mode 100644 src/main/java/org/arl/fjage/shell/WebServer.java delete mode 100644 src/main/java/org/arl/fjage/shell/WebShell.java diff --git a/src/main/groovy/org/arl/fjage/shell/BaseGroovyScript.groovy b/src/main/groovy/org/arl/fjage/shell/BaseGroovyScript.groovy deleted file mode 100644 index 83490533..00000000 --- a/src/main/groovy/org/arl/fjage/shell/BaseGroovyScript.groovy +++ /dev/null @@ -1,609 +0,0 @@ -/****************************************************************************** - -Copyright (c) 2013, Mandar Chitre - -This file is part of fjage which is released under Simplified BSD License. -See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause -for full license details. - -******************************************************************************/ - -package org.arl.fjage.shell; - -import java.util.logging.*; -import org.arl.fjage.*; -import org.codehaus.groovy.control.customizers.ImportCustomizer - -/** - * Methods and attributes available to Groovy scripts. - * - * @author Mandar Chitre - */ -@SuppressWarnings("rawtypes") -abstract class BaseGroovyScript extends Script { - - // Log levels - static final Level ALL = Level.ALL; - static final Level FINEST = Level.FINEST; - static final Level FINER = Level.FINER; - static final Level FINE = Level.FINE; - static final Level INFO = Level.INFO; - static final Level WARNING = Level.WARNING; - static final Level SEVERE = Level.SEVERE; - static final Level OFF = Level.OFF; - - /** - * Initializes the script. Creates a 'log' variable to allow logging from the - * script. Also creates a 'doc' hash map in suppport of 'help' commands. - */ - void _init_() { - Logger log = Logger.getLogger(getClass().getName()); - log.setLevel(Level.ALL); - Binding binding = getBinding(); - binding.setVariable('log', log); - def doc = [:]; - binding.setVariable('doc', doc); - } - - /** - * Update list of default import classes/packages. - * - * @param name name of class or package to import. - */ - def shellImport(String name) { - Binding binding = getBinding(); - if (binding.hasVariable('imports')) { - ImportCustomizer imports = binding.getVariable('imports'); - if (name.endsWith('.*')) imports.addStarImport(name[0..-3]); - else imports.addImport(name); - } - } - - /** - * Do not use include(), use shellImport() instead. - */ - def include(String name) { - throw new FjageError('include() has been superceded by shellImport()'); - } - - /** - * Subscribe to notifications from a given topic. - * - * @param topic - */ - void subscribe(topic) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - a.subscribe(topic); - } - } - - /** - * Unsubscribe from notifications from a given topic. - * - * @param topic - */ - void unsubscribe(topic) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - a.unsubscribe(topic); - } - } - - /** - * Terminates the current platform and all containers and agents on it. - */ - void shutdown() { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - Platform p = a.getPlatform(); - p.shutdown(); - } - } - - def getShutdown() { - shutdown(); - return null; - } - - /** - * Lists all the agents. - * - * @return a string representation of all agents. - */ - String ps() { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - Container c = a.getContainer(); - AgentID[] agentIDs = c.getAgents(); - StringBuffer s = new StringBuffer(); - boolean first = true; - for (AgentID aid: agentIDs) { - if (!first) s.append('\n'); - s.append(aid); - Agent a1 = c.getAgent(aid); - if (a1) s.append(": ${a1.class.name} - ${a1.state}"); - else s.append(': REMOTE'); - first = false; - } - return s.toString(); - } - return null; - } - - String getPs() { - return ps(); - } - - /** - * Represents an agent identifier for a named agent. - * - * @param name name of the agent. - * @return agent identifier. - */ - AgentID agent(String name) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - return a.agent(name); - } - return new AgentID(name); - } - - /** - * Lists all the services, along with a list of agents that provide them. - * - * @return a string representation of all services. - */ - String services() { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - Container c = a.getContainer(); - String[] svc = c.getServices(); - StringBuffer s = new StringBuffer(); - boolean first = true; - for (String s1: svc) { - if (!first) s.append('\n'); - s.append(s1); - AgentID[] aids = agentsForService(s1) - if (aids) { - s.append(':') - aids.each { - s.append(' ') - s.append(it) - } - } - first = false; - } - return s.toString(); - } - return null; - } - - String getServices() { - return services(); - } - - /** - * Returns an agent identifier for a specified service. - * - * @param service service of interest. - * @return agent identifier. - */ - AgentID agentForService(def service) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - return a.agentForService(service); - } - return null; - } - - /** - * Returns agent identifiers for a specified service. - * - * @param service service of interest. - * @return array of agent identifiers. - */ - AgentID[] agentsForService(def service) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - return a.agentsForService(service); - } - return null; - } - - /** - * Represents a topic for a specified agent or a named topic. - * - * @param s name of topic or agent identifier. - * @return topic. - */ - AgentID topic(s) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - return a.topic(s); - } - return null; - } - - /** - * Represents a named notification topic for a specified agent. - * - * @param aid agent identifier. - * @param s name of the notification topic. - * @return topic. - */ - AgentID topic(aid, s) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - return a.topic(aid, s); - } - return null; - } - - /** - * Sets current log level for a specified logger. - * - * @param name name of the logger. - * @param level log level. - */ - void logLevel(String name, Level level) { - Logger logger = Logger.getLogger(name); - logger.setLevel(level); - } - - /** - * Sets current log level for the root logger. - * - * @param level log level. - */ - void logLevel(Level level) { - Logger logger = Logger.getLogger(''); - logger.setLevel(level); - } - - /** - * Delay execution by a given time. - * - * @param millis time in milliseconds. - */ - void delay(long millis) { - Binding binding = getBinding(); - if (binding.hasVariable('agent')) { - Agent a = binding.getVariable('agent'); - Platform p = a.getPlatform(); - p.delay(millis); - } - else Thread.sleep(millis); - } - - /** - * Lists variables in current binding. - * - * @return string representation of all variables. - */ - String who() { - Binding binding = getBinding(); - StringBuffer s = new StringBuffer(); - binding.getVariables().each { - if (s.length() > 0) s << ', '; - s << it.key; - } - return s.toString(); - } - - String getWho() { - return who(); - } - - /** - * Display on console. This method clears the current line - * and displays output on it, followed by a newline. - * - * @param s object to display. - */ - void println(def x) { - Binding binding = getBinding(); - if (binding.hasVariable('out')) { - def out = binding.getVariable('out'); - if (out != null) out.println(x.toString(), OutputType.OUTPUT); - } - } - - /** - * Display on console. This method clears the current line - * and displays output on it, followed by a newline. - * - * @param s object to display. - * @param type type of output to display. - */ - void println(def x, OutputType type) { - Binding binding = getBinding(); - if (binding.hasVariable('out')) { - def out = binding.getVariable('out'); - if (out != null) out.println(x.toString(), type); - } - } - - /** - * Do not use print(), use println() only. - */ - void print(def x) { - throw new FjageError("print() not supported, use println() instead"); - } - - /** - * Run a nested Groovy script. - * - * @param name filename of the script to run. - * @param args arguments to pass to the script. - */ - void run(String name, Object... args) { - Binding binding = getBinding(); - def oldScript = binding.getVariable('script'); - def oldArgs = binding.getVariable('args'); - try { - if (binding.hasVariable('groovy')) { - GroovyShell groovy = binding.getVariable('groovy'); - groovy.getClassLoader().clearCache(); - if (!name.endsWith('.groovy') && !name.startsWith("cls://")) name += '.groovy'; - if (name.startsWith('res:/')) { - InputStream inp = groovy.class.getResourceAsStream(name.substring(5)); - if (inp == null) throw new FileNotFoundException(name+" not found"); - binding.setVariable('script', name); - groovy.run(new InputStreamReader(inp), name, args as String[]); - } else if (name.startsWith("cls://")) { - Class From d8e7a33e259aa0a3c5413dc350f4f865c60f948a Mon Sep 17 00:00:00 2001 From: Mandar Chitre Date: Wed, 17 Oct 2018 01:50:36 +0800 Subject: [PATCH 21/68] Implemented websock connector and a basic web shell --- build.gradle | 1 + etc/initrc.groovy | 11 +- fjage.sh | 10 +- .../org/arl/fjage/connectors/WebServer.java | 189 + .../fjage/connectors/WebSocketConnector.java | 187 + .../org/arl/fjage/web/shell/hterm_all.js | 20811 ++++++++++++++++ .../org/arl/fjage/web/shell/index.html | 55 + 7 files changed, 21257 insertions(+), 7 deletions(-) create mode 100644 src/main/java/org/arl/fjage/connectors/WebServer.java create mode 100644 src/main/java/org/arl/fjage/connectors/WebSocketConnector.java create mode 100644 src/main/resources/org/arl/fjage/web/shell/hterm_all.js create mode 100644 src/main/resources/org/arl/fjage/web/shell/index.html diff --git a/build.gradle b/build.gradle index 49061d3f..184f8484 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,7 @@ dependencies { compile 'uk.com.robust-it:cloning:1.9.0' compile 'org.eclipse.jetty:jetty-server:9.4.12.v20180830' compile 'org.eclipse.jetty:jetty-servlet:9.4.12.v20180830' + compile 'org.eclipse.jetty.websocket:websocket-server:9.4.12.v20180830' compile 'com.google.code.gson:gson:2.8.2' compile 'com.fazecast:jSerialComm:2.1.1' testCompile 'junit:junit:4.11' diff --git a/etc/initrc.groovy b/etc/initrc.groovy index a2fb98b3..753437f0 100644 --- a/etc/initrc.groovy +++ b/etc/initrc.groovy @@ -1,8 +1,9 @@ import org.arl.fjage.* import org.arl.fjage.remote.* import org.arl.fjage.shell.* +import org.arl.fjage.connectors.* -boolean gui = System.properties.getProperty('fjage.gui') == 'true' +boolean web = System.properties.getProperty('fjage.web') == 'true' int port = 5081 try { port = Integer.parseInt(System.properties.getProperty('fjage.port')) @@ -22,7 +23,13 @@ if (devname != null) { platform = new RealTimePlatform() if (devname == null) container = new MasterContainer(platform, port) else container = new MasterContainer(platform, port, devname, baud, 'N81') -shell = new ShellAgent(new ConsoleShell(), new GroovyScriptEngine()) +if (web) { + WebServer.getInstance(8080).add("/shell", "/org/arl/fjage/web/shell") + Connector conn = new WebSocketConnector(8080, "/shell/ws") + shell = new ShellAgent(new ConsoleShell(conn), new GroovyScriptEngine()) +} else { + shell = new ShellAgent(new ConsoleShell(), new GroovyScriptEngine()) +} shell.addInitrc("cls://org.arl.fjage.shell.fshrc"); container.add 'shell', shell platform.start() diff --git a/fjage.sh b/fjage.sh index de57bf3c..63301abd 100755 --- a/fjage.sh +++ b/fjage.sh @@ -1,7 +1,7 @@ #!/bin/bash # # Usage: -# ./fjage.sh [-gui] [-port port] [-baud baud] [-rs232 devname] +# ./fjage.sh [-web] [-port port] [-baud baud] [-rs232 devname] CLASSPATH=.`find build/libs -name *.jar -exec /bin/echo -n :'{}' \;` export CLASSPATH=$CLASSPATH:samples @@ -12,13 +12,13 @@ if [ $(expr "$(uname -s)" : 'CYGWIN.*') -gt 0 ];then fi # process command line options -GUI=false +WEB=false OPT1= while [[ $1 == -* ]] do OPT=$1 - if [ $OPT = "-gui" ]; then - GUI=true + if [ $OPT = "-web" ]; then + WEB=true elif [ $OPT = "-port" ]; then shift OPT1="$OPT1 -Dfjage.port=$1" @@ -36,4 +36,4 @@ do done mkdir -p logs -java -cp "$CLASSPATH" -Dfjage.gui=$GUI $OPT1 org.arl.fjage.shell.GroovyBoot $@ etc/initrc.groovy +java -cp "$CLASSPATH" -Dfjage.web=$WEB $OPT1 org.arl.fjage.shell.GroovyBoot $@ etc/initrc.groovy diff --git a/src/main/java/org/arl/fjage/connectors/WebServer.java b/src/main/java/org/arl/fjage/connectors/WebServer.java new file mode 100644 index 00000000..5f514e51 --- /dev/null +++ b/src/main/java/org/arl/fjage/connectors/WebServer.java @@ -0,0 +1,189 @@ +/****************************************************************************** + +Copyright (c) 2013, Mandar Chitre + +This file is part of fjage which is released under Simplified BSD License. +See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause +for full license details. + +******************************************************************************/ + +package org.arl.fjage.connectors; + +import java.util.*; +import java.io.*; +import javax.servlet.http.*; +import javax.servlet.ServletException; +import org.eclipse.jetty.util.log.*; +import org.eclipse.jetty.server.*; +import org.eclipse.jetty.server.handler.*; +import org.eclipse.jetty.servlet.ServletContextHandler; + +/** + * Web server instance manager. + */ +public class WebServer { + + //////// static attributes and methods + + private static Map servers = new HashMap(); + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(WebServer.class.getName()); + + static { + // disable Jetty logging (except warnings) + System.setProperty("org.eclipse.jetty.LEVEL", "WARN"); + Log.setLog(new Logger() { + @Override public String getName() { return "[jetty]"; } + @Override public Logger getLogger(String name) { return this; } + @Override public boolean isDebugEnabled() { return false; } + @Override public void warn(String msg, Object... args) { log.warning(msg); } + @Override public void warn(Throwable t) { log.warning(t.toString()); } + @Override public void warn(String msg, Throwable thrown) { log.warning(msg); } + @Override public void info(String msg, Object... args) { } + @Override public void info(Throwable thrown) { } + @Override public void info(String msg, Throwable thrown) { } + @Override public void setDebugEnabled(boolean enabled) { } + @Override public void debug(String msg, Object... args) { } + @Override public void debug(String msg, long x) { } + @Override public void debug(Throwable thrown) { } + @Override public void debug(String msg, Throwable thrown) { } + @Override public void ignore(Throwable ignored) { } + }); + } + + /** + * Gets an instance of a web server running on the specified port. If an instance is not + * already available, a new one is created. + * + * @param port HTTP port number. + */ + public static WebServer getInstance(int port) { + synchronized (servers) { + WebServer svr = servers.get(port); + if (svr == null) svr = new WebServer(port); + return svr; + } + } + + //////// instance attributes and methods + + protected Server server; + protected ContextHandlerCollection contexts; + protected Map staticContexts = new HashMap(); + protected boolean started; + protected int port; + + protected WebServer(int port) { + this.port = port; + server = new Server(port); + if (port > 0) servers.put(port, this); + contexts = new ContextHandlerCollection(); + server.setHandler(contexts); + started = false; + } + + /** + * Gets the port number that the web server is running on. + * + * @return TCP port number. + */ + public int getPort() { + return port; + } + + /** + * Starts the web server. + */ + public void start() { + if (started) return; + try { + server.start(); + server.setStopAtShutdown(true); + log.info("Started web server on port "+port); + started = true; + } catch (Exception ex) { + log.warning(ex.toString()); + } + } + + /** + * Stops the web server. Once this method is called, the server cannot be restarted. + */ + public void stop() { + if (server == null) return; + try { + log.info("Stopping web server"); + server.stop(); + started = false; + } catch (Exception ex) { + log.warning(ex.toString()); + } + server = null; + contexts = null; + } + + + /** + * Adds a context handler to the server. Context handlers should be added before the web + * server is started. + * + * @param handler context handler. + */ + public void add(ContextHandler handler) { + log.info("Adding web context: "+handler.getContextPath()); + contexts.addHandler(handler); + } + + /** + * Removes a context handler. + * + * @param handler context handler to remove. + */ + public void remove(ContextHandler handler) { + contexts.removeHandler(handler); + if (contexts.getHandlers().length == 0) stop(); + } + + /** + * Adds a context to serve static documents. + * + * @param context context path. + * @param resource resource path. + */ + public void add(String context, String resource) { + ContextHandler handler = new ContextHandler(context); + handler.setHandler(new AbstractHandler() { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + if (target.equals("/")) target = "/index.html"; + log.info("GET "+resource+target); + InputStream in = getClass().getResourceAsStream(resource+target); + if (in == null) return; + String s = new Scanner(in, "UTF8").useDelimiter("\\Z").next(); + if (target.endsWith("html")) response.setContentType("text/html;charset=utf-8"); + else if (target.endsWith("css")) response.setContentType("text/css;charset=utf-8"); + else if (target.endsWith("js")) response.setContentType("application/javascript;charset=utf-8"); + else response.setContentType("text/plain;charset=utf-8"); + response.setStatus(HttpServletResponse.SC_OK); + baseRequest.setHandled(true); + response.getWriter().println(s); + } + }); + staticContexts.put(context, handler); + add(handler); + } + + /** + * Removes a context serving static documents. + * + * @param context context path. + */ + public void remove(String context) { + ContextHandler handler = staticContexts.get(context); + if (handler == null) return; + staticContexts.remove(context); + remove(handler); + } + +} diff --git a/src/main/java/org/arl/fjage/connectors/WebSocketConnector.java b/src/main/java/org/arl/fjage/connectors/WebSocketConnector.java new file mode 100644 index 00000000..6be61658 --- /dev/null +++ b/src/main/java/org/arl/fjage/connectors/WebSocketConnector.java @@ -0,0 +1,187 @@ +/****************************************************************************** + +Copyright (c) 2013, Mandar Chitre + +This file is part of fjage which is released under Simplified BSD License. +See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause +for full license details. + +******************************************************************************/ + +package org.arl.fjage.connectors; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.Logger; +import org.eclipse.jetty.websocket.api.Session; +import org.eclipse.jetty.websocket.server.WebSocketHandler; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.websocket.servlet.*; +import org.eclipse.jetty.websocket.api.annotations.*; + +/** + * Web socket connector. + */ +public class WebSocketConnector implements Connector, WebSocketCreator { + + protected String name; + protected WebServer server; + protected ContextHandler handler; + protected List wsHandlers = Collections.synchronizedList(new ArrayList()); + protected OutputThread outThread = null; + protected PseudoInputStream pin = new PseudoInputStream(); + protected PseudoOutputStream pout = new PseudoOutputStream(); + protected Logger log = Logger.getLogger(getClass().getName()); + + /** + * Create a web socket connector and add it to a web server running on a + * given port. If a web server isn't already created, this will start the + * web server. + */ + public WebSocketConnector(int port, String context) { + server = WebServer.getInstance(port); + handler = new ContextHandler(context); + handler.setHandler(new WebSocketHandler() { + @Override + public void configure(WebSocketServletFactory factory) { + factory.setCreator(WebSocketConnector.this); + } + }); + server.add(handler); + server.start(); + outThread = new OutputThread(); + outThread.start(); + name = "ws:["+port+":"+context+"]"; + } + + @Override + public Object createWebSocket​(ServletUpgradeRequest req, ServletUpgradeResponse resp) { + return new WSHandler(); + } + + @Override + public String getName() { + return name; + } + + @Override + public InputStream getInputStream() { + return pin; + } + + @Override + public OutputStream getOutputStream() { + return pout; + } + + @Override + public boolean isReliable() { + return true; + } + + @Override + public boolean waitOutputCompletion(long timeout) { + return true; + } + + @Override + public void close() { + outThread.close(); + outThread = null; + server.remove(handler); + server = null; + handler = null; + pin.close(); + pout.close(); + pin = null; + pout = null; + } + + @Override + public String toString() { + return name; + } + + // thread to monitor incoming data on output stream and write to TCP clients + + private class OutputThread extends Thread { + + OutputThread() { + setName(getClass().getSimpleName()); + setDaemon(true); + } + + @Override + public void run() { + while (true) { + int c = pout.read(); + if (c < 0) break; + synchronized(wsHandlers) { + for (WSHandler t: wsHandlers) + t.write(c); + } + } + } + + void close() { + if (pout != null) pout.close(); + } + + } + + // servlets to manage web socket connections + + @WebSocket(maxIdleTime = Integer.MAX_VALUE) + public class WSHandler { + + Session session = null; + + @OnWebSocketConnect + public void onConnect(Session session) { + log.info("New connection from "+session.getRemoteAddress()); + this.session = session; + wsHandlers.add(this); + } + + @OnWebSocketClose + public void onClose(int statusCode, String reason) { + log.info("Connection from "+session.getRemoteAddress()+" closed"); + session = null; + wsHandlers.remove(this); + } + + @OnWebSocketError + public void onError(Throwable t) { + log.warning(t.getMessage()); + } + + @OnWebSocketMessage + public void onMessage(String message) { + byte[] buf = message.getBytes(); + for (int i = 0; i < buf.length; i++) { + int c = buf[i]; + if (c < 0) c += 256; + try { + pin.write(c); + } catch (IOException ex) { + // do nothing + } + } + } + + void write(int c) { + try { + if (session != null) { + byte[] buf = new byte[1]; + buf[0] = (byte)c; + session.getRemote().sendString(new String(buf)); + } + } catch (IOException e) { + log.warning(e.getMessage()); + } + } + + } + +} diff --git a/src/main/resources/org/arl/fjage/web/shell/hterm_all.js b/src/main/resources/org/arl/fjage/web/shell/hterm_all.js new file mode 100644 index 00000000..d7452659 --- /dev/null +++ b/src/main/resources/org/arl/fjage/web/shell/hterm_all.js @@ -0,0 +1,20811 @@ +// This file was generated by libdot/bin/concat.sh. +// It has been marked read-only for your safety. Rather than +// edit it directly, please modify one of these source files. +// +// libdot/js/lib.js +// libdot/js/lib_polyfill.js +// libdot/js/lib_array.js +// libdot/js/lib_colors.js +// libdot/js/lib_f.js +// libdot/js/lib_i18n.js +// libdot/js/lib_message_manager.js +// libdot/js/lib_preference_manager.js +// libdot/js/lib_resource.js +// libdot/js/lib_storage.js +// libdot/js/lib_storage_chrome.js +// libdot/js/lib_storage_local.js +// libdot/js/lib_storage_memory.js +// libdot/js/lib_test_manager.js +// libdot/js/lib_utf8.js +// libdot/third_party/wcwidth/lib_wc.js + +'use strict'; + +// SOURCE FILE: libdot/js/lib.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +if (typeof lib != 'undefined') + throw new Error('Global "lib" object already exists.'); + +var lib = {}; + +/** + * Map of "dependency" to ["source", ...]. + * + * Each dependency is a object name, like "lib.fs", "source" is the url that + * depends on the object. + */ +lib.runtimeDependencies_ = {}; + +/** + * List of functions that need to be invoked during library initialization. + * + * Each element in the initCallbacks_ array is itself a two-element array. + * Element 0 is a short string describing the owner of the init routine, useful + * for debugging. Element 1 is the callback function. + */ +lib.initCallbacks_ = []; + +/** + * Records a runtime dependency. + * + * This can be useful when you want to express a run-time dependency at + * compile time. It is not intended to be a full-fledged library system or + * dependency tracker. It's just there to make it possible to debug the + * deps without running all the code. + * + * Object names are specified as strings. For example... + * + * lib.rtdep('lib.colors', 'lib.PreferenceManager'); + * + * Object names need not be rooted by 'lib'. You may use this to declare a + * dependency on any object. + * + * The client program may call lib.ensureRuntimeDependencies() at startup in + * order to ensure that all runtime dependencies have been met. + * + * @param {string} var_args One or more objects specified as strings. + */ +lib.rtdep = function(var_args) { + var source; + + try { + throw new Error(); + } catch (ex) { + var stackArray = ex.stack.split('\n'); + // In Safari, the resulting stackArray will only have 2 elements and the + // individual strings are formatted differently. + if (stackArray.length >= 3) { + source = stackArray[2].replace(/^\s*at\s+/, ''); + } else { + source = stackArray[1].replace(/^\s*global code@/, ''); + } + } + + for (var i = 0; i < arguments.length; i++) { + var path = arguments[i]; + if (path instanceof Array) { + lib.rtdep.apply(lib, path); + } else { + var ary = this.runtimeDependencies_[path]; + if (!ary) + ary = this.runtimeDependencies_[path] = []; + ary.push(source); + } + } +}; + +/** + * Ensures that all runtime dependencies are met, or an exception is thrown. + * + * Every unmet runtime dependency will be logged to the JS console. If at + * least one dependency is unmet this will raise an exception. + */ +lib.ensureRuntimeDependencies_ = function() { + var passed = true; + + for (var path in lib.runtimeDependencies_) { + var sourceList = lib.runtimeDependencies_[path]; + var names = path.split('.'); + + // In a document context 'window' is the global object. In a worker it's + // called 'self'. + var obj = (window || self); + for (var i = 0; i < names.length; i++) { + if (!(names[i] in obj)) { + console.warn('Missing "' + path + '" is needed by', sourceList); + passed = false; + break; + } + + obj = obj[names[i]]; + } + } + + if (!passed) + throw new Error('Failed runtime dependency check'); +}; + +/** + * Register an initialization function. + * + * The initialization functions are invoked in registration order when + * lib.init() is invoked. Each function will receive a single parameter, which + * is a function to be invoked when it completes its part of the initialization. + * + * @param {string} name A short descriptive name of the init routine useful for + * debugging. + * @param {function(function)} callback The initialization function to register. + * @return {function} The callback parameter. + */ +lib.registerInit = function(name, callback) { + lib.initCallbacks_.push([name, callback]); + return callback; +}; + +/** + * Initialize the library. + * + * This will ensure that all registered runtime dependencies are met, and + * invoke any registered initialization functions. + * + * Initialization is asynchronous. The library is not ready for use until + * the onInit function is invoked. + * + * @param {function()} onInit The function to invoke when initialization is + * complete. + * @param {function(*)} opt_logFunction An optional function to send + * initialization related log messages to. + */ +lib.init = function(onInit, opt_logFunction) { + var ary = lib.initCallbacks_; + + var initNext = function() { + if (ary.length) { + var rec = ary.shift(); + if (opt_logFunction) + opt_logFunction('init: ' + rec[0]); + rec[1](lib.f.alarm(initNext)); + } else { + onInit(); + } + }; + + if (typeof onInit != 'function') + throw new Error('Missing or invalid argument: onInit'); + + lib.ensureRuntimeDependencies_(); + + setTimeout(initNext, 0); +}; +// SOURCE FILE: libdot/js/lib_polyfill.js +// Copyright 2017 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Polyfills for ES2016+ features we want to use. + */ + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart +if (!String.prototype.padStart) { + String.prototype.padStart = function(targetLength, padString) { + // If the string is already long enough, nothing to do! + targetLength -= this.length; + if (targetLength <= 0) + return String(this); + + if (padString === undefined) + padString = ' '; + + // In case the pad is multiple chars long. + if (targetLength > padString.length) + padString = padString.repeat((targetLength / padString.length) + 1); + + return padString.slice(0, targetLength) + String(this); + }; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd +if (!String.prototype.padEnd) { + String.prototype.padEnd = function(targetLength, padString) { + // If the string is already long enough, nothing to do! + targetLength -= this.length; + if (targetLength <= 0) + return String(this); + + if (padString === undefined) + padString = ' '; + + // In case the pad is multiple chars long. + if (targetLength > padString.length) + padString = padString.repeat((targetLength / padString.length) + 1); + + return String(this) + padString.slice(0, targetLength); + }; +} + +// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values +// https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js +if (!Object.values || !Object.entries) { + const reduce = Function.bind.call(Function.call, Array.prototype.reduce); + const isEnumerable = Function.bind.call(Function.call, + Object.prototype.propertyIsEnumerable); + const concat = Function.bind.call(Function.call, Array.prototype.concat); + + if (!Object.values) { + Object.values = function values(O) { + return reduce(Reflect.ownKeys(O), (v, k) => concat(v, + typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); + }; + } + + if (!Object.entries) { + Object.entries = function entries(O) { + return reduce(Reflect.ownKeys(O), (e, k) => concat(e, + typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []); + }; + } +} +// SOURCE FILE: libdot/js/lib_array.js +// Copyright 2017 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Helper functions for (typed) arrays. + */ + +lib.array = {}; + +/** + * Convert an array of four unsigned bytes into an unsigned 32-bit integer (big + * endian). + * + * @param {!Array.} array + * @returns {!number} + */ +lib.array.arrayBigEndianToUint32 = function(array) { + const maybeSigned = + (array[0] << 24) | (array[1] << 16) | (array[2] << 8) | (array[3] << 0); + // Interpret the result of the bit operations as an unsigned integer. + return maybeSigned >>> 0; +}; + +/** + * Convert an unsigned 32-bit integer into an array of four unsigned bytes (big + * endian). + * + * @param {!number} uint32 + * @returns {!Array.} + */ +lib.array.uint32ToArrayBigEndian = function(uint32) { + return [ + (uint32 >>> 24) & 0xFF, + (uint32 >>> 16) & 0xFF, + (uint32 >>> 8) & 0xFF, + (uint32 >>> 0) & 0xFF, + ]; +}; + +/** + * Concatenate an arbitrary number of typed arrays of the same type into a new + * typed array of this type. + * + * @template TYPED_ARRAY + * @param {...!TYPED_ARRAY} arrays + * @returns {!TYPED_ARRAY} + */ +lib.array.concatTyped = function(...arrays) { + let resultLength = 0; + for (const array of arrays) { + resultLength += array.length; + } + const result = new arrays[0].constructor(resultLength); + let pos = 0; + for (const array of arrays) { + result.set(array, pos); + pos += array.length; + } + return result; +}; + +/** + * Compare two array-like objects entrywise. + * + * @template ARRAY_LIKE + * @param {?ARRAY_LIKE} a + * @param {?ARRAY_LIKE} b + * @returns {!boolean} true if both arrays are null or they agree entrywise; + * false otherwise. + */ +lib.array.compare = function(a, b) { + if (a === null || b === null) { + return a === null && b === null; + } + + if (a.length !== b.length) { + return false; + } + + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +}; +// SOURCE FILE: libdot/js/lib_colors.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Namespace for color utilities. + */ +lib.colors = {}; + +/** + * First, some canned regular expressions we're going to use in this file. + * + * + * BRACE YOURSELF + * + * ,~~~~. + * |>_< ~~ + * 3`---'-/. + * 3:::::\v\ + * =o=:::::\,\ + * | :::::\,,\ + * + * THE REGULAR EXPRESSIONS + * ARE COMING. + * + * There's no way to break long RE literals in JavaScript. Fix that why don't + * you? Oh, and also there's no way to write a string that doesn't interpret + * escapes. + * + * Instead, we stoop to this .replace() trick. + */ +lib.colors.re_ = { + // CSS hex color, #RGB. + hex16: /#([a-f0-9])([a-f0-9])([a-f0-9])/i, + + // CSS hex color, #RRGGBB. + hex24: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i, + + // CSS rgb color, rgb(rrr,ggg,bbb). + rgb: new RegExp( + ('^/s*rgb/s*/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,' + + '/s*(/d{1,3})/s*/)/s*$' + ).replace(/\//g, '\\'), 'i'), + + // CSS rgb color, rgb(rrr,ggg,bbb,aaa). + rgba: new RegExp( + ('^/s*rgba/s*' + + '/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,/s*(/d{1,3})/s*' + + '(?:,/s*(/d+(?:/./d+)?)/s*)/)/s*$' + ).replace(/\//g, '\\'), 'i'), + + // Either RGB or RGBA. + rgbx: new RegExp( + ('^/s*rgba?/s*' + + '/(/s*(/d{1,3})/s*,/s*(/d{1,3})/s*,/s*(/d{1,3})/s*' + + '(?:,/s*(/d+(?:/./d+)?)/s*)?/)/s*$' + ).replace(/\//g, '\\'), 'i'), + + // An X11 "rgb:dddd/dddd/dddd" value. + x11rgb: /^\s*rgb:([a-f0-9]{1,4})\/([a-f0-9]{1,4})\/([a-f0-9]{1,4})\s*$/i, + + // English color name. + name: /[a-z][a-z0-9\s]+/, +}; + +/** + * Convert a CSS rgb(ddd,ddd,ddd) color value into an X11 color value. + * + * Other CSS color values are ignored to ensure sanitary data handling. + * + * Each 'ddd' component is a one byte value specified in decimal. + * + * @param {string} value The CSS color value to convert. + * @return {string} The X11 color value or null if the value could not be + * converted. + */ +lib.colors.rgbToX11 = function(value) { + function scale(v) { + v = (Math.min(v, 255) * 257).toString(16); + return lib.f.zpad(v, 4); + } + + var ary = value.match(lib.colors.re_.rgbx); + if (!ary) + return null; + + return 'rgb:' + scale(ary[1]) + '/' + scale(ary[2]) + '/' + scale(ary[3]); +}; + +/** + * Convert a legacy X11 colover value into an CSS rgb(...) color value. + * + * They take the form: + * 12 bit: #RGB -> #R000G000B000 + * 24 bit: #RRGGBB -> #RR00GG00BB00 + * 36 bit: #RRRGGGBBB -> #RRR0GGG0BBB0 + * 48 bit: #RRRRGGGGBBBB + * These are the most significant bits. + * + * Truncate values back down to 24 bit since that's all CSS supports. + */ +lib.colors.x11HexToCSS = function(v) { + if (!v.startsWith('#')) + return null; + // Strip the leading # off. + v = v.substr(1); + + // Reject unknown sizes. + if ([3, 6, 9, 12].indexOf(v.length) == -1) + return null; + + // Reject non-hex values. + if (v.match(/[^a-f0-9]/i)) + return null; + + // Split the colors out. + var size = v.length / 3; + var r = v.substr(0, size); + var g = v.substr(size, size); + var b = v.substr(size + size, size); + + // Normalize to 16 bits. + function norm16(v) { + v = parseInt(v, 16); + return size == 2 ? v : // 16 bit + size == 1 ? v << 4 : // 8 bit + v >> (4 * (size - 2)); // 24 or 32 bit + } + return lib.colors.arrayToRGBA([r, g, b].map(norm16)); +}; + +/** + * Convert an X11 color value into an CSS rgb(...) color value. + * + * The X11 value may be an X11 color name, or an RGB value of the form + * rgb:hhhh/hhhh/hhhh. If a component value is less than 4 digits it is + * padded out to 4, then scaled down to fit in a single byte. + * + * @param {string} value The X11 color value to convert. + * @return {string} The CSS color value or null if the value could not be + * converted. + */ +lib.colors.x11ToCSS = function(v) { + function scale(v) { + // Pad out values with less than four digits. This padding (probably) + // matches xterm. It's difficult to say for sure since xterm seems to + // arrive at a padded value and then perform some combination of + // gamma correction, color space transformation, and quantization. + + if (v.length == 1) { + // Single digits pad out to four by repeating the character. "f" becomes + // "ffff". Scaling down a hex value of this pattern by 257 is the same + // as cutting off one byte. We skip the middle step and just double + // the character. + return parseInt(v + v, 16); + } + + if (v.length == 2) { + // Similar deal here. X11 pads two digit values by repeating the + // byte (or scale up by 257). Since we're going to scale it back + // down anyway, we can just return the original value. + return parseInt(v, 16); + } + + if (v.length == 3) { + // Three digit values seem to be padded by repeating the final digit. + // e.g. 10f becomes 10ff. + v = v + v.substr(2); + } + + // Scale down the 2 byte value. + return Math.round(parseInt(v, 16) / 257); + } + + var ary = v.match(lib.colors.re_.x11rgb); + if (!ary) { + // Handle the legacy format. + if (v.startsWith('#')) + return lib.colors.x11HexToCSS(v); + else + return lib.colors.nameToRGB(v); + } + + ary.splice(0, 1); + return lib.colors.arrayToRGBA(ary.map(scale)); +}; + +/** + * Converts one or more CSS '#RRGGBB' color values into their rgb(...) + * form. + * + * Arrays are converted in place. If a value cannot be converted, it is + * replaced with null. + * + * @param {string|Array.} A single RGB value or array of RGB values to + * convert. + * @return {string|Array.} The converted value or values. + */ +lib.colors.hexToRGB = function(arg) { + var hex16 = lib.colors.re_.hex16; + var hex24 = lib.colors.re_.hex24; + + function convert(hex) { + if (hex.length == 4) { + hex = hex.replace(hex16, function(h, r, g, b) { + return "#" + r + r + g + g + b + b; + }); + } + var ary = hex.match(hex24); + if (!ary) + return null; + + return 'rgb(' + parseInt(ary[1], 16) + ', ' + + parseInt(ary[2], 16) + ', ' + + parseInt(ary[3], 16) + ')'; + } + + if (arg instanceof Array) { + for (var i = 0; i < arg.length; i++) { + arg[i] = convert(arg[i]); + } + } else { + arg = convert(arg); + } + + return arg; +}; + +/** + * Converts one or more CSS rgb(...) forms into their '#RRGGBB' color values. + * + * If given an rgba(...) form, the alpha field is thrown away. + * + * Arrays are converted in place. If a value cannot be converted, it is + * replaced with null. + * + * @param {string|Array.} A single rgb(...) value or array of rgb(...) + * values to convert. + * @return {string|Array.} The converted value or values. + */ +lib.colors.rgbToHex = function(arg) { + function convert(rgb) { + var ary = lib.colors.crackRGB(rgb); + if (!ary) + return null; + return '#' + lib.f.zpad(((parseInt(ary[0]) << 16) | + (parseInt(ary[1]) << 8) | + (parseInt(ary[2]) << 0)).toString(16), 6); + } + + if (arg instanceof Array) { + for (var i = 0; i < arg.length; i++) { + arg[i] = convert(arg[i]); + } + } else { + arg = convert(arg); + } + + return arg; +}; + +/** + * Take any valid css color definition and turn it into an rgb or rgba value. + * + * Returns null if the value could not be normalized. + */ +lib.colors.normalizeCSS = function(def) { + if (def.startsWith('#')) + return lib.colors.hexToRGB(def); + + if (lib.colors.re_.rgbx.test(def)) + return def; + + return lib.colors.nameToRGB(def); +}; + +/** + * Convert a 3 or 4 element array into an rgba(...) string. + */ +lib.colors.arrayToRGBA = function(ary) { + var alpha = (ary.length > 3) ? ary[3] : 1; + return 'rgba(' + ary[0] + ', ' + ary[1] + ', ' + ary[2] + ', ' + alpha + ')'; +}; + +/** + * Overwrite the alpha channel of an rgb/rgba color. + */ +lib.colors.setAlpha = function(rgb, alpha) { + var ary = lib.colors.crackRGB(rgb); + ary[3] = alpha; + return lib.colors.arrayToRGBA(ary); +}; + +/** + * Mix a percentage of a tint color into a base color. + */ +lib.colors.mix = function(base, tint, percent) { + var ary1 = lib.colors.crackRGB(base); + var ary2 = lib.colors.crackRGB(tint); + + for (var i = 0; i < 4; ++i) { + var diff = ary2[i] - ary1[i]; + ary1[i] = Math.round(parseInt(ary1[i]) + diff * percent); + } + + return lib.colors.arrayToRGBA(ary1); +}; + +/** + * Split an rgb/rgba color into an array of its components. + * + * On success, a 4 element array will be returned. For rgb values, the alpha + * will be set to 1. + */ +lib.colors.crackRGB = function(color) { + if (color.startsWith('rgba')) { + var ary = color.match(lib.colors.re_.rgba); + if (ary) { + ary.shift(); + return ary; + } + } else { + var ary = color.match(lib.colors.re_.rgb); + if (ary) { + ary.shift(); + ary.push('1'); + return ary; + } + } + + console.error('Couldn\'t crack: ' + color); + return null; +}; + +/** + * Convert an X11 color name into a CSS rgb(...) value. + * + * Names are stripped of spaces and converted to lowercase. If the name is + * unknown, null is returned. + * + * This list of color name to RGB mapping is derived from the stock X11 + * rgb.txt file. + * + * @param {string} name The color name to convert. + * @return {string} The corresponding CSS rgb(...) value. + */ +lib.colors.nameToRGB = function(name) { + if (name in lib.colors.colorNames) + return lib.colors.colorNames[name]; + + name = name.toLowerCase(); + if (name in lib.colors.colorNames) + return lib.colors.colorNames[name]; + + name = name.replace(/\s+/g, ''); + if (name in lib.colors.colorNames) + return lib.colors.colorNames[name]; + + return null; +}; + +/** + * The stock color palette. + */ +lib.colors.stockColorPalette = lib.colors.hexToRGB + ([// The "ANSI 16"... + '#000000', '#CC0000', '#4E9A06', '#C4A000', + '#3465A4', '#75507B', '#06989A', '#D3D7CF', + '#555753', '#EF2929', '#00BA13', '#FCE94F', + '#729FCF', '#F200CB', '#00B5BD', '#EEEEEC', + + // The 6x6 color cubes... + '#000000', '#00005F', '#000087', '#0000AF', '#0000D7', '#0000FF', + '#005F00', '#005F5F', '#005F87', '#005FAF', '#005FD7', '#005FFF', + '#008700', '#00875F', '#008787', '#0087AF', '#0087D7', '#0087FF', + '#00AF00', '#00AF5F', '#00AF87', '#00AFAF', '#00AFD7', '#00AFFF', + '#00D700', '#00D75F', '#00D787', '#00D7AF', '#00D7D7', '#00D7FF', + '#00FF00', '#00FF5F', '#00FF87', '#00FFAF', '#00FFD7', '#00FFFF', + + '#5F0000', '#5F005F', '#5F0087', '#5F00AF', '#5F00D7', '#5F00FF', + '#5F5F00', '#5F5F5F', '#5F5F87', '#5F5FAF', '#5F5FD7', '#5F5FFF', + '#5F8700', '#5F875F', '#5F8787', '#5F87AF', '#5F87D7', '#5F87FF', + '#5FAF00', '#5FAF5F', '#5FAF87', '#5FAFAF', '#5FAFD7', '#5FAFFF', + '#5FD700', '#5FD75F', '#5FD787', '#5FD7AF', '#5FD7D7', '#5FD7FF', + '#5FFF00', '#5FFF5F', '#5FFF87', '#5FFFAF', '#5FFFD7', '#5FFFFF', + + '#870000', '#87005F', '#870087', '#8700AF', '#8700D7', '#8700FF', + '#875F00', '#875F5F', '#875F87', '#875FAF', '#875FD7', '#875FFF', + '#878700', '#87875F', '#878787', '#8787AF', '#8787D7', '#8787FF', + '#87AF00', '#87AF5F', '#87AF87', '#87AFAF', '#87AFD7', '#87AFFF', + '#87D700', '#87D75F', '#87D787', '#87D7AF', '#87D7D7', '#87D7FF', + '#87FF00', '#87FF5F', '#87FF87', '#87FFAF', '#87FFD7', '#87FFFF', + + '#AF0000', '#AF005F', '#AF0087', '#AF00AF', '#AF00D7', '#AF00FF', + '#AF5F00', '#AF5F5F', '#AF5F87', '#AF5FAF', '#AF5FD7', '#AF5FFF', + '#AF8700', '#AF875F', '#AF8787', '#AF87AF', '#AF87D7', '#AF87FF', + '#AFAF00', '#AFAF5F', '#AFAF87', '#AFAFAF', '#AFAFD7', '#AFAFFF', + '#AFD700', '#AFD75F', '#AFD787', '#AFD7AF', '#AFD7D7', '#AFD7FF', + '#AFFF00', '#AFFF5F', '#AFFF87', '#AFFFAF', '#AFFFD7', '#AFFFFF', + + '#D70000', '#D7005F', '#D70087', '#D700AF', '#D700D7', '#D700FF', + '#D75F00', '#D75F5F', '#D75F87', '#D75FAF', '#D75FD7', '#D75FFF', + '#D78700', '#D7875F', '#D78787', '#D787AF', '#D787D7', '#D787FF', + '#D7AF00', '#D7AF5F', '#D7AF87', '#D7AFAF', '#D7AFD7', '#D7AFFF', + '#D7D700', '#D7D75F', '#D7D787', '#D7D7AF', '#D7D7D7', '#D7D7FF', + '#D7FF00', '#D7FF5F', '#D7FF87', '#D7FFAF', '#D7FFD7', '#D7FFFF', + + '#FF0000', '#FF005F', '#FF0087', '#FF00AF', '#FF00D7', '#FF00FF', + '#FF5F00', '#FF5F5F', '#FF5F87', '#FF5FAF', '#FF5FD7', '#FF5FFF', + '#FF8700', '#FF875F', '#FF8787', '#FF87AF', '#FF87D7', '#FF87FF', + '#FFAF00', '#FFAF5F', '#FFAF87', '#FFAFAF', '#FFAFD7', '#FFAFFF', + '#FFD700', '#FFD75F', '#FFD787', '#FFD7AF', '#FFD7D7', '#FFD7FF', + '#FFFF00', '#FFFF5F', '#FFFF87', '#FFFFAF', '#FFFFD7', '#FFFFFF', + + // The greyscale ramp... + '#080808', '#121212', '#1C1C1C', '#262626', '#303030', '#3A3A3A', + '#444444', '#4E4E4E', '#585858', '#626262', '#6C6C6C', '#767676', + '#808080', '#8A8A8A', '#949494', '#9E9E9E', '#A8A8A8', '#B2B2B2', + '#BCBCBC', '#C6C6C6', '#D0D0D0', '#DADADA', '#E4E4E4', '#EEEEEE' + ]); + +/** + * The current color palette, possibly with user changes. + */ +lib.colors.colorPalette = lib.colors.stockColorPalette; + +/** + * Named colors according to the stock X11 rgb.txt file. + */ +lib.colors.colorNames = { + "aliceblue": "rgb(240, 248, 255)", + "antiquewhite": "rgb(250, 235, 215)", + "antiquewhite1": "rgb(255, 239, 219)", + "antiquewhite2": "rgb(238, 223, 204)", + "antiquewhite3": "rgb(205, 192, 176)", + "antiquewhite4": "rgb(139, 131, 120)", + "aquamarine": "rgb(127, 255, 212)", + "aquamarine1": "rgb(127, 255, 212)", + "aquamarine2": "rgb(118, 238, 198)", + "aquamarine3": "rgb(102, 205, 170)", + "aquamarine4": "rgb(69, 139, 116)", + "azure": "rgb(240, 255, 255)", + "azure1": "rgb(240, 255, 255)", + "azure2": "rgb(224, 238, 238)", + "azure3": "rgb(193, 205, 205)", + "azure4": "rgb(131, 139, 139)", + "beige": "rgb(245, 245, 220)", + "bisque": "rgb(255, 228, 196)", + "bisque1": "rgb(255, 228, 196)", + "bisque2": "rgb(238, 213, 183)", + "bisque3": "rgb(205, 183, 158)", + "bisque4": "rgb(139, 125, 107)", + "black": "rgb(0, 0, 0)", + "blanchedalmond": "rgb(255, 235, 205)", + "blue": "rgb(0, 0, 255)", + "blue1": "rgb(0, 0, 255)", + "blue2": "rgb(0, 0, 238)", + "blue3": "rgb(0, 0, 205)", + "blue4": "rgb(0, 0, 139)", + "blueviolet": "rgb(138, 43, 226)", + "brown": "rgb(165, 42, 42)", + "brown1": "rgb(255, 64, 64)", + "brown2": "rgb(238, 59, 59)", + "brown3": "rgb(205, 51, 51)", + "brown4": "rgb(139, 35, 35)", + "burlywood": "rgb(222, 184, 135)", + "burlywood1": "rgb(255, 211, 155)", + "burlywood2": "rgb(238, 197, 145)", + "burlywood3": "rgb(205, 170, 125)", + "burlywood4": "rgb(139, 115, 85)", + "cadetblue": "rgb(95, 158, 160)", + "cadetblue1": "rgb(152, 245, 255)", + "cadetblue2": "rgb(142, 229, 238)", + "cadetblue3": "rgb(122, 197, 205)", + "cadetblue4": "rgb(83, 134, 139)", + "chartreuse": "rgb(127, 255, 0)", + "chartreuse1": "rgb(127, 255, 0)", + "chartreuse2": "rgb(118, 238, 0)", + "chartreuse3": "rgb(102, 205, 0)", + "chartreuse4": "rgb(69, 139, 0)", + "chocolate": "rgb(210, 105, 30)", + "chocolate1": "rgb(255, 127, 36)", + "chocolate2": "rgb(238, 118, 33)", + "chocolate3": "rgb(205, 102, 29)", + "chocolate4": "rgb(139, 69, 19)", + "coral": "rgb(255, 127, 80)", + "coral1": "rgb(255, 114, 86)", + "coral2": "rgb(238, 106, 80)", + "coral3": "rgb(205, 91, 69)", + "coral4": "rgb(139, 62, 47)", + "cornflowerblue": "rgb(100, 149, 237)", + "cornsilk": "rgb(255, 248, 220)", + "cornsilk1": "rgb(255, 248, 220)", + "cornsilk2": "rgb(238, 232, 205)", + "cornsilk3": "rgb(205, 200, 177)", + "cornsilk4": "rgb(139, 136, 120)", + "cyan": "rgb(0, 255, 255)", + "cyan1": "rgb(0, 255, 255)", + "cyan2": "rgb(0, 238, 238)", + "cyan3": "rgb(0, 205, 205)", + "cyan4": "rgb(0, 139, 139)", + "darkblue": "rgb(0, 0, 139)", + "darkcyan": "rgb(0, 139, 139)", + "darkgoldenrod": "rgb(184, 134, 11)", + "darkgoldenrod1": "rgb(255, 185, 15)", + "darkgoldenrod2": "rgb(238, 173, 14)", + "darkgoldenrod3": "rgb(205, 149, 12)", + "darkgoldenrod4": "rgb(139, 101, 8)", + "darkgray": "rgb(169, 169, 169)", + "darkgreen": "rgb(0, 100, 0)", + "darkgrey": "rgb(169, 169, 169)", + "darkkhaki": "rgb(189, 183, 107)", + "darkmagenta": "rgb(139, 0, 139)", + "darkolivegreen": "rgb(85, 107, 47)", + "darkolivegreen1": "rgb(202, 255, 112)", + "darkolivegreen2": "rgb(188, 238, 104)", + "darkolivegreen3": "rgb(162, 205, 90)", + "darkolivegreen4": "rgb(110, 139, 61)", + "darkorange": "rgb(255, 140, 0)", + "darkorange1": "rgb(255, 127, 0)", + "darkorange2": "rgb(238, 118, 0)", + "darkorange3": "rgb(205, 102, 0)", + "darkorange4": "rgb(139, 69, 0)", + "darkorchid": "rgb(153, 50, 204)", + "darkorchid1": "rgb(191, 62, 255)", + "darkorchid2": "rgb(178, 58, 238)", + "darkorchid3": "rgb(154, 50, 205)", + "darkorchid4": "rgb(104, 34, 139)", + "darkred": "rgb(139, 0, 0)", + "darksalmon": "rgb(233, 150, 122)", + "darkseagreen": "rgb(143, 188, 143)", + "darkseagreen1": "rgb(193, 255, 193)", + "darkseagreen2": "rgb(180, 238, 180)", + "darkseagreen3": "rgb(155, 205, 155)", + "darkseagreen4": "rgb(105, 139, 105)", + "darkslateblue": "rgb(72, 61, 139)", + "darkslategray": "rgb(47, 79, 79)", + "darkslategray1": "rgb(151, 255, 255)", + "darkslategray2": "rgb(141, 238, 238)", + "darkslategray3": "rgb(121, 205, 205)", + "darkslategray4": "rgb(82, 139, 139)", + "darkslategrey": "rgb(47, 79, 79)", + "darkturquoise": "rgb(0, 206, 209)", + "darkviolet": "rgb(148, 0, 211)", + "debianred": "rgb(215, 7, 81)", + "deeppink": "rgb(255, 20, 147)", + "deeppink1": "rgb(255, 20, 147)", + "deeppink2": "rgb(238, 18, 137)", + "deeppink3": "rgb(205, 16, 118)", + "deeppink4": "rgb(139, 10, 80)", + "deepskyblue": "rgb(0, 191, 255)", + "deepskyblue1": "rgb(0, 191, 255)", + "deepskyblue2": "rgb(0, 178, 238)", + "deepskyblue3": "rgb(0, 154, 205)", + "deepskyblue4": "rgb(0, 104, 139)", + "dimgray": "rgb(105, 105, 105)", + "dimgrey": "rgb(105, 105, 105)", + "dodgerblue": "rgb(30, 144, 255)", + "dodgerblue1": "rgb(30, 144, 255)", + "dodgerblue2": "rgb(28, 134, 238)", + "dodgerblue3": "rgb(24, 116, 205)", + "dodgerblue4": "rgb(16, 78, 139)", + "firebrick": "rgb(178, 34, 34)", + "firebrick1": "rgb(255, 48, 48)", + "firebrick2": "rgb(238, 44, 44)", + "firebrick3": "rgb(205, 38, 38)", + "firebrick4": "rgb(139, 26, 26)", + "floralwhite": "rgb(255, 250, 240)", + "forestgreen": "rgb(34, 139, 34)", + "gainsboro": "rgb(220, 220, 220)", + "ghostwhite": "rgb(248, 248, 255)", + "gold": "rgb(255, 215, 0)", + "gold1": "rgb(255, 215, 0)", + "gold2": "rgb(238, 201, 0)", + "gold3": "rgb(205, 173, 0)", + "gold4": "rgb(139, 117, 0)", + "goldenrod": "rgb(218, 165, 32)", + "goldenrod1": "rgb(255, 193, 37)", + "goldenrod2": "rgb(238, 180, 34)", + "goldenrod3": "rgb(205, 155, 29)", + "goldenrod4": "rgb(139, 105, 20)", + "gray": "rgb(190, 190, 190)", + "gray0": "rgb(0, 0, 0)", + "gray1": "rgb(3, 3, 3)", + "gray10": "rgb(26, 26, 26)", + "gray100": "rgb(255, 255, 255)", + "gray11": "rgb(28, 28, 28)", + "gray12": "rgb(31, 31, 31)", + "gray13": "rgb(33, 33, 33)", + "gray14": "rgb(36, 36, 36)", + "gray15": "rgb(38, 38, 38)", + "gray16": "rgb(41, 41, 41)", + "gray17": "rgb(43, 43, 43)", + "gray18": "rgb(46, 46, 46)", + "gray19": "rgb(48, 48, 48)", + "gray2": "rgb(5, 5, 5)", + "gray20": "rgb(51, 51, 51)", + "gray21": "rgb(54, 54, 54)", + "gray22": "rgb(56, 56, 56)", + "gray23": "rgb(59, 59, 59)", + "gray24": "rgb(61, 61, 61)", + "gray25": "rgb(64, 64, 64)", + "gray26": "rgb(66, 66, 66)", + "gray27": "rgb(69, 69, 69)", + "gray28": "rgb(71, 71, 71)", + "gray29": "rgb(74, 74, 74)", + "gray3": "rgb(8, 8, 8)", + "gray30": "rgb(77, 77, 77)", + "gray31": "rgb(79, 79, 79)", + "gray32": "rgb(82, 82, 82)", + "gray33": "rgb(84, 84, 84)", + "gray34": "rgb(87, 87, 87)", + "gray35": "rgb(89, 89, 89)", + "gray36": "rgb(92, 92, 92)", + "gray37": "rgb(94, 94, 94)", + "gray38": "rgb(97, 97, 97)", + "gray39": "rgb(99, 99, 99)", + "gray4": "rgb(10, 10, 10)", + "gray40": "rgb(102, 102, 102)", + "gray41": "rgb(105, 105, 105)", + "gray42": "rgb(107, 107, 107)", + "gray43": "rgb(110, 110, 110)", + "gray44": "rgb(112, 112, 112)", + "gray45": "rgb(115, 115, 115)", + "gray46": "rgb(117, 117, 117)", + "gray47": "rgb(120, 120, 120)", + "gray48": "rgb(122, 122, 122)", + "gray49": "rgb(125, 125, 125)", + "gray5": "rgb(13, 13, 13)", + "gray50": "rgb(127, 127, 127)", + "gray51": "rgb(130, 130, 130)", + "gray52": "rgb(133, 133, 133)", + "gray53": "rgb(135, 135, 135)", + "gray54": "rgb(138, 138, 138)", + "gray55": "rgb(140, 140, 140)", + "gray56": "rgb(143, 143, 143)", + "gray57": "rgb(145, 145, 145)", + "gray58": "rgb(148, 148, 148)", + "gray59": "rgb(150, 150, 150)", + "gray6": "rgb(15, 15, 15)", + "gray60": "rgb(153, 153, 153)", + "gray61": "rgb(156, 156, 156)", + "gray62": "rgb(158, 158, 158)", + "gray63": "rgb(161, 161, 161)", + "gray64": "rgb(163, 163, 163)", + "gray65": "rgb(166, 166, 166)", + "gray66": "rgb(168, 168, 168)", + "gray67": "rgb(171, 171, 171)", + "gray68": "rgb(173, 173, 173)", + "gray69": "rgb(176, 176, 176)", + "gray7": "rgb(18, 18, 18)", + "gray70": "rgb(179, 179, 179)", + "gray71": "rgb(181, 181, 181)", + "gray72": "rgb(184, 184, 184)", + "gray73": "rgb(186, 186, 186)", + "gray74": "rgb(189, 189, 189)", + "gray75": "rgb(191, 191, 191)", + "gray76": "rgb(194, 194, 194)", + "gray77": "rgb(196, 196, 196)", + "gray78": "rgb(199, 199, 199)", + "gray79": "rgb(201, 201, 201)", + "gray8": "rgb(20, 20, 20)", + "gray80": "rgb(204, 204, 204)", + "gray81": "rgb(207, 207, 207)", + "gray82": "rgb(209, 209, 209)", + "gray83": "rgb(212, 212, 212)", + "gray84": "rgb(214, 214, 214)", + "gray85": "rgb(217, 217, 217)", + "gray86": "rgb(219, 219, 219)", + "gray87": "rgb(222, 222, 222)", + "gray88": "rgb(224, 224, 224)", + "gray89": "rgb(227, 227, 227)", + "gray9": "rgb(23, 23, 23)", + "gray90": "rgb(229, 229, 229)", + "gray91": "rgb(232, 232, 232)", + "gray92": "rgb(235, 235, 235)", + "gray93": "rgb(237, 237, 237)", + "gray94": "rgb(240, 240, 240)", + "gray95": "rgb(242, 242, 242)", + "gray96": "rgb(245, 245, 245)", + "gray97": "rgb(247, 247, 247)", + "gray98": "rgb(250, 250, 250)", + "gray99": "rgb(252, 252, 252)", + "green": "rgb(0, 255, 0)", + "green1": "rgb(0, 255, 0)", + "green2": "rgb(0, 238, 0)", + "green3": "rgb(0, 205, 0)", + "green4": "rgb(0, 139, 0)", + "greenyellow": "rgb(173, 255, 47)", + "grey": "rgb(190, 190, 190)", + "grey0": "rgb(0, 0, 0)", + "grey1": "rgb(3, 3, 3)", + "grey10": "rgb(26, 26, 26)", + "grey100": "rgb(255, 255, 255)", + "grey11": "rgb(28, 28, 28)", + "grey12": "rgb(31, 31, 31)", + "grey13": "rgb(33, 33, 33)", + "grey14": "rgb(36, 36, 36)", + "grey15": "rgb(38, 38, 38)", + "grey16": "rgb(41, 41, 41)", + "grey17": "rgb(43, 43, 43)", + "grey18": "rgb(46, 46, 46)", + "grey19": "rgb(48, 48, 48)", + "grey2": "rgb(5, 5, 5)", + "grey20": "rgb(51, 51, 51)", + "grey21": "rgb(54, 54, 54)", + "grey22": "rgb(56, 56, 56)", + "grey23": "rgb(59, 59, 59)", + "grey24": "rgb(61, 61, 61)", + "grey25": "rgb(64, 64, 64)", + "grey26": "rgb(66, 66, 66)", + "grey27": "rgb(69, 69, 69)", + "grey28": "rgb(71, 71, 71)", + "grey29": "rgb(74, 74, 74)", + "grey3": "rgb(8, 8, 8)", + "grey30": "rgb(77, 77, 77)", + "grey31": "rgb(79, 79, 79)", + "grey32": "rgb(82, 82, 82)", + "grey33": "rgb(84, 84, 84)", + "grey34": "rgb(87, 87, 87)", + "grey35": "rgb(89, 89, 89)", + "grey36": "rgb(92, 92, 92)", + "grey37": "rgb(94, 94, 94)", + "grey38": "rgb(97, 97, 97)", + "grey39": "rgb(99, 99, 99)", + "grey4": "rgb(10, 10, 10)", + "grey40": "rgb(102, 102, 102)", + "grey41": "rgb(105, 105, 105)", + "grey42": "rgb(107, 107, 107)", + "grey43": "rgb(110, 110, 110)", + "grey44": "rgb(112, 112, 112)", + "grey45": "rgb(115, 115, 115)", + "grey46": "rgb(117, 117, 117)", + "grey47": "rgb(120, 120, 120)", + "grey48": "rgb(122, 122, 122)", + "grey49": "rgb(125, 125, 125)", + "grey5": "rgb(13, 13, 13)", + "grey50": "rgb(127, 127, 127)", + "grey51": "rgb(130, 130, 130)", + "grey52": "rgb(133, 133, 133)", + "grey53": "rgb(135, 135, 135)", + "grey54": "rgb(138, 138, 138)", + "grey55": "rgb(140, 140, 140)", + "grey56": "rgb(143, 143, 143)", + "grey57": "rgb(145, 145, 145)", + "grey58": "rgb(148, 148, 148)", + "grey59": "rgb(150, 150, 150)", + "grey6": "rgb(15, 15, 15)", + "grey60": "rgb(153, 153, 153)", + "grey61": "rgb(156, 156, 156)", + "grey62": "rgb(158, 158, 158)", + "grey63": "rgb(161, 161, 161)", + "grey64": "rgb(163, 163, 163)", + "grey65": "rgb(166, 166, 166)", + "grey66": "rgb(168, 168, 168)", + "grey67": "rgb(171, 171, 171)", + "grey68": "rgb(173, 173, 173)", + "grey69": "rgb(176, 176, 176)", + "grey7": "rgb(18, 18, 18)", + "grey70": "rgb(179, 179, 179)", + "grey71": "rgb(181, 181, 181)", + "grey72": "rgb(184, 184, 184)", + "grey73": "rgb(186, 186, 186)", + "grey74": "rgb(189, 189, 189)", + "grey75": "rgb(191, 191, 191)", + "grey76": "rgb(194, 194, 194)", + "grey77": "rgb(196, 196, 196)", + "grey78": "rgb(199, 199, 199)", + "grey79": "rgb(201, 201, 201)", + "grey8": "rgb(20, 20, 20)", + "grey80": "rgb(204, 204, 204)", + "grey81": "rgb(207, 207, 207)", + "grey82": "rgb(209, 209, 209)", + "grey83": "rgb(212, 212, 212)", + "grey84": "rgb(214, 214, 214)", + "grey85": "rgb(217, 217, 217)", + "grey86": "rgb(219, 219, 219)", + "grey87": "rgb(222, 222, 222)", + "grey88": "rgb(224, 224, 224)", + "grey89": "rgb(227, 227, 227)", + "grey9": "rgb(23, 23, 23)", + "grey90": "rgb(229, 229, 229)", + "grey91": "rgb(232, 232, 232)", + "grey92": "rgb(235, 235, 235)", + "grey93": "rgb(237, 237, 237)", + "grey94": "rgb(240, 240, 240)", + "grey95": "rgb(242, 242, 242)", + "grey96": "rgb(245, 245, 245)", + "grey97": "rgb(247, 247, 247)", + "grey98": "rgb(250, 250, 250)", + "grey99": "rgb(252, 252, 252)", + "honeydew": "rgb(240, 255, 240)", + "honeydew1": "rgb(240, 255, 240)", + "honeydew2": "rgb(224, 238, 224)", + "honeydew3": "rgb(193, 205, 193)", + "honeydew4": "rgb(131, 139, 131)", + "hotpink": "rgb(255, 105, 180)", + "hotpink1": "rgb(255, 110, 180)", + "hotpink2": "rgb(238, 106, 167)", + "hotpink3": "rgb(205, 96, 144)", + "hotpink4": "rgb(139, 58, 98)", + "indianred": "rgb(205, 92, 92)", + "indianred1": "rgb(255, 106, 106)", + "indianred2": "rgb(238, 99, 99)", + "indianred3": "rgb(205, 85, 85)", + "indianred4": "rgb(139, 58, 58)", + "ivory": "rgb(255, 255, 240)", + "ivory1": "rgb(255, 255, 240)", + "ivory2": "rgb(238, 238, 224)", + "ivory3": "rgb(205, 205, 193)", + "ivory4": "rgb(139, 139, 131)", + "khaki": "rgb(240, 230, 140)", + "khaki1": "rgb(255, 246, 143)", + "khaki2": "rgb(238, 230, 133)", + "khaki3": "rgb(205, 198, 115)", + "khaki4": "rgb(139, 134, 78)", + "lavender": "rgb(230, 230, 250)", + "lavenderblush": "rgb(255, 240, 245)", + "lavenderblush1": "rgb(255, 240, 245)", + "lavenderblush2": "rgb(238, 224, 229)", + "lavenderblush3": "rgb(205, 193, 197)", + "lavenderblush4": "rgb(139, 131, 134)", + "lawngreen": "rgb(124, 252, 0)", + "lemonchiffon": "rgb(255, 250, 205)", + "lemonchiffon1": "rgb(255, 250, 205)", + "lemonchiffon2": "rgb(238, 233, 191)", + "lemonchiffon3": "rgb(205, 201, 165)", + "lemonchiffon4": "rgb(139, 137, 112)", + "lightblue": "rgb(173, 216, 230)", + "lightblue1": "rgb(191, 239, 255)", + "lightblue2": "rgb(178, 223, 238)", + "lightblue3": "rgb(154, 192, 205)", + "lightblue4": "rgb(104, 131, 139)", + "lightcoral": "rgb(240, 128, 128)", + "lightcyan": "rgb(224, 255, 255)", + "lightcyan1": "rgb(224, 255, 255)", + "lightcyan2": "rgb(209, 238, 238)", + "lightcyan3": "rgb(180, 205, 205)", + "lightcyan4": "rgb(122, 139, 139)", + "lightgoldenrod": "rgb(238, 221, 130)", + "lightgoldenrod1": "rgb(255, 236, 139)", + "lightgoldenrod2": "rgb(238, 220, 130)", + "lightgoldenrod3": "rgb(205, 190, 112)", + "lightgoldenrod4": "rgb(139, 129, 76)", + "lightgoldenrodyellow": "rgb(250, 250, 210)", + "lightgray": "rgb(211, 211, 211)", + "lightgreen": "rgb(144, 238, 144)", + "lightgrey": "rgb(211, 211, 211)", + "lightpink": "rgb(255, 182, 193)", + "lightpink1": "rgb(255, 174, 185)", + "lightpink2": "rgb(238, 162, 173)", + "lightpink3": "rgb(205, 140, 149)", + "lightpink4": "rgb(139, 95, 101)", + "lightsalmon": "rgb(255, 160, 122)", + "lightsalmon1": "rgb(255, 160, 122)", + "lightsalmon2": "rgb(238, 149, 114)", + "lightsalmon3": "rgb(205, 129, 98)", + "lightsalmon4": "rgb(139, 87, 66)", + "lightseagreen": "rgb(32, 178, 170)", + "lightskyblue": "rgb(135, 206, 250)", + "lightskyblue1": "rgb(176, 226, 255)", + "lightskyblue2": "rgb(164, 211, 238)", + "lightskyblue3": "rgb(141, 182, 205)", + "lightskyblue4": "rgb(96, 123, 139)", + "lightslateblue": "rgb(132, 112, 255)", + "lightslategray": "rgb(119, 136, 153)", + "lightslategrey": "rgb(119, 136, 153)", + "lightsteelblue": "rgb(176, 196, 222)", + "lightsteelblue1": "rgb(202, 225, 255)", + "lightsteelblue2": "rgb(188, 210, 238)", + "lightsteelblue3": "rgb(162, 181, 205)", + "lightsteelblue4": "rgb(110, 123, 139)", + "lightyellow": "rgb(255, 255, 224)", + "lightyellow1": "rgb(255, 255, 224)", + "lightyellow2": "rgb(238, 238, 209)", + "lightyellow3": "rgb(205, 205, 180)", + "lightyellow4": "rgb(139, 139, 122)", + "limegreen": "rgb(50, 205, 50)", + "linen": "rgb(250, 240, 230)", + "magenta": "rgb(255, 0, 255)", + "magenta1": "rgb(255, 0, 255)", + "magenta2": "rgb(238, 0, 238)", + "magenta3": "rgb(205, 0, 205)", + "magenta4": "rgb(139, 0, 139)", + "maroon": "rgb(176, 48, 96)", + "maroon1": "rgb(255, 52, 179)", + "maroon2": "rgb(238, 48, 167)", + "maroon3": "rgb(205, 41, 144)", + "maroon4": "rgb(139, 28, 98)", + "mediumaquamarine": "rgb(102, 205, 170)", + "mediumblue": "rgb(0, 0, 205)", + "mediumorchid": "rgb(186, 85, 211)", + "mediumorchid1": "rgb(224, 102, 255)", + "mediumorchid2": "rgb(209, 95, 238)", + "mediumorchid3": "rgb(180, 82, 205)", + "mediumorchid4": "rgb(122, 55, 139)", + "mediumpurple": "rgb(147, 112, 219)", + "mediumpurple1": "rgb(171, 130, 255)", + "mediumpurple2": "rgb(159, 121, 238)", + "mediumpurple3": "rgb(137, 104, 205)", + "mediumpurple4": "rgb(93, 71, 139)", + "mediumseagreen": "rgb(60, 179, 113)", + "mediumslateblue": "rgb(123, 104, 238)", + "mediumspringgreen": "rgb(0, 250, 154)", + "mediumturquoise": "rgb(72, 209, 204)", + "mediumvioletred": "rgb(199, 21, 133)", + "midnightblue": "rgb(25, 25, 112)", + "mintcream": "rgb(245, 255, 250)", + "mistyrose": "rgb(255, 228, 225)", + "mistyrose1": "rgb(255, 228, 225)", + "mistyrose2": "rgb(238, 213, 210)", + "mistyrose3": "rgb(205, 183, 181)", + "mistyrose4": "rgb(139, 125, 123)", + "moccasin": "rgb(255, 228, 181)", + "navajowhite": "rgb(255, 222, 173)", + "navajowhite1": "rgb(255, 222, 173)", + "navajowhite2": "rgb(238, 207, 161)", + "navajowhite3": "rgb(205, 179, 139)", + "navajowhite4": "rgb(139, 121, 94)", + "navy": "rgb(0, 0, 128)", + "navyblue": "rgb(0, 0, 128)", + "oldlace": "rgb(253, 245, 230)", + "olivedrab": "rgb(107, 142, 35)", + "olivedrab1": "rgb(192, 255, 62)", + "olivedrab2": "rgb(179, 238, 58)", + "olivedrab3": "rgb(154, 205, 50)", + "olivedrab4": "rgb(105, 139, 34)", + "orange": "rgb(255, 165, 0)", + "orange1": "rgb(255, 165, 0)", + "orange2": "rgb(238, 154, 0)", + "orange3": "rgb(205, 133, 0)", + "orange4": "rgb(139, 90, 0)", + "orangered": "rgb(255, 69, 0)", + "orangered1": "rgb(255, 69, 0)", + "orangered2": "rgb(238, 64, 0)", + "orangered3": "rgb(205, 55, 0)", + "orangered4": "rgb(139, 37, 0)", + "orchid": "rgb(218, 112, 214)", + "orchid1": "rgb(255, 131, 250)", + "orchid2": "rgb(238, 122, 233)", + "orchid3": "rgb(205, 105, 201)", + "orchid4": "rgb(139, 71, 137)", + "palegoldenrod": "rgb(238, 232, 170)", + "palegreen": "rgb(152, 251, 152)", + "palegreen1": "rgb(154, 255, 154)", + "palegreen2": "rgb(144, 238, 144)", + "palegreen3": "rgb(124, 205, 124)", + "palegreen4": "rgb(84, 139, 84)", + "paleturquoise": "rgb(175, 238, 238)", + "paleturquoise1": "rgb(187, 255, 255)", + "paleturquoise2": "rgb(174, 238, 238)", + "paleturquoise3": "rgb(150, 205, 205)", + "paleturquoise4": "rgb(102, 139, 139)", + "palevioletred": "rgb(219, 112, 147)", + "palevioletred1": "rgb(255, 130, 171)", + "palevioletred2": "rgb(238, 121, 159)", + "palevioletred3": "rgb(205, 104, 137)", + "palevioletred4": "rgb(139, 71, 93)", + "papayawhip": "rgb(255, 239, 213)", + "peachpuff": "rgb(255, 218, 185)", + "peachpuff1": "rgb(255, 218, 185)", + "peachpuff2": "rgb(238, 203, 173)", + "peachpuff3": "rgb(205, 175, 149)", + "peachpuff4": "rgb(139, 119, 101)", + "peru": "rgb(205, 133, 63)", + "pink": "rgb(255, 192, 203)", + "pink1": "rgb(255, 181, 197)", + "pink2": "rgb(238, 169, 184)", + "pink3": "rgb(205, 145, 158)", + "pink4": "rgb(139, 99, 108)", + "plum": "rgb(221, 160, 221)", + "plum1": "rgb(255, 187, 255)", + "plum2": "rgb(238, 174, 238)", + "plum3": "rgb(205, 150, 205)", + "plum4": "rgb(139, 102, 139)", + "powderblue": "rgb(176, 224, 230)", + "purple": "rgb(160, 32, 240)", + "purple1": "rgb(155, 48, 255)", + "purple2": "rgb(145, 44, 238)", + "purple3": "rgb(125, 38, 205)", + "purple4": "rgb(85, 26, 139)", + "red": "rgb(255, 0, 0)", + "red1": "rgb(255, 0, 0)", + "red2": "rgb(238, 0, 0)", + "red3": "rgb(205, 0, 0)", + "red4": "rgb(139, 0, 0)", + "rosybrown": "rgb(188, 143, 143)", + "rosybrown1": "rgb(255, 193, 193)", + "rosybrown2": "rgb(238, 180, 180)", + "rosybrown3": "rgb(205, 155, 155)", + "rosybrown4": "rgb(139, 105, 105)", + "royalblue": "rgb(65, 105, 225)", + "royalblue1": "rgb(72, 118, 255)", + "royalblue2": "rgb(67, 110, 238)", + "royalblue3": "rgb(58, 95, 205)", + "royalblue4": "rgb(39, 64, 139)", + "saddlebrown": "rgb(139, 69, 19)", + "salmon": "rgb(250, 128, 114)", + "salmon1": "rgb(255, 140, 105)", + "salmon2": "rgb(238, 130, 98)", + "salmon3": "rgb(205, 112, 84)", + "salmon4": "rgb(139, 76, 57)", + "sandybrown": "rgb(244, 164, 96)", + "seagreen": "rgb(46, 139, 87)", + "seagreen1": "rgb(84, 255, 159)", + "seagreen2": "rgb(78, 238, 148)", + "seagreen3": "rgb(67, 205, 128)", + "seagreen4": "rgb(46, 139, 87)", + "seashell": "rgb(255, 245, 238)", + "seashell1": "rgb(255, 245, 238)", + "seashell2": "rgb(238, 229, 222)", + "seashell3": "rgb(205, 197, 191)", + "seashell4": "rgb(139, 134, 130)", + "sienna": "rgb(160, 82, 45)", + "sienna1": "rgb(255, 130, 71)", + "sienna2": "rgb(238, 121, 66)", + "sienna3": "rgb(205, 104, 57)", + "sienna4": "rgb(139, 71, 38)", + "skyblue": "rgb(135, 206, 235)", + "skyblue1": "rgb(135, 206, 255)", + "skyblue2": "rgb(126, 192, 238)", + "skyblue3": "rgb(108, 166, 205)", + "skyblue4": "rgb(74, 112, 139)", + "slateblue": "rgb(106, 90, 205)", + "slateblue1": "rgb(131, 111, 255)", + "slateblue2": "rgb(122, 103, 238)", + "slateblue3": "rgb(105, 89, 205)", + "slateblue4": "rgb(71, 60, 139)", + "slategray": "rgb(112, 128, 144)", + "slategray1": "rgb(198, 226, 255)", + "slategray2": "rgb(185, 211, 238)", + "slategray3": "rgb(159, 182, 205)", + "slategray4": "rgb(108, 123, 139)", + "slategrey": "rgb(112, 128, 144)", + "snow": "rgb(255, 250, 250)", + "snow1": "rgb(255, 250, 250)", + "snow2": "rgb(238, 233, 233)", + "snow3": "rgb(205, 201, 201)", + "snow4": "rgb(139, 137, 137)", + "springgreen": "rgb(0, 255, 127)", + "springgreen1": "rgb(0, 255, 127)", + "springgreen2": "rgb(0, 238, 118)", + "springgreen3": "rgb(0, 205, 102)", + "springgreen4": "rgb(0, 139, 69)", + "steelblue": "rgb(70, 130, 180)", + "steelblue1": "rgb(99, 184, 255)", + "steelblue2": "rgb(92, 172, 238)", + "steelblue3": "rgb(79, 148, 205)", + "steelblue4": "rgb(54, 100, 139)", + "tan": "rgb(210, 180, 140)", + "tan1": "rgb(255, 165, 79)", + "tan2": "rgb(238, 154, 73)", + "tan3": "rgb(205, 133, 63)", + "tan4": "rgb(139, 90, 43)", + "thistle": "rgb(216, 191, 216)", + "thistle1": "rgb(255, 225, 255)", + "thistle2": "rgb(238, 210, 238)", + "thistle3": "rgb(205, 181, 205)", + "thistle4": "rgb(139, 123, 139)", + "tomato": "rgb(255, 99, 71)", + "tomato1": "rgb(255, 99, 71)", + "tomato2": "rgb(238, 92, 66)", + "tomato3": "rgb(205, 79, 57)", + "tomato4": "rgb(139, 54, 38)", + "turquoise": "rgb(64, 224, 208)", + "turquoise1": "rgb(0, 245, 255)", + "turquoise2": "rgb(0, 229, 238)", + "turquoise3": "rgb(0, 197, 205)", + "turquoise4": "rgb(0, 134, 139)", + "violet": "rgb(238, 130, 238)", + "violetred": "rgb(208, 32, 144)", + "violetred1": "rgb(255, 62, 150)", + "violetred2": "rgb(238, 58, 140)", + "violetred3": "rgb(205, 50, 120)", + "violetred4": "rgb(139, 34, 82)", + "wheat": "rgb(245, 222, 179)", + "wheat1": "rgb(255, 231, 186)", + "wheat2": "rgb(238, 216, 174)", + "wheat3": "rgb(205, 186, 150)", + "wheat4": "rgb(139, 126, 102)", + "white": "rgb(255, 255, 255)", + "whitesmoke": "rgb(245, 245, 245)", + "yellow": "rgb(255, 255, 0)", + "yellow1": "rgb(255, 255, 0)", + "yellow2": "rgb(238, 238, 0)", + "yellow3": "rgb(205, 205, 0)", + "yellow4": "rgb(139, 139, 0)", + "yellowgreen": "rgb(154, 205, 50)" +}; +// SOURCE FILE: libdot/js/lib_f.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Grab bag of utility functions. + */ +lib.f = {}; + +/** + * Create a unique enum value. + * + * @suppress {lintChecks} + * @param {string} name A human friendly name for debugging. + * @return {Object} A unique enum that won't compare equal to anything else. + */ +lib.f.createEnum = function(name) { + // We use a String object as nothing else should be using them -- we want to + // use string primitives normally. But debuggers will include our name. + // eslint-disable-next-line no-new-wrappers + return new String(name); +}; + +/** + * Replace variable references in a string. + * + * Variables are of the form %FUNCTION(VARNAME). FUNCTION is an optional + * escape function to apply to the value. + * + * For example + * lib.f.replaceVars("%(greeting), %encodeURIComponent(name)", + * { greeting: "Hello", + * name: "Google+" }); + * + * Will result in "Hello, Google%2B". + */ +lib.f.replaceVars = function(str, vars) { + return str.replace(/%([a-z]*)\(([^\)]+)\)/gi, function(match, fn, varname) { + if (typeof vars[varname] == 'undefined') + throw 'Unknown variable: ' + varname; + + var rv = vars[varname]; + + if (fn in lib.f.replaceVars.functions) { + rv = lib.f.replaceVars.functions[fn](rv); + } else if (fn) { + throw 'Unknown escape function: ' + fn; + } + + return rv; + }); +}; + +/** + * Functions that can be used with replaceVars. + * + * Clients can add to this list to extend lib.f.replaceVars(). + */ +lib.f.replaceVars.functions = { + encodeURI: encodeURI, + encodeURIComponent: encodeURIComponent, + escapeHTML: function(str) { + var map = { + '<': '<', + '>': '>', + '&': '&', + '"': '"', + "'": ''' + }; + + return str.replace(/[<>&\"\']/g, (m) => map[m]); + } +}; + +/** + * Parse a query string into a hash. + * + * This takes a url query string in the form 'name1=value&name2=value' and + * converts it into an object of the form { name1: 'value', name2: 'value' }. + * If a given name appears multiple times in the query string, only the + * last value will appear in the result. If the name ends with [], it is + * turned into an array. + * + * Names and values are passed through decodeURIComponent before being added + * to the result object. + * + * @param {string} queryString The string to parse. If it starts with a + * leading '?', the '?' will be ignored. + */ +lib.f.parseQuery = function(queryString) { + if (queryString.startsWith('?')) + queryString = queryString.substr(1); + + var rv = {}; + + var pairs = queryString.split('&'); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i].split('='); + let key = decodeURIComponent(pair[0]); + let val = decodeURIComponent(pair[1]); + + if (key.endsWith('[]')) { + // It's an array. + key = key.slice(0, -2); + // The key doesn't exist, or wasn't an array before. + if (!(rv[key] instanceof Array)) + rv[key] = []; + rv[key].push(val); + } else { + // It's a plain string. + rv[key] = val; + } + } + + return rv; +}; + +lib.f.getURL = function(path) { + if (lib.f.getURL.chromeSupported()) + return chrome.runtime.getURL(path); + + return path; +}; + +lib.f.getURL.chromeSupported = function() { + return window.chrome && chrome.runtime && chrome.runtime.getURL; +}; + +/** + * Clamp a given integer to a specified range. + * + * @param {integer} v The value to be clamped. + * @param {integer} min The minimum acceptable value. + * @param {integer} max The maximum acceptable value. + */ +lib.f.clamp = function(v, min, max) { + if (v < min) + return min; + if (v > max) + return max; + return v; +}; + +/** + * Left pad a number to a given length with leading zeros. + * + * @param {string|integer} number The number to pad. + * @param {integer} length The desired length. + * @return {string} The padded number as a string. + */ +lib.f.zpad = function(number, length) { + return String(number).padStart(length, '0'); +}; + +/** + * Return a string containing a given number of space characters. + * + * This method maintains a static cache of the largest amount of whitespace + * ever requested. It shouldn't be used to generate an insanely huge amount of + * whitespace. + * + * @param {integer} length The desired amount of whitespace. + * @param {string} A string of spaces of the requested length. + */ +lib.f.getWhitespace = function(length) { + if (length <= 0) + return ''; + + var f = this.getWhitespace; + if (!f.whitespace) + f.whitespace = ' '; + + while (length > f.whitespace.length) { + f.whitespace += f.whitespace; + } + + return f.whitespace.substr(0, length); +}; + + /** + * Ensure that a function is called within a certain time limit. + * + * Simple usage looks like this... + * + * lib.registerInit(lib.f.alarm(onInit)); + * + * This will log a warning to the console if onInit() is not invoked within + * 5 seconds. + * + * If you're performing some operation that may take longer than 5 seconds you + * can pass a duration in milliseconds as the optional second parameter. + * + * If you pass a string identifier instead of a callback function, you'll get a + * wrapper generator rather than a single wrapper. Each call to the + * generator will return a wrapped version of the callback wired to + * a shared timeout. This is for cases where you want to ensure that at least + * one of a set of callbacks is invoked before a timeout expires. + * + * var alarm = lib.f.alarm('fetch object'); + * lib.foo.fetchObject(alarm(onSuccess), alarm(onFailure)); + * + * @param {function(*)} callback The function to wrap in an alarm. + * @param {int} opt_ms Optional number of milliseconds to wait before raising + * an alarm. Default is 5000 (5 seconds). + * @return {function} If callback is a function then the return value will be + * the wrapped callback. If callback is a string then the return value will + * be a function that generates new wrapped callbacks. + */ +lib.f.alarm = function(callback, opt_ms) { + var ms = opt_ms || 5 * 1000; + var stack = lib.f.getStack(1); + + return (function() { + // This outer function is called immediately. It's here to capture a new + // scope for the timeout variable. + + // The 'timeout' variable is shared by this timeout function, and the + // callback wrapper. + var timeout = setTimeout(function() { + var name = (typeof callback == 'string') ? name : callback.name; + name = name ? (': ' + name) : ''; + console.warn('lib.f.alarm: timeout expired: ' + (ms / 1000) + 's' + name); + console.log(stack); + timeout = null; + }, ms); + + var wrapperGenerator = function(callback) { + return function() { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + + return callback.apply(null, arguments); + }; + }; + + if (typeof callback == 'string') + return wrapperGenerator; + + return wrapperGenerator(callback); + })(); +}; + +/** + * Return the current call stack after skipping a given number of frames. + * + * This method is intended to be used for debugging only. It returns an + * Object instead of an Array, because the console stringifies arrays by + * default and that's not what we want. + * + * A typical call might look like... + * + * console.log('Something wicked this way came', lib.f.getStack()); + * // Notice the comma ^ + * + * This would print the message to the js console, followed by an object + * which can be clicked to reveal the stack. + * + * @param {number=} ignoreFrames How many inner stack frames to ignore. The + * innermost 'getStack' call is always ignored. + * @param {number=} count How many frames to return. + */ +lib.f.getStack = function(ignoreFrames = 0, count = undefined) { + const stackArray = (new Error()).stack.split('\n'); + + // Always ignore the Error() object and getStack call itself. + // [0] = 'Error' + // [1] = ' at Object.lib.f.getStack (file:///.../lib_f.js:267:23)' + ignoreFrames += 2; + + const max = stackArray.length - ignoreFrames; + if (count === undefined) + count = max; + else + count = lib.f.clamp(count, 0, max); + + // Remove the leading spaces and "at" from each line: + // ' at window.onload (file:///.../lib_test.js:11:18)' + const stackObject = new Array(); + for (let i = ignoreFrames; i < count + ignoreFrames; ++i) + stackObject.push(stackArray[i].replace(/^\s*at\s+/, '')); + + return stackObject; +}; + +/** + * Divides the two numbers and floors the results, unless the remainder is less + * than an incredibly small value, in which case it returns the ceiling. + * This is useful when the number are truncated approximations of longer + * values, and so doing division with these numbers yields a result incredibly + * close to a whole number. + * + * @param {number} numerator + * @param {number} denominator + * @return {number} + */ +lib.f.smartFloorDivide = function(numerator, denominator) { + var val = numerator / denominator; + var ceiling = Math.ceil(val); + if (ceiling - val < .0001) { + return ceiling; + } else { + return Math.floor(val); + } +}; + +/** + * Get a random integer in a range (inclusive). + * + * @param {number} min The lowest integer in the range. + * @param {number} max The highest integer in the range. + * @return {number} A random number between min & max. + */ +lib.f.randomInt = function(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +}; + +/** + * Get the current OS. + * + * @return {Promise} A promise that resolves to a constant in + * runtime.PlatformOs. + */ +lib.f.getOs = function() { + // Try the brower extensions API. + if (window.browser && browser.runtime && browser.runtime.getPlatformInfo) + return browser.runtime.getPlatformInfo().then((info) => info.os); + + // Use the native Chrome API if available. + if (window.chrome && chrome.runtime && chrome.runtime.getPlatformInfo) { + return new Promise((resolve, reject) => + chrome.runtime.getPlatformInfo((info) => resolve(info.os))); + } + + // Fallback logic. Capture the major OS's. The rest should support the + // browser API above. + if (window.navigator && navigator.userAgent) { + const ua = navigator.userAgent; + if (ua.includes('Mac OS X')) + return Promise.resolve('mac'); + else if (ua.includes('CrOS')) + return Promise.resolve('cros'); + else if (ua.includes('Linux')) + return Promise.resolve('linux'); + else if (ua.includes('Android')) + return Promise.resolve('android'); + else if (ua.includes('Windows')) + return Promise.resolve('windows'); + } + + // Still here? No idea. + return Promise.reject(null); +}; + +/** + * Get the current Chrome milestone version. + * + * @return {number} The milestone number if we're running on Chrome, else NaN. + */ +lib.f.getChromeMilestone = function() { + if (window.navigator && navigator.userAgent) { + const ary = navigator.userAgent.match(/\sChrome\/(\d+)/); + if (ary) + return parseInt(ary[1]); + } + + // Returning NaN will make all number comparisons fail. + return NaN; +}; + +/** + * Return the lastError string in the browser. + * + * This object might live in different locations, and it isn't always defined + * (if there hasn't been a "last error"). Wrap all that ugliness here. + * + * @param {string=} defaultMsg The default message if no error is found. + * @return {string} The last error message from the browser. + */ +lib.f.lastError = function(defaultMsg = null) { + let lastError; + if (window.browser && browser.runtime) + lastError = browser.runtime.lastError; + else if (window.chrome && chrome.runtime) + lastError = chrome.runtime.lastError; + + if (lastError && lastError.message) + return lastError.message; + else + return defaultMsg; +}; +// SOURCE FILE: libdot/js/lib_i18n.js +// Copyright 2018 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Wrappers over the browser i18n helpers. + * + * Arguably some of these functions should be l10n, but oh well. + */ +lib.i18n = {}; + +/** + * Convenience shortcut to the browser i18n object. + */ +lib.i18n.browser_ = + window.browser && browser.i18n ? browser.i18n : + window.chrome && chrome.i18n ? chrome.i18n : + null; + +/** + * Get the list of accepted UI languages. + * + * https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/i18n/getAcceptLanguages + * + * @param {function(Array)} callback Function to invoke with the results. The + * parameter is a list of locale names. + */ +lib.i18n.getAcceptLanguages = function(callback) { + if (lib.i18n.browser_) { + lib.i18n.browser_.getAcceptLanguages(callback); + } else { + setTimeout(function() { + callback([navigator.language.replace(/-/g, '_')]); + }, 0); + } +}; + +/** + * Get a message by name, optionally replacing arguments too. + * + * https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/i18n/getMessage + * + * @param {string} msgname The id for this localized string. + * @param {string[]=} substitutions Any replacements in the string. + * @param {string=} fallback Translation if the message wasn't found. + * @return {string} The translated message. + */ +lib.i18n.getMessage = function(msgname, substitutions = [], fallback = '') { + // First let the native browser APIs handle everything for us. + if (lib.i18n.browser_) { + const message = lib.i18n.browser_.getMessage(msgname, substitutions); + if (message) + return message; + } + + // Do our best to get something reasonable. + return lib.i18n.replaceReferences(fallback, substitutions); +}; + +/** + * Replace $1...$n references with the elements of the args array. + * + * This largely behaves like Chrome's getMessage helper. The $# references are + * always replaced/removed regardless of the specified substitutions. + * + * @param {string} msg String containing the message and argument references. + * @param {string[]=} args Array containing the argument values. + * @return {string} The message with replacements expanded. + */ +lib.i18n.replaceReferences = function(msg, args = []) { + // The Chrome API allows a single substitution as a string rather than array. + if (args === null) { + args = []; + } + if (!(args instanceof Array)) { + args = [args]; + } + + return msg.replace(/\$(\d+)/g, (m, index) => { + return index <= args.length ? args[index - 1] : ''; + }); +}; +// SOURCE FILE: libdot/js/lib_message_manager.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * MessageManager class handles internationalized strings. + * + * Note: chrome.i18n isn't sufficient because... + * 1. There's a bug in chrome that makes it unavailable in iframes: + * https://crbug.com/130200 + * 2. The client code may not be packaged in a Chrome extension. + * 3. The client code may be part of a library packaged in a third-party + * Chrome extension. + * + * @param {Array} languages List of languages to load, in the order they + * should be loaded. Newer messages replace older ones. 'en' is + * automatically added as the first language if it is not already present. + */ +lib.MessageManager = function(languages) { + this.languages_ = languages.map((el) => el.replace(/-/g, '_')); + + if (this.languages_.indexOf('en') == -1) + this.languages_.unshift('en'); + + this.messages = {}; +}; + +/** + * Add message definitions to the message manager. + * + * This takes an object of the same format of a Chrome messages.json file. See + * . + */ +lib.MessageManager.prototype.addMessages = function(defs) { + for (var key in defs) { + var def = defs[key]; + + if (!def.placeholders) { + this.messages[key] = def.message; + } else { + // Replace "$NAME$" placeholders with "$1", etc. + this.messages[key] = def.message.replace( + /\$([a-z][^\s\$]+)\$/ig, + function(m, name) { + return defs[key].placeholders[name.toLowerCase()].content; + }); + } + } +}; + +/** + * Load the first available language message bundle. + * + * @param {string} pattern A url pattern containing a "$1" where the locale + * name should go. + * @param {function(Array,Array)} onComplete Function to be called when loading + * is complete. The two arrays are the list of successful and failed + * locale names. If the first parameter is length 0, no locales were + * loaded. + */ +lib.MessageManager.prototype.findAndLoadMessages = function( + pattern, onComplete) { + var languages = this.languages_.concat(); + var loaded = []; + var failed = []; + + function onLanguageComplete(state) { + if (state) { + loaded = languages.shift(); + } else { + failed = languages.shift(); + } + + if (languages.length) { + tryNextLanguage(); + } else { + onComplete(loaded, failed); + } + } + + var tryNextLanguage = function() { + this.loadMessages(this.replaceReferences(pattern, languages), + onLanguageComplete.bind(this, true), + onLanguageComplete.bind(this, false)); + }.bind(this); + + tryNextLanguage(); +}; + +/** + * Load messages from a messages.json file. + */ +lib.MessageManager.prototype.loadMessages = function( + url, onSuccess, opt_onError) { + var xhr = new XMLHttpRequest(); + + xhr.onload = () => { + this.addMessages(JSON.parse(xhr.responseText)); + onSuccess(); + }; + if (opt_onError) + xhr.onerror = () => opt_onError(xhr); + + xhr.open('GET', url); + xhr.send(); +}; + +/** + * Per-instance copy of replaceReferences. + */ +lib.MessageManager.prototype.replaceReferences = lib.i18n.replaceReferences; + +/** + * Get a message by name, optionally replacing arguments too. + * + * @param {string} msgname String containing the name of the message to get. + * @param {Array} opt_args Optional array containing the argument values. + * @param {string} opt_default Optional value to return if the msgname is not + * found. Returns the message name by default. + */ +lib.MessageManager.prototype.get = function(msgname, opt_args, opt_default) { + // First try the integrated browser getMessage. We prefer that over any + // registered messages as only the browser supports translations. + let message = lib.i18n.getMessage(msgname, opt_args); + if (message) + return message; + + // Look it up in the registered cache next. + message = this.messages[msgname]; + if (!message) { + console.warn('Unknown message: ' + msgname); + message = opt_default === undefined ? msgname : opt_default; + // Register the message with the default to avoid multiple warnings. + this.messages[msgname] = message; + } + + return this.replaceReferences(message, opt_args); +}; + +/** + * Process all of the "i18n" html attributes found in a given dom fragment. + * + * The real work happens in processI18nAttribute. + */ +lib.MessageManager.prototype.processI18nAttributes = function(dom) { + var nodes = dom.querySelectorAll('[i18n]'); + + for (var i = 0; i < nodes.length; i++) + this.processI18nAttribute(nodes[i]); +}; + +/** + * Process the "i18n" attribute in the specified node. + * + * The i18n attribute should contain a JSON object. The keys are taken to + * be attribute names, and the values are message names. + * + * If the JSON object has a "_" (underscore) key, its value is used as the + * textContent of the element. + * + * Message names can refer to other attributes on the same element with by + * prefixing with a dollar sign. For example... + * + * + * + * The aria-label message name will be computed as "SEND_BUTTON_ARIA_LABEL". + * Notice that the "id" attribute was appended to the target attribute, and + * the result converted to UPPER_AND_UNDER style. + */ +lib.MessageManager.prototype.processI18nAttribute = function(node) { + // Convert the "lower-and-dashes" attribute names into + // "UPPER_AND_UNDER" style. + const thunk = (str) => str.replace(/-/g, '_').toUpperCase(); + + var i18n = node.getAttribute('i18n'); + if (!i18n) + return; + + try { + i18n = JSON.parse(i18n); + } catch (ex) { + console.error('Can\'t parse ' + node.tagName + '#' + node.id + ': ' + i18n); + throw ex; + } + + // Load all the messages specified in the i18n attributes. + for (var key in i18n) { + // The node attribute we'll be setting. + var attr = key; + + var msgname = i18n[key]; + // For "=foo", re-use the referenced message name. + if (msgname.startsWith('=')) { + key = msgname.substr(1); + msgname = i18n[key]; + } + + // For "$foo", calculate the message name. + if (msgname.startsWith('$')) + msgname = thunk(node.getAttribute(msgname.substr(1)) + '_' + key); + + // Finally load the message. + var msg = this.get(msgname); + if (attr == '_') + node.textContent = msg; + else + node.setAttribute(attr, msg); + } +}; +// SOURCE FILE: libdot/js/lib_preference_manager.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Constructor for lib.PreferenceManager objects. + * + * These objects deal with persisting changes to stable storage and notifying + * consumers when preferences change. + * + * It is intended that the backing store could be something other than HTML5 + * storage, but there aren't any use cases at the moment. In the future there + * may be a chrome api to store sync-able name/value pairs, and we'd want + * that. + * + * @param {lib.Storage.*} storage The storage object to use as a backing + * store. + * @param {string} opt_prefix The optional prefix to be used for all preference + * names. The '/' character should be used to separate levels of hierarchy, + * if you're going to have that kind of thing. If provided, the prefix + * should start with a '/'. If not provided, it defaults to '/'. + */ +lib.PreferenceManager = function(storage, opt_prefix) { + this.storage = storage; + this.storageObserver_ = this.onStorageChange_.bind(this); + + this.isActive_ = false; + this.activate(); + + this.trace = false; + + var prefix = opt_prefix || '/'; + if (!prefix.endsWith('/')) + prefix += '/'; + + this.prefix = prefix; + + this.prefRecords_ = {}; + this.globalObservers_ = []; + + this.childFactories_ = {}; + + // Map of list-name to {map of child pref managers} + // As in... + // + // this.childLists_ = { + // 'profile-ids': { + // 'one': PreferenceManager, + // 'two': PreferenceManager, + // ... + // }, + // + // 'frob-ids': { + // ... + // } + // } + this.childLists_ = {}; +}; + +/** + * Used internally to indicate that the current value of the preference should + * be taken from the default value defined with the preference. + * + * Equality tests against this value MUST use '===' or '!==' to be accurate. + */ +lib.PreferenceManager.prototype.DEFAULT_VALUE = lib.f.createEnum('DEFAULT'); + +/** + * An individual preference. + * + * These objects are managed by the PreferenceManager, you shouldn't need to + * handle them directly. + */ +lib.PreferenceManager.Record = function(name, defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + this.currentValue = this.DEFAULT_VALUE; + this.observers = []; +}; + +/** + * A local copy of the DEFAULT_VALUE constant to make it less verbose. + */ +lib.PreferenceManager.Record.prototype.DEFAULT_VALUE = + lib.PreferenceManager.prototype.DEFAULT_VALUE; + +/** + * Register a callback to be invoked when this preference changes. + * + * @param {function(value, string, lib.PreferenceManager} observer The function + * to invoke. It will receive the new value, the name of the preference, + * and a reference to the PreferenceManager as parameters. + */ +lib.PreferenceManager.Record.prototype.addObserver = function(observer) { + this.observers.push(observer); +}; + +/** + * Unregister an observer callback. + * + * @param {function} observer A previously registered callback. + */ +lib.PreferenceManager.Record.prototype.removeObserver = function(observer) { + var i = this.observers.indexOf(observer); + if (i >= 0) + this.observers.splice(i, 1); +}; + +/** + * Fetch the value of this preference. + */ +lib.PreferenceManager.Record.prototype.get = function() { + if (this.currentValue === this.DEFAULT_VALUE) { + if (/^(string|number)$/.test(typeof this.defaultValue)) + return this.defaultValue; + + if (typeof this.defaultValue == 'object') { + // We want to return a COPY of the default value so that users can + // modify the array or object without changing the default value. + return JSON.parse(JSON.stringify(this.defaultValue)); + } + + return this.defaultValue; + } + + return this.currentValue; +}; + +/** + * Stop this preference manager from tracking storage changes. + * + * Call this if you're going to swap out one preference manager for another so + * that you don't get notified about irrelevant changes. + */ +lib.PreferenceManager.prototype.deactivate = function() { + if (!this.isActive_) + throw new Error('Not activated'); + + this.isActive_ = false; + this.storage.removeObserver(this.storageObserver_); +}; + +/** + * Start tracking storage changes. + * + * If you previously deactivated this preference manager, you can reactivate it + * with this method. You don't need to call this at initialization time, as + * it's automatically called as part of the constructor. + */ +lib.PreferenceManager.prototype.activate = function() { + if (this.isActive_) + throw new Error('Already activated'); + + this.isActive_ = true; + this.storage.addObserver(this.storageObserver_); +}; + +/** + * Read the backing storage for these preferences. + * + * You should do this once at initialization time to prime the local cache + * of preference values. The preference manager will monitor the backing + * storage for changes, so you should not need to call this more than once. + * + * This function recursively reads storage for all child preference managers as + * well. + * + * This function is asynchronous, if you need to read preference values, you + * *must* wait for the callback. + * + * @param {function()} opt_callback Optional function to invoke when the read + * has completed. + */ +lib.PreferenceManager.prototype.readStorage = function(opt_callback) { + var pendingChildren = 0; + + function onChildComplete() { + if (--pendingChildren == 0 && opt_callback) + opt_callback(); + } + + var keys = Object.keys(this.prefRecords_).map((el) => this.prefix + el); + + if (this.trace) + console.log('Preferences read: ' + this.prefix); + + this.storage.getItems(keys, function(items) { + var prefixLength = this.prefix.length; + + for (var key in items) { + var value = items[key]; + var name = key.substr(prefixLength); + var needSync = (name in this.childLists_ && + (JSON.stringify(value) != + JSON.stringify(this.prefRecords_[name].currentValue))); + + this.prefRecords_[name].currentValue = value; + + if (needSync) { + pendingChildren++; + this.syncChildList(name, onChildComplete); + } + } + + if (pendingChildren == 0 && opt_callback) + setTimeout(opt_callback); + }.bind(this)); +}; + +/** + * Define a preference. + * + * This registers a name, default value, and onChange handler for a preference. + * + * @param {string} name The name of the preference. This will be prefixed by + * the prefix of this PreferenceManager before written to local storage. + * @param {string|number|boolean|Object|Array|null} value The default value of + * this preference. Anything that can be represented in JSON is a valid + * default value. + * @param {function(value, string, lib.PreferenceManager} opt_observer A + * function to invoke when the preference changes. It will receive the new + * value, the name of the preference, and a reference to the + * PreferenceManager as parameters. + */ +lib.PreferenceManager.prototype.definePreference = function( + name, value, opt_onChange) { + + var record = this.prefRecords_[name]; + if (record) { + this.changeDefault(name, value); + } else { + record = this.prefRecords_[name] = + new lib.PreferenceManager.Record(name, value); + } + + if (opt_onChange) + record.addObserver(opt_onChange); +}; + +/** + * Define multiple preferences with a single function call. + * + * @param {Array} defaults An array of 3-element arrays. Each three element + * array should contain the [key, value, onChange] parameters for a + * preference. + */ +lib.PreferenceManager.prototype.definePreferences = function(defaults) { + for (var i = 0; i < defaults.length; i++) { + this.definePreference(defaults[i][0], defaults[i][1], defaults[i][2]); + } +}; + +/** + * Define an ordered list of child preferences. + * + * Child preferences are different from just storing an array of JSON objects + * in that each child is an instance of a preference manager. This means you + * can observe changes to individual child preferences, and get some validation + * that you're not reading or writing to an undefined child preference value. + * + * @param {string} listName A name for the list of children. This must be + * unique in this preference manager. The listName will become a + * preference on this PreferenceManager used to store the ordered list of + * child ids. It is also used in get/add/remove operations to identify the + * list of children to operate on. + * @param {function} childFactory A function that will be used to generate + * instances of these children. The factory function will receive the + * parent lib.PreferenceManager object and a unique id for the new child + * preferences. + */ +lib.PreferenceManager.prototype.defineChildren = function( + listName, childFactory) { + + // Define a preference to hold the ordered list of child ids. + this.definePreference(listName, [], + this.onChildListChange_.bind(this, listName)); + this.childFactories_[listName] = childFactory; + this.childLists_[listName] = {}; +}; + +/** + * Register to observe preference changes. + * + * @param {Function} global A callback that will happen for every preference. + * Pass null if you don't need one. + * @param {Object} map A map of preference specific callbacks. Pass null if + * you don't need any. + */ +lib.PreferenceManager.prototype.addObservers = function(global, map) { + if (global && typeof global != 'function') + throw new Error('Invalid param: globals'); + + if (global) + this.globalObservers_.push(global); + + if (!map) + return; + + for (var name in map) { + if (!(name in this.prefRecords_)) + throw new Error('Unknown preference: ' + name); + + this.prefRecords_[name].addObserver(map[name]); + } +}; + +/** + * Dispatch the change observers for all known preferences. + * + * It may be useful to call this after readStorage completes, in order to + * get application state in sync with user preferences. + * + * This can be used if you've changed a preference manager out from under + * a live object, for example when switching to a different prefix. + */ +lib.PreferenceManager.prototype.notifyAll = function() { + for (var name in this.prefRecords_) { + this.notifyChange_(name); + } +}; + +/** + * Notify the change observers for a given preference. + * + * @param {string} name The name of the preference that changed. + */ +lib.PreferenceManager.prototype.notifyChange_ = function(name) { + var record = this.prefRecords_[name]; + if (!record) + throw new Error('Unknown preference: ' + name); + + var currentValue = record.get(); + + for (var i = 0; i < this.globalObservers_.length; i++) + this.globalObservers_[i](name, currentValue); + + for (var i = 0; i < record.observers.length; i++) { + record.observers[i](currentValue, name, this); + } +}; + +/** + * Create a new child PreferenceManager for the given child list. + * + * The optional hint parameter is an opaque prefix added to the auto-generated + * unique id for this child. Your child factory can parse out the prefix + * and use it. + * + * @param {string} listName The child list to create the new instance from. + * @param {string} opt_hint Optional hint to include in the child id. + * @param {string} opt_id Optional id to override the generated id. + */ +lib.PreferenceManager.prototype.createChild = function(listName, opt_hint, + opt_id) { + var ids = this.get(listName); + var id; + + if (opt_id) { + id = opt_id; + if (ids.indexOf(id) != -1) + throw new Error('Duplicate child: ' + listName + ': ' + id); + + } else { + // Pick a random, unique 4-digit hex identifier for the new profile. + while (!id || ids.indexOf(id) != -1) { + id = lib.f.randomInt(1, 0xffff).toString(16); + id = lib.f.zpad(id, 4); + if (opt_hint) + id = opt_hint + ':' + id; + } + } + + var childManager = this.childFactories_[listName](this, id); + childManager.trace = this.trace; + childManager.resetAll(); + + this.childLists_[listName][id] = childManager; + + ids.push(id); + this.set(listName, ids); + + return childManager; +}; + +/** + * Remove a child preferences instance. + * + * Removes a child preference manager and clears any preferences stored in it. + * + * @param {string} listName The name of the child list containing the child to + * remove. + * @param {string} id The child ID. + */ +lib.PreferenceManager.prototype.removeChild = function(listName, id) { + var prefs = this.getChild(listName, id); + prefs.resetAll(); + + var ids = this.get(listName); + var i = ids.indexOf(id); + if (i != -1) { + ids.splice(i, 1); + this.set(listName, ids); + } + + delete this.childLists_[listName][id]; +}; + +/** + * Return a child PreferenceManager instance for a given id. + * + * If the child list or child id is not known this will return the specified + * default value or throw an exception if no default value is provided. + * + * @param {string} listName The child list to look in. + * @param {string} id The child ID. + * @param {*} opt_default The optional default value to return if the child + * is not found. + */ +lib.PreferenceManager.prototype.getChild = function(listName, id, opt_default) { + if (!(listName in this.childLists_)) + throw new Error('Unknown child list: ' + listName); + + var childList = this.childLists_[listName]; + if (!(id in childList)) { + if (typeof opt_default == 'undefined') + throw new Error('Unknown "' + listName + '" child: ' + id); + + return opt_default; + } + + return childList[id]; +}; + +/** + * Calculate the difference between two lists of child ids. + * + * Given two arrays of child ids, this function will return an object + * with "added", "removed", and "common" properties. Each property is + * a map of child-id to `true`. For example, given... + * + * a = ['child-x', 'child-y'] + * b = ['child-y'] + * + * diffChildLists(a, b) => + * { added: { 'child-x': true }, removed: {}, common: { 'child-y': true } } + * + * The added/removed properties assume that `a` is the current list. + * + * @param {Array[string]} a The most recent list of child ids. + * @param {Array[string]} b An older list of child ids. + * @return {Object} An object with added/removed/common properties. + */ +lib.PreferenceManager.diffChildLists = function(a, b) { + var rv = { + added: {}, + removed: {}, + common: {}, + }; + + for (var i = 0; i < a.length; i++) { + if (b.indexOf(a[i]) != -1) { + rv.common[a[i]] = true; + } else { + rv.added[a[i]] = true; + } + } + + for (var i = 0; i < b.length; i++) { + if ((b[i] in rv.added) || (b[i] in rv.common)) + continue; + + rv.removed[b[i]] = true; + } + + return rv; +}; + +/** + * Synchronize a list of child PreferenceManagers instances with the current + * list stored in prefs. + * + * This will instantiate any missing managers and read current preference values + * from storage. Any active managers that no longer appear in preferences will + * be deleted. + * + * @param {string} listName The child list to synchronize. + * @param {function()} opt_callback Optional function to invoke when the sync + * is complete. + */ +lib.PreferenceManager.prototype.syncChildList = function( + listName, opt_callback) { + + var pendingChildren = 0; + function onChildStorage() { + if (--pendingChildren == 0 && opt_callback) + opt_callback(); + } + + // The list of child ids that we *should* have a manager for. + var currentIds = this.get(listName); + + // The known managers at the start of the sync. Any manager still in this + // list at the end should be discarded. + var oldIds = Object.keys(this.childLists_[listName]); + + var rv = lib.PreferenceManager.diffChildLists(currentIds, oldIds); + + for (var i = 0; i < currentIds.length; i++) { + var id = currentIds[i]; + + var managerIndex = oldIds.indexOf(id); + if (managerIndex >= 0) + oldIds.splice(managerIndex, 1); + + if (!this.childLists_[listName][id]) { + var childManager = this.childFactories_[listName](this, id); + if (!childManager) { + console.warn('Unable to restore child: ' + listName + ': ' + id); + continue; + } + + childManager.trace = this.trace; + this.childLists_[listName][id] = childManager; + pendingChildren++; + childManager.readStorage(onChildStorage); + } + } + + for (var i = 0; i < oldIds.length; i++) { + delete this.childLists_[listName][oldIds[i]]; + } + + if (!pendingChildren && opt_callback) + setTimeout(opt_callback); +}; + +/** + * Reset a preference to its default state. + * + * This will dispatch the onChange handler if the preference value actually + * changes. + * + * @param {string} name The preference to reset. + */ +lib.PreferenceManager.prototype.reset = function(name) { + var record = this.prefRecords_[name]; + if (!record) + throw new Error('Unknown preference: ' + name); + + this.storage.removeItem(this.prefix + name); + + if (record.currentValue !== this.DEFAULT_VALUE) { + record.currentValue = this.DEFAULT_VALUE; + this.notifyChange_(name); + } +}; + +/** + * Reset all preferences back to their default state. + */ +lib.PreferenceManager.prototype.resetAll = function() { + var changed = []; + + for (var listName in this.childLists_) { + var childList = this.childLists_[listName]; + for (var id in childList) { + childList[id].resetAll(); + } + } + + for (var name in this.prefRecords_) { + if (this.prefRecords_[name].currentValue !== this.DEFAULT_VALUE) { + this.prefRecords_[name].currentValue = this.DEFAULT_VALUE; + changed.push(name); + } + } + + var keys = Object.keys(this.prefRecords_).map(function(el) { + return this.prefix + el; + }.bind(this)); + + this.storage.removeItems(keys); + + changed.forEach(this.notifyChange_.bind(this)); +}; + +/** + * Return true if two values should be considered not-equal. + * + * If both values are the same scalar type and compare equal this function + * returns false (no difference), otherwise return true. + * + * This is used in places where we want to check if a preference has changed. + * Rather than take the time to compare complex values we just consider them + * to always be different. + * + * @param {*} a A value to compare. + * @param {*} b A value to compare. + */ +lib.PreferenceManager.prototype.diff = function(a, b) { + // If the types are different, or the type is not a simple primitive one. + if ((typeof a) !== (typeof b) || + !(/^(undefined|boolean|number|string)$/.test(typeof a))) { + return true; + } + + return a !== b; +}; + +/** + * Change the default value of a preference. + * + * This is useful when subclassing preference managers. + * + * The function does not alter the current value of the preference, unless + * it has the old default value. When that happens, the change observers + * will be notified. + * + * @param {string} name The name of the parameter to change. + * @param {*} newValue The new default value for the preference. + */ +lib.PreferenceManager.prototype.changeDefault = function(name, newValue) { + var record = this.prefRecords_[name]; + if (!record) + throw new Error('Unknown preference: ' + name); + + if (!this.diff(record.defaultValue, newValue)) { + // Default value hasn't changed. + return; + } + + if (record.currentValue !== this.DEFAULT_VALUE) { + // This pref has a specific value, just change the default and we're done. + record.defaultValue = newValue; + return; + } + + record.defaultValue = newValue; + + this.notifyChange_(name); +}; + +/** + * Change the default value of multiple preferences. + * + * @param {Object} map A map of name -> value pairs specifying the new default + * values. + */ +lib.PreferenceManager.prototype.changeDefaults = function(map) { + for (var key in map) { + this.changeDefault(key, map[key]); + } +}; + +/** + * Set a preference to a specific value. + * + * This will dispatch the onChange handler if the preference value actually + * changes. + * + * @param {string} key The preference to set. + * @param {*} value The value to set. Anything that can be represented in + * JSON is a valid value. + */ +lib.PreferenceManager.prototype.set = function(name, newValue) { + var record = this.prefRecords_[name]; + if (!record) + throw new Error('Unknown preference: ' + name); + + var oldValue = record.get(); + + if (!this.diff(oldValue, newValue)) + return; + + if (this.diff(record.defaultValue, newValue)) { + record.currentValue = newValue; + this.storage.setItem(this.prefix + name, newValue); + } else { + record.currentValue = this.DEFAULT_VALUE; + this.storage.removeItem(this.prefix + name); + } + + // We need to manually send out the notification on this instance. If we + // The storage event won't fire a notification because we've already changed + // the currentValue, so it won't see a difference. If we delayed changing + // currentValue until the storage event, a pref read immediately after a write + // would return the previous value. + // + // The notification is in a timeout so clients don't accidentally depend on + // a synchronous notification. + setTimeout(this.notifyChange_.bind(this, name), 0); +}; + +/** + * Get the value of a preference. + * + * @param {string} key The preference to get. + */ +lib.PreferenceManager.prototype.get = function(name) { + var record = this.prefRecords_[name]; + if (!record) + throw new Error('Unknown preference: ' + name); + + return record.get(); +}; + +/** + * Return all non-default preferences as a JSON object. + * + * This includes any nested preference managers as well. + */ +lib.PreferenceManager.prototype.exportAsJson = function() { + var rv = {}; + + for (var name in this.prefRecords_) { + if (name in this.childLists_) { + rv[name] = []; + var childIds = this.get(name); + for (var i = 0; i < childIds.length; i++) { + var id = childIds[i]; + rv[name].push({id: id, json: this.getChild(name, id).exportAsJson()}); + } + + } else { + var record = this.prefRecords_[name]; + if (record.currentValue != this.DEFAULT_VALUE) + rv[name] = record.currentValue; + } + } + + return rv; +}; + +/** + * Import a JSON blob of preferences previously generated with exportAsJson. + * + * This will create nested preference managers as well. + */ +lib.PreferenceManager.prototype.importFromJson = function(json, opt_onComplete) { + let pendingWrites = 0; + const onWriteStorage = () => { + if (--pendingWrites < 1 && opt_onComplete) + opt_onComplete(); + }; + + for (var name in json) { + if (name in this.childLists_) { + var childList = json[name]; + for (var i = 0; i < childList.length; i++) { + var id = childList[i].id; + + var childPrefManager = this.childLists_[name][id]; + if (!childPrefManager) + childPrefManager = this.createChild(name, null, id); + + childPrefManager.importFromJson(childList[i].json, onWriteStorage); + pendingWrites++; + } + + } else { + // The set is synchronous. + this.set(name, json[name]); + } + } + + // If we didn't update any children, no async work has been queued, so make + // the completion callback directly. + if (pendingWrites == 0 && opt_onComplete) + opt_onComplete(); +}; + +/** + * Called when one of the child list preferences changes. + */ +lib.PreferenceManager.prototype.onChildListChange_ = function(listName) { + this.syncChildList(listName); +}; + +/** + * Called when a key in the storage changes. + */ +lib.PreferenceManager.prototype.onStorageChange_ = function(map) { + for (var key in map) { + if (this.prefix) { + if (key.lastIndexOf(this.prefix, 0) != 0) + continue; + } + + var name = key.substr(this.prefix.length); + + if (!(name in this.prefRecords_)) { + // Sometimes we'll get notified about prefs that are no longer defined. + continue; + } + + var record = this.prefRecords_[name]; + + var newValue = map[key].newValue; + var currentValue = record.currentValue; + if (currentValue === record.DEFAULT_VALUE) + currentValue = (void 0); + + if (this.diff(currentValue, newValue)) { + if (typeof newValue == 'undefined' || newValue === null) { + record.currentValue = record.DEFAULT_VALUE; + } else { + record.currentValue = newValue; + } + + this.notifyChange_(name); + } + } +}; +// SOURCE FILE: libdot/js/lib_resource.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Storage for canned resources. + * + * These are usually non-JavaScript things that are collected during a build + * step and converted into a series of 'lib.resource.add(...)' calls. See + * the "@resource" directive from libdot/bin/concat for the canonical use + * case. + * + * This is global storage, so you should prefix your resource names to avoid + * collisions. + */ +lib.resource = { + resources_: {} +}; + +/** + * Add a resource. + * + * @param {string} name A name for the resource. You should prefix this to + * avoid collisions with resources from a shared library. + * @param {string} type A mime type for the resource, or "raw" if not + * applicable. + * @param {*} data The value of the resource. + */ +lib.resource.add = function(name, type, data) { + lib.resource.resources_[name] = { + type: type, + name: name, + data: data + }; +}; + +/** + * Retrieve a resource record. + * + * The resource data is stored on the "data" property of the returned object. + * + * @param {string} name The name of the resource to get. + * @param {*} opt_defaultValue The optional value to return if the resource is + * not defined. + * @return {object} An object with "type", "name", and "data" properties. + */ +lib.resource.get = function(name, opt_defaultValue) { + if (!(name in lib.resource.resources_)) { + if (typeof opt_defaultValue == 'undefined') + throw 'Unknown resource: ' + name; + + return opt_defaultValue; + } + + return lib.resource.resources_[name]; +}; + +/** + * Retrieve resource data. + * + * @param {string} name The name of the resource to get. + * @param {*} opt_defaultValue The optional value to return if the resource is + * not defined. + * @return {*} The resource data. + */ +lib.resource.getData = function(name, opt_defaultValue) { + if (!(name in lib.resource.resources_)) { + if (typeof opt_defaultValue == 'undefined') + throw 'Unknown resource: ' + name; + + return opt_defaultValue; + } + + return lib.resource.resources_[name].data; +}; + +/** + * Retrieve resource as a data: url. + * + * @param {string} name The name of the resource to get. + * @param {*} opt_defaultValue The optional value to return if the resource is + * not defined. + * @return {*} A data: url encoded version of the resource. + */ +lib.resource.getDataUrl = function(name, opt_defaultValue) { + var resource = lib.resource.get(name, opt_defaultValue); + return 'data:' + resource.type + ',' + resource.data; +}; +// SOURCE FILE: libdot/js/lib_storage.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Namespace for implementations of persistent, possibly cloud-backed + * storage. + */ +lib.Storage = new Object(); +// SOURCE FILE: libdot/js/lib_storage_chrome.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * chrome.storage based class with an async interface that is interchangeable + * with other lib.Storage.* implementations. + */ +lib.Storage.Chrome = function(storage) { + this.storage_ = storage; + this.observers_ = []; + + chrome.storage.onChanged.addListener(this.onChanged_.bind(this)); +}; + +/** + * Called by the storage implementation when the storage is modified. + */ +lib.Storage.Chrome.prototype.onChanged_ = function(changes, areaname) { + if (chrome.storage[areaname] != this.storage_) + return; + + for (var i = 0; i < this.observers_.length; i++) { + this.observers_[i](changes); + } +}; + +/** + * Register a function to observe storage changes. + * + * @param {function(map)} callback The function to invoke when the storage + * changes. + */ +lib.Storage.Chrome.prototype.addObserver = function(callback) { + this.observers_.push(callback); +}; + +/** + * Unregister a change observer. + * + * @param {function} observer A previously registered callback. + */ +lib.Storage.Chrome.prototype.removeObserver = function(callback) { + var i = this.observers_.indexOf(callback); + if (i != -1) + this.observers_.splice(i, 1); +}; + +/** + * Delete everything in this storage. + * + * @param {function(map)} callback The function to invoke when the delete + * has completed. + */ +lib.Storage.Chrome.prototype.clear = function(opt_callback) { + this.storage_.clear(); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Return the current value of a storage item. + * + * @param {string} key The key to look up. + * @param {function(value) callback The function to invoke when the value has + * been retrieved. + */ +lib.Storage.Chrome.prototype.getItem = function(key, callback) { + this.storage_.get(key, callback); +}; +/** + * Fetch the values of multiple storage items. + * + * @param {Array} keys The keys to look up. + * @param {function(map) callback The function to invoke when the values have + * been retrieved. + */ + +lib.Storage.Chrome.prototype.getItems = function(keys, callback) { + this.storage_.get(keys, callback); +}; + +/** + * Set a value in storage. + * + * @param {string} key The key for the value to be stored. + * @param {*} value The value to be stored. Anything that can be serialized + * with JSON is acceptable. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Chrome.prototype.setItem = function(key, value, opt_callback) { + const onComplete = () => { + const err = lib.f.lastError(); + if (err) { + // Doesn't seem to be any better way of handling this. + // https://crbug.com/764759 + if (err.indexOf('MAX_WRITE_OPERATIONS')) { + console.warn(`Will retry save of ${key} after exceeding quota: ${err}`); + setTimeout(() => this.setItem(key, value, onComplete), 1000); + return; + } else { + console.error(`Unknown runtime error: ${err}`); + } + } + + if (opt_callback) + opt_callback(); + }; + + var obj = {}; + obj[key] = value; + this.storage_.set(obj, onComplete); +}; + +/** + * Set multiple values in storage. + * + * @param {Object} map A map of key/values to set in storage. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Chrome.prototype.setItems = function(obj, opt_callback) { + this.storage_.set(obj, opt_callback); +}; + +/** + * Remove an item from storage. + * + * @param {string} key The key to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Chrome.prototype.removeItem = function(key, opt_callback) { + this.storage_.remove(key, opt_callback); +}; + +/** + * Remove multiple items from storage. + * + * @param {Array} keys The keys to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Chrome.prototype.removeItems = function(keys, opt_callback) { + this.storage_.remove(keys, opt_callback); +}; +// SOURCE FILE: libdot/js/lib_storage_local.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * window.localStorage based class with an async interface that is + * interchangeable with other lib.Storage.* implementations. + */ +lib.Storage.Local = function() { + this.observers_ = []; + this.storage_ = window.localStorage; + window.addEventListener('storage', this.onStorage_.bind(this)); +}; + +/** + * Called by the storage implementation when the storage is modified. + */ +lib.Storage.Local.prototype.onStorage_ = function(e) { + if (e.storageArea != this.storage_) + return; + + // JS throws an exception if JSON.parse is given an empty string. So here we + // only parse if the value is truthy. This mean the empty string, undefined + // and null will not be parsed. + var prevValue = e.oldValue ? JSON.parse(e.oldValue) : e.oldValue; + var curValue = e.newValue ? JSON.parse(e.newValue) : e.newValue; + var o = {}; + o[e.key] = { + oldValue: prevValue, + newValue: curValue + }; + + for (var i = 0; i < this.observers_.length; i++) { + this.observers_[i](o); + } +}; + +/** + * Register a function to observe storage changes. + * + * @param {function(map)} callback The function to invoke when the storage + * changes. + */ +lib.Storage.Local.prototype.addObserver = function(callback) { + this.observers_.push(callback); +}; + +/** + * Unregister a change observer. + * + * @param {function} observer A previously registered callback. + */ +lib.Storage.Local.prototype.removeObserver = function(callback) { + var i = this.observers_.indexOf(callback); + if (i != -1) + this.observers_.splice(i, 1); +}; + +/** + * Delete everything in this storage. + * + * @param {function(map)} callback The function to invoke when the delete + * has completed. + */ +lib.Storage.Local.prototype.clear = function(opt_callback) { + this.storage_.clear(); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Return the current value of a storage item. + * + * @param {string} key The key to look up. + * @param {function(value) callback The function to invoke when the value has + * been retrieved. + */ +lib.Storage.Local.prototype.getItem = function(key, callback) { + var value = this.storage_.getItem(key); + + if (typeof value == 'string') { + try { + value = JSON.parse(value); + } catch (e) { + // If we can't parse the value, just return it unparsed. + } + } + + setTimeout(callback.bind(null, value), 0); +}; + +/** + * Fetch the values of multiple storage items. + * + * @param {Array} keys The keys to look up. + * @param {function(map) callback The function to invoke when the values have + * been retrieved. + */ +lib.Storage.Local.prototype.getItems = function(keys, callback) { + var rv = {}; + + for (var i = keys.length - 1; i >= 0; i--) { + var key = keys[i]; + var value = this.storage_.getItem(key); + if (typeof value == 'string') { + try { + rv[key] = JSON.parse(value); + } catch (e) { + // If we can't parse the value, just return it unparsed. + rv[key] = value; + } + } else { + keys.splice(i, 1); + } + } + + setTimeout(callback.bind(null, rv), 0); +}; + +/** + * Set a value in storage. + * + * @param {string} key The key for the value to be stored. + * @param {*} value The value to be stored. Anything that can be serialized + * with JSON is acceptable. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Local.prototype.setItem = function(key, value, opt_callback) { + this.storage_.setItem(key, JSON.stringify(value)); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Set multiple values in storage. + * + * @param {Object} map A map of key/values to set in storage. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Local.prototype.setItems = function(obj, opt_callback) { + for (var key in obj) { + this.storage_.setItem(key, JSON.stringify(obj[key])); + } + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Remove an item from storage. + * + * @param {string} key The key to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Local.prototype.removeItem = function(key, opt_callback) { + this.storage_.removeItem(key); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Remove multiple items from storage. + * + * @param {Array} keys The keys to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Local.prototype.removeItems = function(ary, opt_callback) { + for (var i = 0; i < ary.length; i++) { + this.storage_.removeItem(ary[i]); + } + + if (opt_callback) + setTimeout(opt_callback, 0); +}; +// SOURCE FILE: libdot/js/lib_storage_memory.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * In-memory storage class with an async interface that is interchangeable with + * other lib.Storage.* implementations. + */ +lib.Storage.Memory = function() { + this.observers_ = []; + this.storage_ = {}; +}; + +/** + * Register a function to observe storage changes. + * + * @param {function(map)} callback The function to invoke when the storage + * changes. + */ +lib.Storage.Memory.prototype.addObserver = function(callback) { + this.observers_.push(callback); +}; + +/** + * Unregister a change observer. + * + * @param {function} observer A previously registered callback. + */ +lib.Storage.Memory.prototype.removeObserver = function(callback) { + var i = this.observers_.indexOf(callback); + if (i != -1) + this.observers_.splice(i, 1); +}; + +/** + * Delete everything in this storage. + * + * @param {function(map)} callback The function to invoke when the delete + * has completed. + */ +lib.Storage.Memory.prototype.clear = function(opt_callback) { + var e = {}; + for (var key in this.storage_) { + e[key] = {oldValue: this.storage_[key], newValue: (void 0)}; + } + + this.storage_ = {}; + + setTimeout(function() { + for (var i = 0; i < this.observers_.length; i++) { + this.observers_[i](e); + } + }.bind(this), 0); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Return the current value of a storage item. + * + * @param {string} key The key to look up. + * @param {function(value) callback The function to invoke when the value has + * been retrieved. + */ +lib.Storage.Memory.prototype.getItem = function(key, callback) { + var value = this.storage_[key]; + + if (typeof value == 'string') { + try { + value = JSON.parse(value); + } catch (e) { + // If we can't parse the value, just return it unparsed. + } + } + + setTimeout(callback.bind(null, value), 0); +}; + +/** + * Fetch the values of multiple storage items. + * + * @param {Array} keys The keys to look up. + * @param {function(map) callback The function to invoke when the values have + * been retrieved. + */ +lib.Storage.Memory.prototype.getItems = function(keys, callback) { + var rv = {}; + + for (var i = keys.length - 1; i >= 0; i--) { + var key = keys[i]; + var value = this.storage_[key]; + if (typeof value == 'string') { + try { + rv[key] = JSON.parse(value); + } catch (e) { + // If we can't parse the value, just return it unparsed. + rv[key] = value; + } + } else { + keys.splice(i, 1); + } + } + + setTimeout(callback.bind(null, rv), 0); +}; + +/** + * Set a value in storage. + * + * @param {string} key The key for the value to be stored. + * @param {*} value The value to be stored. Anything that can be serialized + * with JSON is acceptable. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Memory.prototype.setItem = function(key, value, opt_callback) { + var oldValue = this.storage_[key]; + this.storage_[key] = JSON.stringify(value); + + var e = {}; + e[key] = {oldValue: oldValue, newValue: value}; + + setTimeout(function() { + for (var i = 0; i < this.observers_.length; i++) { + this.observers_[i](e); + } + }.bind(this), 0); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Set multiple values in storage. + * + * @param {Object} map A map of key/values to set in storage. + * @param {function()} opt_callback Optional function to invoke when the + * set is complete. You don't have to wait for the set to complete in order + * to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Memory.prototype.setItems = function(obj, opt_callback) { + var e = {}; + + for (var key in obj) { + e[key] = {oldValue: this.storage_[key], newValue: obj[key]}; + this.storage_[key] = JSON.stringify(obj[key]); + } + + setTimeout(function() { + for (var i = 0; i < this.observers_.length; i++) { + this.observers_[i](e); + } + }.bind(this)); + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Remove an item from storage. + * + * @param {string} key The key to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Memory.prototype.removeItem = function(key, opt_callback) { + delete this.storage_[key]; + + if (opt_callback) + setTimeout(opt_callback, 0); +}; + +/** + * Remove multiple items from storage. + * + * @param {Array} keys The keys to be removed. + * @param {function()} opt_callback Optional function to invoke when the + * remove is complete. You don't have to wait for the set to complete in + * order to read the value, since the local cache is updated synchronously. + */ +lib.Storage.Memory.prototype.removeItems = function(ary, opt_callback) { + for (var i = 0; i < ary.length; i++) { + delete this.storage_[ary[i]]; + } + + if (opt_callback) + setTimeout(opt_callback, 0); +}; +// SOURCE FILE: libdot/js/lib_test_manager.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview JavaScript unit testing framework for synchronous and + * asynchronous tests. + * + * This file contains the lib.TestManager and related classes. At the moment + * it's all collected in a single file since it's reasonably small + * (=~1k lines), and it's a lot easier to include one file into your test + * harness than it is to include seven. + * + * The following classes are defined... + * + * lib.TestManager - The root class and entrypoint for creating test runs. + * lib.TestManager.Log - Logging service. + * lib.TestManager.Suite - A collection of tests. + * lib.TestManager.Test - A single test. + * lib.TestManager.TestRun - Manages the execution of a set of tests. + * lib.TestManager.Result - A single test result. + */ + +/** + * Root object in the unit test hierarchy, and keeper of the log object. + * + * @param {lib.TestManager.Log} opt_log Optional lib.TestManager.Log object. + * Logs to the JavaScript console if omitted. + */ +lib.TestManager = function(opt_log) { + this.log = opt_log || new lib.TestManager.Log(); +}; + +/** + * Create a new test run object for this test manager. + * + * @param {Object} opt_cx An object to be passed to test suite setup(), + * preamble(), and test cases during this test run. This object is opaque + * to lib.TestManager.* code. It's entirely up to the test suite what it's + * used for. + */ +lib.TestManager.prototype.createTestRun = function(opt_cx) { + return new lib.TestManager.TestRun(this, opt_cx); +}; + +/** + * Called when a test run associated with this test manager completes. + * + * Clients may override this to call an appropriate function. + */ +lib.TestManager.prototype.onTestRunComplete = function(testRun) {}; + +/** + * Called before a test associated with this test manager is run. + * + * @param {lib.TestManager.Result} result The result object for the upcoming + * test. + * @param {Object} cx The context object for a test run. + */ +lib.TestManager.prototype.testPreamble = function(result, cx) {}; + +/** + * Called after a test associated with this test manager finishes. + * + * @param {lib.TestManager.Result} result The result object for the finished + * test. + * @param {Object} cx The context object for a test run. + */ +lib.TestManager.prototype.testPostamble = function(result, cx) {}; + +/** + * Destination for test case output. + * + * Thw API will be the same as the console object. e.g. We support info(), + * warn(), error(), etc... just like console.info(), etc... + * + * @param {Object} opt_console The console object to route all logging through. + * Should provide saome API as the standard console API. + */ +lib.TestManager.Log = function(opt_console=console) { + this.save = false; + this.data = ''; + this.prefix_ = ''; + this.prefixStack_ = 0; + + // Capture all the console entry points in case code at runtime calls these + // directly. We want to be able to still see things. + // We also expose the direct API to our callers (e.g. we provide warn()). + this.console_ = opt_console; + ['log', 'debug', 'info', 'warn', 'error'].forEach((level) => { + let msgPrefix = ''; + switch (level) { + case 'debug': + case 'warn': + case 'error': + msgPrefix = level.toUpperCase() + ': '; + break; + } + + const oLog = this.console_[level]; + this[level] = this.console_[level] = (...args) => { + if (this.save) + this.data += this.prefix_ + msgPrefix + args.join(' ') + '\n'; + oLog.apply(this.console_, args); + }; + }); + + // Wrap/bind the group functions. + ['group', 'groupCollapsed'].forEach((group) => { + const oGroup = this.console_[group]; + this[group] = this.console_[group] = (label='') => { + oGroup(label); + if (this.save) + this.data += this.prefix_ + label + '\n'; + this.prefix_ = ' '.repeat(++this.prefixStack_); + }; + }); + + const oGroupEnd = this.console_.groupEnd; + this.groupEnd = this.console_.groupEnd = () => { + oGroupEnd(); + if (this.prefixStack_) + this.prefix_ = ' '.repeat(--this.prefixStack_); + }; +}; + +/** + * Returns a new constructor function that will inherit from + * lib.TestManager.Suite. + * + * Use this function to create a new test suite subclass. It will return a + * properly initialized constructor function for the subclass. You can then + * override the setup() and preamble() methods if necessary and add test cases + * to the subclass. + * + * var MyTests = new lib.TestManager.Suite('MyTests'); + * + * MyTests.prototype.setup = function(cx) { + * // Sets this.size to cx.size if it exists, or the default value of 10 + * // if not. + * this.setDefault(cx, {size: 10}); + * }; + * + * MyTests.prototype.preamble = function(result, cx) { + * // Some tests (even successful ones) may side-effect this list, so + * // recreate it before every test. + * this.list = []; + * for (var i = 0; i < this.size; i++) { + * this.list[i] = i; + * } + * }; + * + * // Basic synchronous test case. + * MyTests.addTest('pop-length', function(result, cx) { + * this.list.pop(); + * + * // If this assertion fails, the testcase will stop here. + * result.assertEQ(this.list.length, this.size - 1); + * + * // A test must indicate it has passed by calling this method. + * result.pass(); + * }); + * + * // Sample asynchronous test case. + * MyTests.addTest('async-pop-length', function(result, cx) { + * var callback = () => { + * result.assertEQ(this.list.length, this.size - 1); + * result.pass(); + * }; + * + * // Wait 100ms to check the array length for the sake of this example. + * setTimeout(callback, 100); + * + * this.list.pop(); + * + * // Indicate that this test needs another 200ms to complete. + * // If the test does not report pass/fail by then, it is considered to + * // have timed out. + * result.requestTime(200); + * }); + * + * ... + * + * @param {string} suiteName The name of the test suite. + */ +lib.TestManager.Suite = function(suiteName) { + function ctor(testManager, cx) { + this.testManager_ = testManager; + this.suiteName = suiteName; + + this.setup(cx); + } + + ctor.suiteName = suiteName; + ctor.addTest = lib.TestManager.Suite.addTest; + ctor.disableTest = lib.TestManager.Suite.disableTest; + ctor.getTest = lib.TestManager.Suite.getTest; + ctor.getTestList = lib.TestManager.Suite.getTestList; + ctor.testList_ = []; + ctor.testMap_ = {}; + ctor.prototype = Object.create(lib.TestManager.Suite.prototype); + ctor.constructor = lib.TestManager.Suite; + + lib.TestManager.Suite.subclasses.push(ctor); + + return ctor; +}; + +/** + * List of lib.TestManager.Suite subclasses, in the order they were defined. + */ +lib.TestManager.Suite.subclasses = []; + +/** + * Add a test to a lib.TestManager.Suite. + * + * This method is copied to new subclasses when they are created. + */ +lib.TestManager.Suite.addTest = function(testName, testFunction) { + if (testName in this.testMap_) + throw 'Duplicate test name: ' + testName; + + var test = new lib.TestManager.Test(this, testName, testFunction); + this.testMap_[testName] = test; + this.testList_.push(test); +}; + +/** + * Defines a disabled test. + */ +lib.TestManager.Suite.disableTest = function(testName, testFunction) { + if (testName in this.testMap_) + throw 'Duplicate test name: ' + testName; + + var test = new lib.TestManager.Test(this, testName, testFunction); + console.log('Disabled test: ' + test.fullName); +}; + +/** + * Get a lib.TestManager.Test instance by name. + * + * This method is copied to new subclasses when they are created. + * + * @param {string} testName The name of the desired test. + * @return {lib.TestManager.Test} The requested test, or undefined if it was not + * found. + */ +lib.TestManager.Suite.getTest = function(testName) { + return this.testMap_[testName]; +}; + +/** + * Get an array of lib.TestManager.Tests associated with this Suite. + * + * This method is copied to new subclasses when they are created. + */ +lib.TestManager.Suite.getTestList = function() { + return this.testList_; +}; + +/** + * Set properties on a test suite instance, pulling the property value from + * the context if it exists and from the defaults dictionary if not. + * + * This is intended to be used in your test suite's setup() method to + * define parameters for the test suite which may be overridden through the + * context object. For example... + * + * MySuite.prototype.setup = function(cx) { + * this.setDefaults(cx, {size: 10}); + * }; + * + * If the context object has a 'size' property then this.size will be set to + * the value of cx.size, otherwise this.size will get a default value of 10. + * + * @param {Object} cx The context object for a test run. + * @param {Object} defaults An object containing name/value pairs to set on + * this test suite instance. The value listed here will be used if the + * name is not defined on the context object. + */ +lib.TestManager.Suite.prototype.setDefaults = function(cx, defaults) { + for (var k in defaults) { + this[k] = (k in cx) ? cx[k] : defaults[k]; + } +}; + +/** + * Subclassable method called to set up the test suite. + * + * The default implementation of this method is a no-op. If your test suite + * requires some kind of suite-wide setup, this is the place to do it. + * + * It's fine to store state on the test suite instance, that state will be + * accessible to all tests in the suite. If any test case fails, the entire + * test suite object will be discarded and a new one will be created for + * the remaining tests. + * + * Any side effects outside of this test suite instance must be idempotent. + * For example, if you're adding DOM nodes to a document, make sure to first + * test that they're not already there. If they are, remove them rather than + * reuse them. You should not count on their state, since they were probably + * left behind by a failed testcase. + * + * Any exception here will abort the remainder of the test run. + * + * @param {Object} cx The context object for a test run. + */ +lib.TestManager.Suite.prototype.setup = function(cx) {}; + +/** + * Subclassable method called to do pre-test set up. + * + * The default implementation of this method is a no-op. If your test suite + * requires some kind of pre-test setup, this is the place to do it. + * + * This can be used to avoid a bunch of boilerplate setup/teardown code in + * this suite's testcases. + * + * Any exception here will abort the remainder of the test run. + * + * @param {lib.TestManager.Result} result The result object for the upcoming + * test. + * @param {Object} cx The context object for a test run. + */ +lib.TestManager.Suite.prototype.preamble = function(result, cx) {}; + +/** + * Subclassable method called to do post-test tear-down. + * + * The default implementation of this method is a no-op. If your test suite + * requires some kind of pre-test setup, this is the place to do it. + * + * This can be used to avoid a bunch of boilerplate setup/teardown code in + * this suite's testcases. + * + * Any exception here will abort the remainder of the test run. + * + * @param {lib.TestManager.Result} result The result object for the finished + * test. + * @param {Object} cx The context object for a test run. + */ +lib.TestManager.Suite.prototype.postamble = function(result, cx) {}; + +/** + * Object representing a single test in a test suite. + * + * These are created as part of the lib.TestManager.Suite.addTest() method. + * You should never have to construct one by hand. + * + * @param {lib.TestManager.Suite} suiteClass The test suite class containing + * this test. + * @param {string} testName The local name of this test case, not including the + * test suite name. + * @param {function(lib.TestManager.Result, Object)} testFunction The function + * to invoke for this test case. This is passed a Result instance and the + * context object associated with the test run. + * + */ +lib.TestManager.Test = function(suiteClass, testName, testFunction) { + /** + * The test suite class containing this function. + */ + this.suiteClass = suiteClass; + + /** + * The local name of this test, not including the test suite name. + */ + this.testName = testName; + + /** + * The global name of this test, including the test suite name. + */ + this.fullName = suiteClass.suiteName + '[' + testName + ']'; + + // The function to call for this test. + this.testFunction_ = testFunction; +}; + +/** + * Execute this test. + * + * This is called by a lib.TestManager.Result instance, as part of a + * lib.TestManager.TestRun. You should not call it by hand. + * + * @param {lib.TestManager.Result} result The result object for the test. + */ +lib.TestManager.Test.prototype.run = function(result) { + try { + // Tests are applied to the parent lib.TestManager.Suite subclass. + this.testFunction_.apply(result.suite, + [result, result.testRun.cx]); + } catch (ex) { + if (ex instanceof lib.TestManager.Result.TestComplete) + return; + + result.println('Test raised an exception: ' + ex); + + if (ex.stack) { + if (ex.stack instanceof Array) { + result.println(ex.stack.join('\n')); + } else { + result.println(ex.stack); + } + } + + result.completeTest_(result.FAILED, false); + } +}; + +/** + * Used to choose a set of tests and run them. + * + * It's slightly more convenient to construct one of these from + * lib.TestManager.prototype.createTestRun(). + * + * @param {lib.TestManager} testManager The testManager associated with this + * TestRun. + * @param {Object} cx A context to be passed into the tests. This can be used + * to set parameters for the test suite or individual test cases. + */ +lib.TestManager.TestRun = function(testManager, cx) { + /** + * The associated lib.TestManager instance. + */ + this.testManager = testManager; + + /** + * Shortcut to the lib.TestManager's log. + */ + this.log = testManager.log; + + /** + * The test run context. It's entirely up to the test suite and test cases + * how this is used. It is opaque to lib.TestManager.* classes. + */ + this.cx = cx || {}; + + /** + * The list of test cases that encountered failures. + */ + this.failures = []; + + /** + * The list of test cases that passed. + */ + this.passes = []; + + /** + * The time the test run started, or null if it hasn't been started yet. + */ + this.startDate = null; + + /** + * The time in milliseconds that the test run took to complete, or null if + * it hasn't completed yet. + */ + this.duration = null; + + /** + * The most recent result object, or null if the test run hasn't started + * yet. In order to detect late failures, this is not cleared when the test + * completes. + */ + this.currentResult = null; + + /** + * Number of maximum failures. The test run will stop when this number is + * reached. If 0 or omitted, the entire set of selected tests is run, even + * if some fail. + */ + this.maxFailures = 0; + + /** + * True if this test run ended early because of an unexpected condition. + */ + this.panic = false; + + // List of pending test cases. + this.testQueue_ = []; + +}; + +/** + * This value can be passed to select() to indicate that all tests should + * be selected. + */ +lib.TestManager.TestRun.prototype.ALL_TESTS = lib.f.createEnum(''); + +/** + * Add a single test to the test run. + */ +lib.TestManager.TestRun.prototype.selectTest = function(test) { + this.testQueue_.push(test); +}; + +lib.TestManager.TestRun.prototype.selectSuite = function( + suiteClass, opt_pattern) { + var pattern = opt_pattern || this.ALL_TESTS; + var selectCount = 0; + var testList = suiteClass.getTestList(); + + for (var j = 0; j < testList.length; j++) { + var test = testList[j]; + // Note that we're using "!==" rather than "!=" so that we're matching + // the ALL_TESTS String object, rather than the contents of the string. + if (pattern !== this.ALL_TESTS) { + if (pattern instanceof RegExp) { + if (!pattern.test(test.testName)) + continue; + } else if (test.testName != pattern) { + continue; + } + } + + this.selectTest(test); + selectCount++; + } + + return selectCount; +}; + +/** + * Selects one or more tests to gather results for. + * + * Selecting the same test more than once is allowed. + * + * @param {string|RegExp} pattern Pattern used to select tests. + * If TestRun.prototype.ALL_TESTS, all tests are selected. + * If a string, only the test that exactly matches is selected. + * If a RegExp, only tests matching the RegExp are added. + * + * @return {int} The number of additional tests that have been selected into + * this TestRun. + */ +lib.TestManager.TestRun.prototype.selectPattern = function(pattern) { + var selectCount = 0; + + for (var i = 0; i < lib.TestManager.Suite.subclasses.length; i++) { + selectCount += this.selectSuite(lib.TestManager.Suite.subclasses[i], + pattern); + } + + if (!selectCount) { + this.log.warn('No tests matched selection criteria: ' + pattern); + } + + return selectCount; +}; + +/** + * Hooked up to window.onerror during a test run in order to catch exceptions + * that would otherwise go uncaught. + */ +lib.TestManager.TestRun.prototype.onUncaughtException_ = function( + message, file, line) { + + if (message.indexOf('Uncaught lib.TestManager.Result.TestComplete') == 0 || + message.indexOf('status: passed') != -1) { + // This is a result.pass() or result.fail() call from a callback. We're + // already going to deal with it as part of the completeTest_() call + // that raised it. We can safely squelch this error message. + return true; + } + + if (!this.currentResult) + return; + + if (message == 'Uncaught ' + this.currentResult.expectedErrorMessage_) { + // Test cases may need to raise an unhandled exception as part of the test. + return; + } + + var when = 'during'; + + if (this.currentResult.status != this.currentResult.PENDING) + when = 'after'; + + this.log.error('Uncaught exception ' + when + ' test case: ' + + this.currentResult.test.fullName); + this.log.error(message + ', ' + file + ':' + line); + + this.currentResult.completeTest_(this.currentResult.FAILED, false); + + return false; +}; + +/** + * Called to when this test run has completed. + * + * This method typically re-runs itself asynchronously, in order to let the + * DOM stabilize and short-term timeouts to complete before declaring the + * test run complete. + * + * @param {boolean} opt_skipTimeout If true, the timeout is skipped and the + * test run is completed immediately. This should only be used from within + * this function. + */ +lib.TestManager.TestRun.prototype.onTestRunComplete_ = function( + opt_skipTimeout) { + if (!opt_skipTimeout) { + // The final test may have left a lingering setTimeout(..., 0), or maybe + // poked at the DOM in a way that will trigger a event to fire at the end + // of this stack, so we give things a chance to settle down before our + // final cleanup... + setTimeout(this.onTestRunComplete_.bind(this), 0, true); + return; + } + + this.duration = (new Date()) - this.startDate; + + this.log.groupEnd(); + this.log.info(this.passes.length + ' passed, ' + + this.failures.length + ' failed, ' + + this.msToSeconds_(this.duration)); + + this.summarize(); + + window.onerror = null; + + this.testManager.onTestRunComplete(this); +}; + +/** + * Called by the lib.TestManager.Result object when a test completes. + * + * @param {lib.TestManager.Result} result The result object which has just + * completed. + */ +lib.TestManager.TestRun.prototype.onResultComplete = function(result) { + try { + this.testManager.testPostamble(result, this.cx); + result.suite.postamble(result, this.ctx); + } catch (ex) { + this.log.error('Unexpected exception in postamble: ' + + (ex.stack ? ex.stack : ex)); + this.panic = true; + } + + if (result.status != result.PASSED) + this.log.error(result.status); + else if (result.duration > 500) + this.log.warn('Slow test took ' + this.msToSeconds_(result.duration)); + this.log.groupEnd(); + + if (result.status == result.FAILED) { + this.failures.push(result); + this.currentSuite = null; + } else if (result.status == result.PASSED) { + this.passes.push(result); + } else { + this.log.error('Unknown result status: ' + result.test.fullName + ': ' + + result.status); + this.panic = true; + return; + } + + this.runNextTest_(); +}; + +/** + * Called by the lib.TestManager.Result object when a test which has already + * completed reports another completion. + * + * This is usually indicative of a buggy testcase. It is probably reporting a + * result on exit and then again from an asynchronous callback. + * + * It may also be the case that the last act of the testcase causes a DOM change + * which triggers some event to run after the test returns. If the event + * handler reports a failure or raises an uncaught exception, the test will + * fail even though it has already completed. + * + * In any case, re-completing a test ALWAYS moves it into the failure pile. + * + * @param {lib.TestManager.Result} result The result object which has just + * completed. + * @param {string} lateStatus The status that the test attempted to record this + * time around. + */ +lib.TestManager.TestRun.prototype.onResultReComplete = function( + result, lateStatus) { + this.log.error('Late complete for test: ' + result.test.fullName + ': ' + + lateStatus); + + // Consider any late completion a failure, even if it's a double-pass, since + // it's a misuse of the testing API. + var index = this.passes.indexOf(result); + if (index >= 0) { + this.passes.splice(index, 1); + this.failures.push(result); + } +}; + +/** + * Run the next test in the queue. + */ +lib.TestManager.TestRun.prototype.runNextTest_ = function() { + if (this.panic || !this.testQueue_.length) { + this.onTestRunComplete_(); + return; + } + + if (this.maxFailures && this.failures.length >= this.maxFailures) { + this.log.error('Maximum failure count reached, aborting test run.'); + this.onTestRunComplete_(); + return; + } + + // Peek at the top test first. We remove it later just before it's about + // to run, so that we don't disturb the incomplete test count in the + // event that we fail before running it. + var test = this.testQueue_[0]; + var suite = this.currentResult ? this.currentResult.suite : null; + + try { + if (!suite || !(suite instanceof test.suiteClass)) { + if (suite) + this.log.groupEnd(); + this.log.group(test.suiteClass.suiteName); + suite = new test.suiteClass(this.testManager, this.cx); + } + } catch (ex) { + // If test suite setup fails we're not even going to try to run the tests. + this.log.error('Exception during setup: ' + (ex.stack ? ex.stack : ex)); + this.panic = true; + this.onTestRunComplete_(); + return; + } + + try { + this.log.group(test.testName); + + this.currentResult = new lib.TestManager.Result(this, suite, test); + this.testManager.testPreamble(this.currentResult, this.cx); + suite.preamble(this.currentResult, this.cx); + + this.testQueue_.shift(); + } catch (ex) { + this.log.error('Unexpected exception during test preamble: ' + + (ex.stack ? ex.stack : ex)); + this.log.groupEnd(); + + this.panic = true; + this.onTestRunComplete_(); + return; + } + + try { + this.currentResult.run(); + } catch (ex) { + // Result.run() should catch test exceptions and turn them into failures. + // If we got here, it means there is trouble in the testing framework. + this.log.error('Unexpected exception during test run: ' + + (ex.stack ? ex.stack : ex)); + this.panic = true; + } +}; + +/** + * Run the selected list of tests. + * + * Some tests may need to run asynchronously, so you cannot assume the run is + * complete when this function returns. Instead, pass in a function to be + * called back when the run has completed. + * + * This function will log the results of the test run as they happen into the + * log defined by the associated lib.TestManager. By default this is + * console.log, which can be viewed in the JavaScript console of most browsers. + * + * The browser state is determined by the last test to run. We intentionally + * don't do any cleanup so that you can inspect the state of a failed test, or + * leave the browser ready for manual testing. + * + * Any failures in lib.TestManager.* code or test suite setup or test case + * preamble will cause the test run to abort. + */ +lib.TestManager.TestRun.prototype.run = function() { + this.log.info('Running ' + this.testQueue_.length + ' test(s)'); + + window.onerror = this.onUncaughtException_.bind(this); + this.startDate = new Date(); + this.runNextTest_(); +}; + +/** + * Format milliseconds as fractional seconds. + */ +lib.TestManager.TestRun.prototype.msToSeconds_ = function(ms) { + var secs = (ms / 1000).toFixed(2); + return secs + 's'; +}; + +/** + * Log the current result summary. + */ +lib.TestManager.TestRun.prototype.summarize = function() { + if (this.failures.length) { + for (var i = 0; i < this.failures.length; i++) { + this.log.error('FAILED: ' + this.failures[i].test.fullName); + } + } + + if (this.testQueue_.length) { + this.log.warn('Test run incomplete: ' + this.testQueue_.length + + ' test(s) were not run.'); + } +}; + +/** + * Record of the result of a single test. + * + * These are constructed during a test run, you shouldn't have to make one + * on your own. + * + * An instance of this class is passed in to each test function. It can be + * used to add messages to the test log, to record a test pass/fail state, to + * test assertions, or to create exception-proof wrappers for callback + * functions. + * + * @param {lib.TestManager.TestRun} testRun The TestRun instance associated with + * this result. + * @param {lib.TestManager.Suit} suite The Suite containing the test we're + * collecting this result for. + * @param {lib.TestManager.Test} test The test we're collecting this result for. + */ +lib.TestManager.Result = function(testRun, suite, test) { + /** + * The TestRun instance associated with this result. + */ + this.testRun = testRun; + + /** + * The Suite containing the test we're collecting this result for. + */ + this.suite = suite; + + /** + * The test we're collecting this result for. + */ + this.test = test; + + /** + * The time we started to collect this result, or null if we haven't started. + */ + this.startDate = null; + + /** + * The time in milliseconds that the test took to complete, or null if + * it hasn't completed yet. + */ + this.duration = null; + + /** + * The current status of this test result. + */ + this.status = this.PENDING; + + // An error message that the test case is expected to generate. + this.expectedErrorMessage_ = null; +}; + +/** + * Possible values for this.status. + */ +lib.TestManager.Result.prototype.PENDING = 'pending'; +lib.TestManager.Result.prototype.FAILED = 'FAILED'; +lib.TestManager.Result.prototype.PASSED = 'passed'; + +/** + * Exception thrown when a test completes (pass or fail), to ensure no more of + * the test is run. + */ +lib.TestManager.Result.TestComplete = function(result) { + this.result = result; +}; + +lib.TestManager.Result.TestComplete.prototype.toString = function() { + return 'lib.TestManager.Result.TestComplete: ' + this.result.test.fullName + + ', status: ' + this.result.status; +}; + +/** + * Start the test associated with this result. + */ +lib.TestManager.Result.prototype.run = function() { + this.startDate = new Date(); + this.test.run(this); + + if (this.status == this.PENDING && !this.timeout_) { + this.println('Test did not return a value and did not request more time.'); + this.completeTest_(this.FAILED, false); + } +}; + +/** + * Unhandled error message this test expects to generate. + * + * This must be the exact string that would appear in the JavaScript console, + * minus the 'Uncaught ' prefix. + * + * The test case does *not* automatically fail if the error message is not + * encountered. + */ +lib.TestManager.Result.prototype.expectErrorMessage = function(str) { + this.expectedErrorMessage_ = str; +}; + +/** + * Function called when a test times out. + */ +lib.TestManager.Result.prototype.onTimeout_ = function() { + this.timeout_ = null; + + if (this.status != this.PENDING) + return; + + this.println('Test timed out.'); + this.completeTest_(this.FAILED, false); +}; + +/** + * Indicate that a test case needs more time to complete. + * + * Before a test case returns it must report a pass/fail result, or request more + * time to do so. + * + * If a test does not report pass/fail before the time expires it will + * be reported as a timeout failure. Any late pass/fails will be noted in the + * test log, but will not affect the final result of the test. + * + * Test cases may call requestTime more than once. If you have a few layers + * of asynchronous API to go through, you should call this once per layer with + * an estimate of how long each callback will take to complete. + * + * @param {int} ms Number of milliseconds requested. + */ +lib.TestManager.Result.prototype.requestTime = function(ms) { + if (this.timeout_) + clearTimeout(this.timeout_); + + this.timeout_ = setTimeout(this.onTimeout_.bind(this), ms); +}; + +/** + * Report the completion of a test. + * + * @param {string} status The status of the test case. + * @param {boolean} opt_throw Optional boolean indicating whether or not + * to throw the TestComplete exception. + */ +lib.TestManager.Result.prototype.completeTest_ = function(status, opt_throw) { + if (this.status == this.PENDING) { + this.duration = (new Date()) - this.startDate; + this.status = status; + + this.testRun.onResultComplete(this); + } else { + this.testRun.onResultReComplete(this, status); + } + + if (arguments.length < 2 || opt_throw) + throw new lib.TestManager.Result.TestComplete(this); +}; + +/** + * Assert that an actual value is exactly equal to the expected value. + * + * This uses the JavaScript '===' operator in order to avoid type coercion. + * + * If the assertion fails, the test is marked as a failure and a TestCompleted + * exception is thrown. + * + * @param {*} actual The actual measured value. + * @param {*} expected The value expected. + * @param {string} opt_name An optional name used to identify this + * assertion in the test log. If omitted it will be the file:line + * of the caller. + */ +lib.TestManager.Result.prototype.assertEQ = function( + actual, expected, opt_name) { + // Utility function to pretty up the log. + function format(value) { + if (typeof value == 'number') + return value; + + var str = String(value); + var ary = str.split('\n').map((e) => JSON.stringify(e)); + if (ary.length > 1) { + // If the string has newlines, start it off on its own line so that + // it's easier to compare against another string with newlines. + return '\n' + ary.join('\n'); + } else { + return ary.join('\n'); + } + } + + if (actual === expected) + return; + + // Deal with common object types since JavaScript can't. + if (expected instanceof Array) + if (lib.array.compare(actual, expected)) + return; + + var name = opt_name ? '[' + opt_name + ']' : ''; + + this.fail('assertEQ' + name + ': ' + this.getCallerLocation_(1) + ': ' + + format(actual) + ' !== ' + format(expected)); +}; + +/** + * Assert that a value is true. + * + * This uses the JavaScript '===' operator in order to avoid type coercion. + * The must be the boolean value `true`, not just some "truish" value. + * + * If the assertion fails, the test is marked as a failure and a TestCompleted + * exception is thrown. + * + * @param {boolean} actual The actual measured value. + * @param {string} opt_name An optional name used to identify this + * assertion in the test log. If omitted it will be the file:line + * of the caller. + */ +lib.TestManager.Result.prototype.assert = function(actual, opt_name) { + if (actual === true) + return; + + var name = opt_name ? '[' + opt_name + ']' : ''; + + this.fail('assert' + name + ': ' + this.getCallerLocation_(1) + ': ' + + String(actual)); +}; + +/** + * Return the filename:line of a calling stack frame. + * + * This uses a dirty hack. It throws an exception, catches it, and examines + * the stack property of the caught exception. + * + * @param {int} frameIndex The stack frame to return. 0 is the frame that + * called this method, 1 is its caller, and so on. + * @return {string} A string of the format "filename:linenumber". + */ +lib.TestManager.Result.prototype.getCallerLocation_ = function(frameIndex) { + try { + throw new Error(); + } catch (ex) { + var frame = ex.stack.split('\n')[frameIndex + 2]; + var ary = frame.match(/([^/]+:\d+):\d+\)?$/); + return ary ? ary[1] : '???'; + } +}; + +/** + * Write a message to the result log. + */ +lib.TestManager.Result.prototype.println = function(message) { + this.testRun.log.info(message); +}; + +/** + * Mark a failed test and exit out of the rest of the test. + * + * This will throw a TestCompleted exception, causing the current test to stop. + * + * @param {string} opt_message Optional message to add to the log. + */ +lib.TestManager.Result.prototype.fail = function(opt_message) { + if (arguments.length) + this.println(opt_message); + + this.completeTest_(this.FAILED, true); +}; + +/** + * Mark a passed test and exit out of the rest of the test. + * + * This will throw a TestCompleted exception, causing the current test to stop. + */ +lib.TestManager.Result.prototype.pass = function() { + this.completeTest_(this.PASSED, true); +}; +// SOURCE FILE: libdot/js/lib_utf8.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// TODO(davidben): When the string encoding API is implemented, +// replace this with the native in-browser implementation. +// +// https://wiki.whatwg.org/wiki/StringEncoding +// https://encoding.spec.whatwg.org/ + +/** + * A stateful UTF-8 decoder. + */ +lib.UTF8Decoder = function() { + // The number of bytes left in the current sequence. + this.bytesLeft = 0; + // The in-progress code point being decoded, if bytesLeft > 0. + this.codePoint = 0; + // The lower bound on the final code point, if bytesLeft > 0. + this.lowerBound = 0; +}; + +/** + * Decodes a some UTF-8 data, taking into account state from previous + * data streamed through the encoder. + * + * @param {String} str data to decode, represented as a JavaScript + * String with each code unit representing a byte between 0x00 to + * 0xFF. + * @return {String} The data decoded into a JavaScript UTF-16 string. + */ +lib.UTF8Decoder.prototype.decode = function(str) { + var ret = ''; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (this.bytesLeft == 0) { + if (c <= 0x7F) { + ret += str.charAt(i); + } else if (0xC0 <= c && c <= 0xDF) { + this.codePoint = c - 0xC0; + this.bytesLeft = 1; + this.lowerBound = 0x80; + } else if (0xE0 <= c && c <= 0xEF) { + this.codePoint = c - 0xE0; + this.bytesLeft = 2; + this.lowerBound = 0x800; + } else if (0xF0 <= c && c <= 0xF7) { + this.codePoint = c - 0xF0; + this.bytesLeft = 3; + this.lowerBound = 0x10000; + } else if (0xF8 <= c && c <= 0xFB) { + this.codePoint = c - 0xF8; + this.bytesLeft = 4; + this.lowerBound = 0x200000; + } else if (0xFC <= c && c <= 0xFD) { + this.codePoint = c - 0xFC; + this.bytesLeft = 5; + this.lowerBound = 0x4000000; + } else { + ret += '\ufffd'; + } + } else { + if (0x80 <= c && c <= 0xBF) { + this.bytesLeft--; + this.codePoint = (this.codePoint << 6) + (c - 0x80); + if (this.bytesLeft == 0) { + // Got a full sequence. Check if it's within bounds and + // filter out surrogate pairs. + var codePoint = this.codePoint; + if (codePoint < this.lowerBound + || (0xD800 <= codePoint && codePoint <= 0xDFFF) + || codePoint > 0x10FFFF) { + ret += '\ufffd'; + } else { + // Encode as UTF-16 in the output. + if (codePoint < 0x10000) { + ret += String.fromCharCode(codePoint); + } else { + // Surrogate pair. + codePoint -= 0x10000; + ret += String.fromCharCode( + 0xD800 + ((codePoint >>> 10) & 0x3FF), + 0xDC00 + (codePoint & 0x3FF)); + } + } + } + } else { + // Too few bytes in multi-byte sequence. Rewind stream so we + // don't lose the next byte. + ret += '\ufffd'; + this.bytesLeft = 0; + i--; + } + } + } + return ret; +}; + +/** + * Decodes UTF-8 data. This is a convenience function for when all the + * data is already known. + * + * @param {String} str data to decode, represented as a JavaScript + * String with each code unit representing a byte between 0x00 to + * 0xFF. + * @return {String} The data decoded into a JavaScript UTF-16 string. + */ +lib.decodeUTF8 = function(utf8) { + return (new lib.UTF8Decoder()).decode(utf8); +}; + +/** + * Encodes a UTF-16 string into UTF-8. + * + * TODO(davidben): Do we need a stateful version of this that can + * handle a surrogate pair split in two calls? What happens if a + * keypress event would have contained a character outside the BMP? + * + * @param {String} str The string to encode. + * @return {String} The string encoded as UTF-8, as a JavaScript + * string with bytes represented as code units from 0x00 to 0xFF. + */ +lib.encodeUTF8 = function(str) { + var ret = ''; + for (var i = 0; i < str.length; i++) { + // Get a unicode code point out of str. + var c = str.charCodeAt(i); + if (0xDC00 <= c && c <= 0xDFFF) { + c = 0xFFFD; + } else if (0xD800 <= c && c <= 0xDBFF) { + if (i+1 < str.length) { + var d = str.charCodeAt(i+1); + if (0xDC00 <= d && d <= 0xDFFF) { + // Swallow a surrogate pair. + c = 0x10000 + ((c & 0x3FF) << 10) + (d & 0x3FF); + i++; + } else { + c = 0xFFFD; + } + } else { + c = 0xFFFD; + } + } + + // Encode c in UTF-8. + var bytesLeft; + if (c <= 0x7F) { + ret += str.charAt(i); + continue; + } else if (c <= 0x7FF) { + ret += String.fromCharCode(0xC0 | (c >>> 6)); + bytesLeft = 1; + } else if (c <= 0xFFFF) { + ret += String.fromCharCode(0xE0 | (c >>> 12)); + bytesLeft = 2; + } else /* if (c <= 0x10FFFF) */ { + ret += String.fromCharCode(0xF0 | (c >>> 18)); + bytesLeft = 3; + } + + while (bytesLeft > 0) { + bytesLeft--; + ret += String.fromCharCode(0x80 | ((c >>> (6 * bytesLeft)) & 0x3F)); + } + } + return ret; +}; +// SOURCE FILE: libdot/third_party/wcwidth/lib_wc.js +// Copyright (c) 2014 The Chromium OS Authors. All rights reserved. +// Use of lib.wc source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * This JavaScript library is ported from the wcwidth.js module of node.js. + * The original implementation can be found at: + * https://npmjs.org/package/wcwidth.js + */ + +/** + * JavaScript porting of Markus Kuhn's wcwidth() implementation + * + * The following explanation comes from the original C implementation: + * + * This is an implementation of wcwidth() and wcswidth() (defined in + * IEEE Std 1002.1-2001) for Unicode. + * + * http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html + * http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html + * + * In fixed-width output devices, Latin characters all occupy a single + * "cell" position of equal width, whereas ideographic CJK characters + * occupy two such cells. Interoperability between terminal-line + * applications and (teletype-style) character terminals using the + * UTF-8 encoding requires agreement on which character should advance + * the cursor by how many cell positions. No established formal + * standards exist at present on which Unicode character shall occupy + * how many cell positions on character terminals. These routines are + * a first attempt of defining such behavior based on simple rules + * applied to data provided by the Unicode Consortium. + * + * For some graphical characters, the Unicode standard explicitly + * defines a character-cell width via the definition of the East Asian + * FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. + * In all these cases, there is no ambiguity about which width a + * terminal shall use. For characters in the East Asian Ambiguous (A) + * class, the width choice depends purely on a preference of backward + * compatibility with either historic CJK or Western practice. + * Choosing single-width for these characters is easy to justify as + * the appropriate long-term solution, as the CJK practice of + * displaying these characters as double-width comes from historic + * implementation simplicity (8-bit encoded characters were displayed + * single-width and 16-bit ones double-width, even for Greek, + * Cyrillic, etc.) and not any typographic considerations. + * + * Much less clear is the choice of width for the Not East Asian + * (Neutral) class. Existing practice does not dictate a width for any + * of these characters. It would nevertheless make sense + * typographically to allocate two character cells to characters such + * as for instance EM SPACE or VOLUME INTEGRAL, which cannot be + * represented adequately with a single-width glyph. The following + * routines at present merely assign a single-cell width to all + * neutral characters, in the interest of simplicity. This is not + * entirely satisfactory and should be reconsidered before + * establishing a formal standard in lib.wc area. At the moment, the + * decision which Not East Asian (Neutral) characters should be + * represented by double-width glyphs cannot yet be answered by + * applying a simple rule from the Unicode database content. Setting + * up a proper standard for the behavior of UTF-8 character terminals + * will require a careful analysis not only of each Unicode character, + * but also of each presentation form, something the author of these + * routines has avoided to do so far. + * + * http://www.unicode.org/unicode/reports/tr11/ + * + * Markus Kuhn -- 2007-05-26 (Unicode 5.0) + * + * Permission to use, copy, modify, and distribute lib.wc software + * for any purpose and without fee is hereby granted. The author + * disclaims all warranties with regard to lib.wc software. + * + * Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c + */ + +/** + * The following function defines the column width of an ISO 10646 character + * as follows: + * + * - The null character (U+0000) has a column width of 0. + * - Other C0/C1 control characters and DEL will lead to a return value of -1. + * - Non-spacing and enclosing combining characters (general category code Mn + * or Me in the Unicode database) have a column width of 0. + * - SOFT HYPHEN (U+00AD) has a column width of 1. + * - Other format characters (general category code Cf in the Unicode database) + * and ZERO WIDTH SPACE (U+200B) have a column width of 0. + * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) have a + * column width of 0. + * - Spacing characters in the East Asian Wide (W) or East Asian Full-width (F) + * category as defined in Unicode Technical Report #11 have a column width of + * 2. + * - East Asian Ambiguous characters are taken into account if + * regardCjkAmbiguous flag is enabled. They have a column width of 2. + * - All remaining characters (including all printable ISO 8859-1 and WGL4 + * characters, Unicode control characters, etc.) have a column width of 1. + * + * This implementation assumes that characters are encoded in ISO 10646. + */ + +lib.wc = {}; + +// Width of a nul character. +lib.wc.nulWidth = 0; + +// Width of a control character. +lib.wc.controlWidth = 0; + +// Flag whether to consider East Asian Ambiguous characters. +lib.wc.regardCjkAmbiguous = false; + +// Width of an East Asian Ambiguous character. +lib.wc.cjkAmbiguousWidth = 2; + +// Sorted list of non-overlapping intervals of non-spacing characters +// generated by the `./ranges.py` helper. +lib.wc.combining = [ + [0x00ad, 0x00ad], [0x0300, 0x036f], [0x0483, 0x0489], + [0x0591, 0x05bd], [0x05bf, 0x05bf], [0x05c1, 0x05c2], + [0x05c4, 0x05c5], [0x05c7, 0x05c7], [0x0610, 0x061a], + [0x061c, 0x061c], [0x064b, 0x065f], [0x0670, 0x0670], + [0x06d6, 0x06dc], [0x06df, 0x06e4], [0x06e7, 0x06e8], + [0x06ea, 0x06ed], [0x0711, 0x0711], [0x0730, 0x074a], + [0x07a6, 0x07b0], [0x07eb, 0x07f3], [0x07fd, 0x07fd], + [0x0816, 0x0819], [0x081b, 0x0823], [0x0825, 0x0827], + [0x0829, 0x082d], [0x0859, 0x085b], [0x08d3, 0x08e1], + [0x08e3, 0x0902], [0x093a, 0x093a], [0x093c, 0x093c], + [0x0941, 0x0948], [0x094d, 0x094d], [0x0951, 0x0957], + [0x0962, 0x0963], [0x0981, 0x0981], [0x09bc, 0x09bc], + [0x09c1, 0x09c4], [0x09cd, 0x09cd], [0x09e2, 0x09e3], + [0x09fe, 0x09fe], [0x0a01, 0x0a02], [0x0a3c, 0x0a3c], + [0x0a41, 0x0a42], [0x0a47, 0x0a48], [0x0a4b, 0x0a4d], + [0x0a51, 0x0a51], [0x0a70, 0x0a71], [0x0a75, 0x0a75], + [0x0a81, 0x0a82], [0x0abc, 0x0abc], [0x0ac1, 0x0ac5], + [0x0ac7, 0x0ac8], [0x0acd, 0x0acd], [0x0ae2, 0x0ae3], + [0x0afa, 0x0aff], [0x0b01, 0x0b01], [0x0b3c, 0x0b3c], + [0x0b3f, 0x0b3f], [0x0b41, 0x0b44], [0x0b4d, 0x0b4d], + [0x0b56, 0x0b56], [0x0b62, 0x0b63], [0x0b82, 0x0b82], + [0x0bc0, 0x0bc0], [0x0bcd, 0x0bcd], [0x0c00, 0x0c00], + [0x0c04, 0x0c04], [0x0c3e, 0x0c40], [0x0c46, 0x0c48], + [0x0c4a, 0x0c4d], [0x0c55, 0x0c56], [0x0c62, 0x0c63], + [0x0c81, 0x0c81], [0x0cbc, 0x0cbc], [0x0cbf, 0x0cbf], + [0x0cc6, 0x0cc6], [0x0ccc, 0x0ccd], [0x0ce2, 0x0ce3], + [0x0d00, 0x0d01], [0x0d3b, 0x0d3c], [0x0d41, 0x0d44], + [0x0d4d, 0x0d4d], [0x0d62, 0x0d63], [0x0dca, 0x0dca], + [0x0dd2, 0x0dd4], [0x0dd6, 0x0dd6], [0x0e31, 0x0e31], + [0x0e34, 0x0e3a], [0x0e47, 0x0e4e], [0x0eb1, 0x0eb1], + [0x0eb4, 0x0eb9], [0x0ebb, 0x0ebc], [0x0ec8, 0x0ecd], + [0x0f18, 0x0f19], [0x0f35, 0x0f35], [0x0f37, 0x0f37], + [0x0f39, 0x0f39], [0x0f71, 0x0f7e], [0x0f80, 0x0f84], + [0x0f86, 0x0f87], [0x0f8d, 0x0f97], [0x0f99, 0x0fbc], + [0x0fc6, 0x0fc6], [0x102d, 0x1030], [0x1032, 0x1037], + [0x1039, 0x103a], [0x103d, 0x103e], [0x1058, 0x1059], + [0x105e, 0x1060], [0x1071, 0x1074], [0x1082, 0x1082], + [0x1085, 0x1086], [0x108d, 0x108d], [0x109d, 0x109d], + [0x1160, 0x11ff], [0x135d, 0x135f], [0x1712, 0x1714], + [0x1732, 0x1734], [0x1752, 0x1753], [0x1772, 0x1773], + [0x17b4, 0x17b5], [0x17b7, 0x17bd], [0x17c6, 0x17c6], + [0x17c9, 0x17d3], [0x17dd, 0x17dd], [0x180b, 0x180e], + [0x1885, 0x1886], [0x18a9, 0x18a9], [0x1920, 0x1922], + [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193b], + [0x1a17, 0x1a18], [0x1a1b, 0x1a1b], [0x1a56, 0x1a56], + [0x1a58, 0x1a5e], [0x1a60, 0x1a60], [0x1a62, 0x1a62], + [0x1a65, 0x1a6c], [0x1a73, 0x1a7c], [0x1a7f, 0x1a7f], + [0x1ab0, 0x1abe], [0x1b00, 0x1b03], [0x1b34, 0x1b34], + [0x1b36, 0x1b3a], [0x1b3c, 0x1b3c], [0x1b42, 0x1b42], + [0x1b6b, 0x1b73], [0x1b80, 0x1b81], [0x1ba2, 0x1ba5], + [0x1ba8, 0x1ba9], [0x1bab, 0x1bad], [0x1be6, 0x1be6], + [0x1be8, 0x1be9], [0x1bed, 0x1bed], [0x1bef, 0x1bf1], + [0x1c2c, 0x1c33], [0x1c36, 0x1c37], [0x1cd0, 0x1cd2], + [0x1cd4, 0x1ce0], [0x1ce2, 0x1ce8], [0x1ced, 0x1ced], + [0x1cf4, 0x1cf4], [0x1cf8, 0x1cf9], [0x1dc0, 0x1df9], + [0x1dfb, 0x1dff], [0x200b, 0x200f], [0x202a, 0x202e], + [0x2060, 0x2064], [0x2066, 0x206f], [0x20d0, 0x20f0], + [0x2cef, 0x2cf1], [0x2d7f, 0x2d7f], [0x2de0, 0x2dff], + [0x302a, 0x302d], [0x3099, 0x309a], [0xa66f, 0xa672], + [0xa674, 0xa67d], [0xa69e, 0xa69f], [0xa6f0, 0xa6f1], + [0xa802, 0xa802], [0xa806, 0xa806], [0xa80b, 0xa80b], + [0xa825, 0xa826], [0xa8c4, 0xa8c5], [0xa8e0, 0xa8f1], + [0xa8ff, 0xa8ff], [0xa926, 0xa92d], [0xa947, 0xa951], + [0xa980, 0xa982], [0xa9b3, 0xa9b3], [0xa9b6, 0xa9b9], + [0xa9bc, 0xa9bc], [0xa9e5, 0xa9e5], [0xaa29, 0xaa2e], + [0xaa31, 0xaa32], [0xaa35, 0xaa36], [0xaa43, 0xaa43], + [0xaa4c, 0xaa4c], [0xaa7c, 0xaa7c], [0xaab0, 0xaab0], + [0xaab2, 0xaab4], [0xaab7, 0xaab8], [0xaabe, 0xaabf], + [0xaac1, 0xaac1], [0xaaec, 0xaaed], [0xaaf6, 0xaaf6], + [0xabe5, 0xabe5], [0xabe8, 0xabe8], [0xabed, 0xabed], + [0xfb1e, 0xfb1e], [0xfe00, 0xfe0f], [0xfe20, 0xfe2f], + [0xfeff, 0xfeff], [0xfff9, 0xfffb], [0x101fd, 0x101fd], + [0x102e0, 0x102e0], [0x10376, 0x1037a], [0x10a01, 0x10a03], + [0x10a05, 0x10a06], [0x10a0c, 0x10a0f], [0x10a38, 0x10a3a], + [0x10a3f, 0x10a3f], [0x10ae5, 0x10ae6], [0x10d24, 0x10d27], + [0x10f46, 0x10f50], [0x11001, 0x11001], [0x11038, 0x11046], + [0x1107f, 0x11081], [0x110b3, 0x110b6], [0x110b9, 0x110ba], + [0x11100, 0x11102], [0x11127, 0x1112b], [0x1112d, 0x11134], + [0x11173, 0x11173], [0x11180, 0x11181], [0x111b6, 0x111be], + [0x111c9, 0x111cc], [0x1122f, 0x11231], [0x11234, 0x11234], + [0x11236, 0x11237], [0x1123e, 0x1123e], [0x112df, 0x112df], + [0x112e3, 0x112ea], [0x11300, 0x11301], [0x1133b, 0x1133c], + [0x11340, 0x11340], [0x11366, 0x1136c], [0x11370, 0x11374], + [0x11438, 0x1143f], [0x11442, 0x11444], [0x11446, 0x11446], + [0x1145e, 0x1145e], [0x114b3, 0x114b8], [0x114ba, 0x114ba], + [0x114bf, 0x114c0], [0x114c2, 0x114c3], [0x115b2, 0x115b5], + [0x115bc, 0x115bd], [0x115bf, 0x115c0], [0x115dc, 0x115dd], + [0x11633, 0x1163a], [0x1163d, 0x1163d], [0x1163f, 0x11640], + [0x116ab, 0x116ab], [0x116ad, 0x116ad], [0x116b0, 0x116b5], + [0x116b7, 0x116b7], [0x1171d, 0x1171f], [0x11722, 0x11725], + [0x11727, 0x1172b], [0x1182f, 0x11837], [0x11839, 0x1183a], + [0x11a01, 0x11a0a], [0x11a33, 0x11a38], [0x11a3b, 0x11a3e], + [0x11a47, 0x11a47], [0x11a51, 0x11a56], [0x11a59, 0x11a5b], + [0x11a8a, 0x11a96], [0x11a98, 0x11a99], [0x11c30, 0x11c36], + [0x11c38, 0x11c3d], [0x11c3f, 0x11c3f], [0x11c92, 0x11ca7], + [0x11caa, 0x11cb0], [0x11cb2, 0x11cb3], [0x11cb5, 0x11cb6], + [0x11d31, 0x11d36], [0x11d3a, 0x11d3a], [0x11d3c, 0x11d3d], + [0x11d3f, 0x11d45], [0x11d47, 0x11d47], [0x11d90, 0x11d91], + [0x11d95, 0x11d95], [0x11d97, 0x11d97], [0x11ef3, 0x11ef4], + [0x16af0, 0x16af4], [0x16b30, 0x16b36], [0x16f8f, 0x16f92], + [0x1bc9d, 0x1bc9e], [0x1bca0, 0x1bca3], [0x1d167, 0x1d169], + [0x1d173, 0x1d182], [0x1d185, 0x1d18b], [0x1d1aa, 0x1d1ad], + [0x1d242, 0x1d244], [0x1da00, 0x1da36], [0x1da3b, 0x1da6c], + [0x1da75, 0x1da75], [0x1da84, 0x1da84], [0x1da9b, 0x1da9f], + [0x1daa1, 0x1daaf], [0x1e000, 0x1e006], [0x1e008, 0x1e018], + [0x1e01b, 0x1e021], [0x1e023, 0x1e024], [0x1e026, 0x1e02a], + [0x1e8d0, 0x1e8d6], [0x1e944, 0x1e94a], [0xe0001, 0xe0001], + [0xe0020, 0xe007f], [0xe0100, 0xe01ef], +]; + +// Sorted list of non-overlapping intervals of East Asian Ambiguous characters +// generated by the `./ranges.py` helper. +lib.wc.ambiguous = [ + [0x00a1, 0x00a1], [0x00a4, 0x00a4], [0x00a7, 0x00a8], + [0x00aa, 0x00aa], [0x00ad, 0x00ae], [0x00b0, 0x00b4], + [0x00b6, 0x00ba], [0x00bc, 0x00bf], [0x00c6, 0x00c6], + [0x00d0, 0x00d0], [0x00d7, 0x00d8], [0x00de, 0x00e1], + [0x00e6, 0x00e6], [0x00e8, 0x00ea], [0x00ec, 0x00ed], + [0x00f0, 0x00f0], [0x00f2, 0x00f3], [0x00f7, 0x00fa], + [0x00fc, 0x00fc], [0x00fe, 0x00fe], [0x0101, 0x0101], + [0x0111, 0x0111], [0x0113, 0x0113], [0x011b, 0x011b], + [0x0126, 0x0127], [0x012b, 0x012b], [0x0131, 0x0133], + [0x0138, 0x0138], [0x013f, 0x0142], [0x0144, 0x0144], + [0x0148, 0x014b], [0x014d, 0x014d], [0x0152, 0x0153], + [0x0166, 0x0167], [0x016b, 0x016b], [0x01ce, 0x01ce], + [0x01d0, 0x01d0], [0x01d2, 0x01d2], [0x01d4, 0x01d4], + [0x01d6, 0x01d6], [0x01d8, 0x01d8], [0x01da, 0x01da], + [0x01dc, 0x01dc], [0x0251, 0x0251], [0x0261, 0x0261], + [0x02c4, 0x02c4], [0x02c7, 0x02c7], [0x02c9, 0x02cb], + [0x02cd, 0x02cd], [0x02d0, 0x02d0], [0x02d8, 0x02db], + [0x02dd, 0x02dd], [0x02df, 0x02df], [0x0300, 0x036f], + [0x0391, 0x03a1], [0x03a3, 0x03a9], [0x03b1, 0x03c1], + [0x03c3, 0x03c9], [0x0401, 0x0401], [0x0410, 0x044f], + [0x0451, 0x0451], [0x1100, 0x115f], [0x2010, 0x2010], + [0x2013, 0x2016], [0x2018, 0x2019], [0x201c, 0x201d], + [0x2020, 0x2022], [0x2024, 0x2027], [0x2030, 0x2030], + [0x2032, 0x2033], [0x2035, 0x2035], [0x203b, 0x203b], + [0x203e, 0x203e], [0x2074, 0x2074], [0x207f, 0x207f], + [0x2081, 0x2084], [0x20ac, 0x20ac], [0x2103, 0x2103], + [0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113], + [0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126], + [0x212b, 0x212b], [0x2153, 0x2154], [0x215b, 0x215e], + [0x2160, 0x216b], [0x2170, 0x2179], [0x2189, 0x2189], + [0x2190, 0x2199], [0x21b8, 0x21b9], [0x21d2, 0x21d2], + [0x21d4, 0x21d4], [0x21e7, 0x21e7], [0x2200, 0x2200], + [0x2202, 0x2203], [0x2207, 0x2208], [0x220b, 0x220b], + [0x220f, 0x220f], [0x2211, 0x2211], [0x2215, 0x2215], + [0x221a, 0x221a], [0x221d, 0x2220], [0x2223, 0x2223], + [0x2225, 0x2225], [0x2227, 0x222c], [0x222e, 0x222e], + [0x2234, 0x2237], [0x223c, 0x223d], [0x2248, 0x2248], + [0x224c, 0x224c], [0x2252, 0x2252], [0x2260, 0x2261], + [0x2264, 0x2267], [0x226a, 0x226b], [0x226e, 0x226f], + [0x2282, 0x2283], [0x2286, 0x2287], [0x2295, 0x2295], + [0x2299, 0x2299], [0x22a5, 0x22a5], [0x22bf, 0x22bf], + [0x2312, 0x2312], [0x231a, 0x231b], [0x2329, 0x232a], + [0x23e9, 0x23ec], [0x23f0, 0x23f0], [0x23f3, 0x23f3], + [0x2460, 0x24e9], [0x24eb, 0x254b], [0x2550, 0x2573], + [0x2580, 0x258f], [0x2592, 0x2595], [0x25a0, 0x25a1], + [0x25a3, 0x25a9], [0x25b2, 0x25b3], [0x25b6, 0x25b7], + [0x25bc, 0x25bd], [0x25c0, 0x25c1], [0x25c6, 0x25c8], + [0x25cb, 0x25cb], [0x25ce, 0x25d1], [0x25e2, 0x25e5], + [0x25ef, 0x25ef], [0x25fd, 0x25fe], [0x2605, 0x2606], + [0x2609, 0x2609], [0x260e, 0x260f], [0x2614, 0x2615], + [0x261c, 0x261c], [0x261e, 0x261e], [0x2640, 0x2640], + [0x2642, 0x2642], [0x2648, 0x2653], [0x2660, 0x2661], + [0x2663, 0x2665], [0x2667, 0x266a], [0x266c, 0x266d], + [0x266f, 0x266f], [0x267f, 0x267f], [0x2693, 0x2693], + [0x269e, 0x269f], [0x26a1, 0x26a1], [0x26aa, 0x26ab], + [0x26bd, 0x26bf], [0x26c4, 0x26e1], [0x26e3, 0x26e3], + [0x26e8, 0x26ff], [0x2705, 0x2705], [0x270a, 0x270b], + [0x2728, 0x2728], [0x273d, 0x273d], [0x274c, 0x274c], + [0x274e, 0x274e], [0x2753, 0x2755], [0x2757, 0x2757], + [0x2776, 0x277f], [0x2795, 0x2797], [0x27b0, 0x27b0], + [0x27bf, 0x27bf], [0x2b1b, 0x2b1c], [0x2b50, 0x2b50], + [0x2b55, 0x2b59], [0x2e80, 0x2fdf], [0x2ff0, 0x303e], + [0x3040, 0x4dbf], [0x4e00, 0xa4cf], [0xa960, 0xa97f], + [0xac00, 0xd7a3], [0xe000, 0xfaff], [0xfe00, 0xfe19], + [0xfe30, 0xfe6f], [0xff01, 0xff60], [0xffe0, 0xffe6], + [0xfffd, 0xfffd], [0x16fe0, 0x16fe1], [0x17000, 0x18aff], + [0x1b000, 0x1b12f], [0x1b170, 0x1b2ff], [0x1f004, 0x1f004], + [0x1f0cf, 0x1f0cf], [0x1f100, 0x1f10a], [0x1f110, 0x1f12d], + [0x1f130, 0x1f169], [0x1f170, 0x1f1ac], [0x1f200, 0x1f202], + [0x1f210, 0x1f23b], [0x1f240, 0x1f248], [0x1f250, 0x1f251], + [0x1f260, 0x1f265], [0x1f300, 0x1f320], [0x1f32d, 0x1f335], + [0x1f337, 0x1f37c], [0x1f37e, 0x1f393], [0x1f3a0, 0x1f3ca], + [0x1f3cf, 0x1f3d3], [0x1f3e0, 0x1f3f0], [0x1f3f4, 0x1f3f4], + [0x1f3f8, 0x1f43e], [0x1f440, 0x1f440], [0x1f442, 0x1f4fc], + [0x1f4ff, 0x1f53d], [0x1f54b, 0x1f54e], [0x1f550, 0x1f567], + [0x1f57a, 0x1f57a], [0x1f595, 0x1f596], [0x1f5a4, 0x1f5a4], + [0x1f5fb, 0x1f64f], [0x1f680, 0x1f6c5], [0x1f6cc, 0x1f6cc], + [0x1f6d0, 0x1f6d2], [0x1f6eb, 0x1f6ec], [0x1f6f4, 0x1f6f9], + [0x1f910, 0x1f93e], [0x1f940, 0x1f970], [0x1f973, 0x1f976], + [0x1f97a, 0x1f97a], [0x1f97c, 0x1f9a2], [0x1f9b0, 0x1f9b9], + [0x1f9c0, 0x1f9c2], [0x1f9d0, 0x1f9ff], [0x20000, 0x2fffd], + [0x30000, 0x3fffd], [0xe0100, 0xe01ef], [0xf0000, 0xffffd], + [0x100000, 0x10fffd], +]; + +// Sorted list of non-overlapping intervals of East Asian Unambiguous characters +// generated by the `./ranges.py` helper. +lib.wc.unambiguous = [ + [0x1100, 0x115f], [0x231a, 0x231b], [0x2329, 0x232a], + [0x23e9, 0x23ec], [0x23f0, 0x23f0], [0x23f3, 0x23f3], + [0x25fd, 0x25fe], [0x2614, 0x2615], [0x2648, 0x2653], + [0x267f, 0x267f], [0x2693, 0x2693], [0x26a1, 0x26a1], + [0x26aa, 0x26ab], [0x26bd, 0x26be], [0x26c4, 0x26c5], + [0x26ce, 0x26ce], [0x26d4, 0x26d4], [0x26ea, 0x26ea], + [0x26f2, 0x26f3], [0x26f5, 0x26f5], [0x26fa, 0x26fa], + [0x26fd, 0x26fd], [0x2705, 0x2705], [0x270a, 0x270b], + [0x2728, 0x2728], [0x274c, 0x274c], [0x274e, 0x274e], + [0x2753, 0x2755], [0x2757, 0x2757], [0x2795, 0x2797], + [0x27b0, 0x27b0], [0x27bf, 0x27bf], [0x2b1b, 0x2b1c], + [0x2b50, 0x2b50], [0x2b55, 0x2b55], [0x2e80, 0x2fdf], + [0x2ff0, 0x303e], [0x3040, 0x3247], [0x3250, 0x4dbf], + [0x4e00, 0xa4cf], [0xa960, 0xa97f], [0xac00, 0xd7a3], + [0xf900, 0xfaff], [0xfe10, 0xfe19], [0xfe30, 0xfe6f], + [0xff01, 0xff60], [0xffe0, 0xffe6], [0x16fe0, 0x16fe1], + [0x17000, 0x18aff], [0x1b000, 0x1b12f], [0x1b170, 0x1b2ff], + [0x1f004, 0x1f004], [0x1f0cf, 0x1f0cf], [0x1f18e, 0x1f18e], + [0x1f191, 0x1f19a], [0x1f200, 0x1f202], [0x1f210, 0x1f23b], + [0x1f240, 0x1f248], [0x1f250, 0x1f251], [0x1f260, 0x1f265], + [0x1f300, 0x1f320], [0x1f32d, 0x1f335], [0x1f337, 0x1f37c], + [0x1f37e, 0x1f393], [0x1f3a0, 0x1f3ca], [0x1f3cf, 0x1f3d3], + [0x1f3e0, 0x1f3f0], [0x1f3f4, 0x1f3f4], [0x1f3f8, 0x1f43e], + [0x1f440, 0x1f440], [0x1f442, 0x1f4fc], [0x1f4ff, 0x1f53d], + [0x1f54b, 0x1f54e], [0x1f550, 0x1f567], [0x1f57a, 0x1f57a], + [0x1f595, 0x1f596], [0x1f5a4, 0x1f5a4], [0x1f5fb, 0x1f64f], + [0x1f680, 0x1f6c5], [0x1f6cc, 0x1f6cc], [0x1f6d0, 0x1f6d2], + [0x1f6eb, 0x1f6ec], [0x1f6f4, 0x1f6f9], [0x1f910, 0x1f93e], + [0x1f940, 0x1f970], [0x1f973, 0x1f976], [0x1f97a, 0x1f97a], + [0x1f97c, 0x1f9a2], [0x1f9b0, 0x1f9b9], [0x1f9c0, 0x1f9c2], + [0x1f9d0, 0x1f9ff], [0x20000, 0x2fffd], [0x30000, 0x3fffd], +]; + +/** + * Binary search to check if the given unicode character is in the table. + * + * @param {integer} ucs A unicode character code. + * @param {Object} table A sorted list of internals to match against. + * @return {boolean} True if the given character is in the table. + */ +lib.wc.binaryTableSearch_ = function(ucs, table) { + var min = 0, max = table.length - 1; + var mid; + + if (ucs < table[min][0] || ucs > table[max][1]) + return false; + while (max >= min) { + mid = Math.floor((min + max) / 2); + if (ucs > table[mid][1]) { + min = mid + 1; + } else if (ucs < table[mid][0]) { + max = mid - 1; + } else { + return true; + } + } + + return false; +}; + +/** + * Binary search to check if the given unicode character is a space character. + * + * @param {integer} ucs A unicode character code. + * + * @return {boolean} True if the given character is a space character; false + * otherwise. + */ +lib.wc.isSpace = function(ucs) { + return lib.wc.binaryTableSearch_(ucs, lib.wc.combining); +}; + +/** + * Auxiliary function for checking if the given unicode character is a East + * Asian Ambiguous character. + * + * @param {integer} ucs A unicode character code. + * + * @return {boolean} True if the given character is a East Asian Ambiguous + * character. + */ +lib.wc.isCjkAmbiguous = function(ucs) { + return lib.wc.binaryTableSearch_(ucs, lib.wc.ambiguous); +}; + +/** + * Determine the column width of the given character. + * + * @param {integer} ucs A unicode character code. + * + * @return {integer} The column width of the given character. + */ +lib.wc.charWidth = function(ucs) { + if (lib.wc.regardCjkAmbiguous) { + return lib.wc.charWidthRegardAmbiguous(ucs); + } else { + return lib.wc.charWidthDisregardAmbiguous(ucs); + } +}; + +/** + * Determine the column width of the given character without considering East + * Asian Ambiguous characters. + * + * @param {integer} ucs A unicode character code. + * + * @return {integer} The column width of the given character. + */ +lib.wc.charWidthDisregardAmbiguous = function(ucs) { + // Optimize for ASCII characters. + if (ucs < 0x7f) { + if (ucs >= 0x20) + return 1; + else if (ucs == 0) + return lib.wc.nulWidth; + else /* if (ucs < 0x20) */ + return lib.wc.controlWidth; + } + + // Test for 8-bit control characters. + if (ucs < 0xa0) + return lib.wc.controlWidth; + + // Binary search in table of non-spacing characters. + if (lib.wc.isSpace(ucs)) + return 0; + + // Binary search in table of wide characters. + return lib.wc.binaryTableSearch_(ucs, lib.wc.unambiguous) ? 2 : 1; +}; + +/** + * Determine the column width of the given character considering East Asian + * Ambiguous characters. + * + * @param {integer} ucs A unicode character code. + * + * @return {integer} The column width of the given character. + */ +lib.wc.charWidthRegardAmbiguous = function(ucs) { + if (lib.wc.isCjkAmbiguous(ucs)) + return lib.wc.cjkAmbiguousWidth; + + return lib.wc.charWidthDisregardAmbiguous(ucs); +}; + +/** + * Determine the column width of the given string. + * + * @param {string} str A string. + * + * @return {integer} The column width of the given string. + */ +lib.wc.strWidth = function(str) { + var width, rv = 0; + + for (var i = 0; i < str.length;) { + var codePoint = str.codePointAt(i); + width = lib.wc.charWidth(codePoint); + if (width < 0) + return -1; + rv += width; + i += (codePoint <= 0xffff) ? 1 : 2; + } + + return rv; +}; + +/** + * Get the substring at the given column offset of the given column width. + * + * @param {string} str The string to get substring from. + * @param {integer} start The starting column offset to get substring. + * @param {integer} opt_width The column width of the substring. + * + * @return {string} The substring. + */ +lib.wc.substr = function(str, start, opt_width) { + var startIndex = 0; + var endIndex, width; + + // Fun edge case: Normally we associate zero width codepoints (like combining + // characters) with the previous codepoint, so we skip any leading ones while + // including trailing ones. However, if there are zero width codepoints at + // the start of the string, and the substring starts at 0, lets include them + // in the result. This also makes for a simple optimization for a common + // request. + if (start) { + for (width = 0; startIndex < str.length;) { + const codePoint = str.codePointAt(startIndex); + width += lib.wc.charWidth(codePoint); + if (width > start) + break; + startIndex += (codePoint <= 0xffff) ? 1 : 2; + } + } + + if (opt_width != undefined) { + for (endIndex = startIndex, width = 0; endIndex < str.length;) { + const codePoint = str.codePointAt(endIndex); + width += lib.wc.charWidth(codePoint); + if (width > opt_width) + break; + endIndex += (codePoint <= 0xffff) ? 1 : 2; + } + return str.substring(startIndex, endIndex); + } + + return str.substr(startIndex); +}; + +/** + * Get substring at the given start and end column offset. + * + * @param {string} str The string to get substring from. + * @param {integer} start The starting column offset. + * @param {integer} end The ending column offset. + * + * @return {string} The substring. + */ +lib.wc.substring = function(str, start, end) { + return lib.wc.substr(str, start, end - start); +}; +lib.resource.add('libdot/changelog/version', 'text/plain', +'2018-08-29' +); + +lib.resource.add('libdot/changelog/date', 'text/plain', +'1.23' +); + +// This file was generated by libdot/bin/concat.sh. +// It has been marked read-only for your safety. Rather than +// edit it directly, please modify one of these source files. +// +// hterm/audio/bell.ogg +// hterm/images/icon-96.png + +'use strict'; + +lib.resource.add('hterm/audio/bell', 'audio/ogg;base64', +'T2dnUwACAAAAAAAAAADhqW5KAAAAAMFvEjYBHgF2b3JiaXMAAAAAAYC7AAAAAAAAAHcBAAAAAAC4' + +'AU9nZ1MAAAAAAAAAAAAA4aluSgEAAAAAesI3EC3//////////////////8kDdm9yYmlzHQAAAFhp' + +'cGguT3JnIGxpYlZvcmJpcyBJIDIwMDkwNzA5AAAAAAEFdm9yYmlzKUJDVgEACAAAADFMIMWA0JBV' + +'AAAQAABgJCkOk2ZJKaWUoSh5mJRISSmllMUwiZiUicUYY4wxxhhjjDHGGGOMIDRkFQAABACAKAmO' + +'o+ZJas45ZxgnjnKgOWlOOKcgB4pR4DkJwvUmY26mtKZrbs4pJQgNWQUAAAIAQEghhRRSSCGFFGKI' + +'IYYYYoghhxxyyCGnnHIKKqigggoyyCCDTDLppJNOOumoo4466ii00EILLbTSSkwx1VZjrr0GXXxz' + +'zjnnnHPOOeecc84JQkNWAQAgAAAEQgYZZBBCCCGFFFKIKaaYcgoyyIDQkFUAACAAgAAAAABHkRRJ' + +'sRTLsRzN0SRP8ixREzXRM0VTVE1VVVVVdV1XdmXXdnXXdn1ZmIVbuH1ZuIVb2IVd94VhGIZhGIZh' + +'GIZh+H3f933f930gNGQVACABAKAjOZbjKaIiGqLiOaIDhIasAgBkAAAEACAJkiIpkqNJpmZqrmmb' + +'tmirtm3LsizLsgyEhqwCAAABAAQAAAAAAKBpmqZpmqZpmqZpmqZpmqZpmqZpmmZZlmVZlmVZlmVZ' + +'lmVZlmVZlmVZlmVZlmVZlmVZlmVZlmVZlmVZQGjIKgBAAgBAx3Ecx3EkRVIkx3IsBwgNWQUAyAAA' + +'CABAUizFcjRHczTHczzHczxHdETJlEzN9EwPCA1ZBQAAAgAIAAAAAABAMRzFcRzJ0SRPUi3TcjVX' + +'cz3Xc03XdV1XVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVYHQkFUAAAQAACGdZpZq' + +'gAgzkGEgNGQVAIAAAAAYoQhDDAgNWQUAAAQAAIih5CCa0JrzzTkOmuWgqRSb08GJVJsnuamYm3PO' + +'OeecbM4Z45xzzinKmcWgmdCac85JDJqloJnQmnPOeRKbB62p0ppzzhnnnA7GGWGcc85p0poHqdlY' + +'m3POWdCa5qi5FJtzzomUmye1uVSbc84555xzzjnnnHPOqV6czsE54Zxzzonam2u5CV2cc875ZJzu' + +'zQnhnHPOOeecc84555xzzglCQ1YBAEAAAARh2BjGnYIgfY4GYhQhpiGTHnSPDpOgMcgppB6NjkZK' + +'qYNQUhknpXSC0JBVAAAgAACEEFJIIYUUUkghhRRSSCGGGGKIIaeccgoqqKSSiirKKLPMMssss8wy' + +'y6zDzjrrsMMQQwwxtNJKLDXVVmONteaec645SGultdZaK6WUUkoppSA0ZBUAAAIAQCBkkEEGGYUU' + +'UkghhphyyimnoIIKCA1ZBQAAAgAIAAAA8CTPER3RER3RER3RER3RER3P8RxREiVREiXRMi1TMz1V' + +'VFVXdm1Zl3Xbt4Vd2HXf133f141fF4ZlWZZlWZZlWZZlWZZlWZZlCUJDVgEAIAAAAEIIIYQUUkgh' + +'hZRijDHHnINOQgmB0JBVAAAgAIAAAAAAR3EUx5EcyZEkS7IkTdIszfI0T/M00RNFUTRNUxVd0RV1' + +'0xZlUzZd0zVl01Vl1XZl2bZlW7d9WbZ93/d93/d93/d93/d939d1IDRkFQAgAQCgIzmSIimSIjmO' + +'40iSBISGrAIAZAAABACgKI7iOI4jSZIkWZImeZZniZqpmZ7pqaIKhIasAgAAAQAEAAAAAACgaIqn' + +'mIqniIrniI4oiZZpiZqquaJsyq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7rukBo' + +'yCoAQAIAQEdyJEdyJEVSJEVyJAcIDVkFAMgAAAgAwDEcQ1Ikx7IsTfM0T/M00RM90TM9VXRFFwgN' + +'WQUAAAIACAAAAAAAwJAMS7EczdEkUVIt1VI11VItVVQ9VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' + +'VVVVVVVVVVVV1TRN0zSB0JCVAAAZAAAjQQYZhBCKcpBCbj1YCDHmJAWhOQahxBiEpxAzDDkNInSQ' + +'QSc9uJI5wwzz4FIoFURMg40lN44gDcKmXEnlOAhCQ1YEAFEAAIAxyDHEGHLOScmgRM4xCZ2UyDkn' + +'pZPSSSktlhgzKSWmEmPjnKPSScmklBhLip2kEmOJrQAAgAAHAIAAC6HQkBUBQBQAAGIMUgophZRS' + +'zinmkFLKMeUcUko5p5xTzjkIHYTKMQadgxAppRxTzinHHITMQeWcg9BBKAAAIMABACDAQig0ZEUA' + +'ECcA4HAkz5M0SxQlSxNFzxRl1xNN15U0zTQ1UVRVyxNV1VRV2xZNVbYlTRNNTfRUVRNFVRVV05ZN' + +'VbVtzzRl2VRV3RZV1bZl2xZ+V5Z13zNNWRZV1dZNVbV115Z9X9ZtXZg0zTQ1UVRVTRRV1VRV2zZV' + +'17Y1UXRVUVVlWVRVWXZlWfdVV9Z9SxRV1VNN2RVVVbZV2fVtVZZ94XRVXVdl2fdVWRZ+W9eF4fZ9' + +'4RhV1dZN19V1VZZ9YdZlYbd13yhpmmlqoqiqmiiqqqmqtm2qrq1bouiqoqrKsmeqrqzKsq+rrmzr' + +'miiqrqiqsiyqqiyrsqz7qizrtqiquq3KsrCbrqvrtu8LwyzrunCqrq6rsuz7qizruq3rxnHrujB8' + +'pinLpqvquqm6um7runHMtm0co6rqvirLwrDKsu/rui+0dSFRVXXdlF3jV2VZ921fd55b94WybTu/' + +'rfvKceu60vg5z28cubZtHLNuG7+t+8bzKz9hOI6lZ5q2baqqrZuqq+uybivDrOtCUVV9XZVl3zdd' + +'WRdu3zeOW9eNoqrquirLvrDKsjHcxm8cuzAcXds2jlvXnbKtC31jyPcJz2vbxnH7OuP2daOvDAnH' + +'jwAAgAEHAIAAE8pAoSErAoA4AQAGIecUUxAqxSB0EFLqIKRUMQYhc05KxRyUUEpqIZTUKsYgVI5J' + +'yJyTEkpoKZTSUgehpVBKa6GU1lJrsabUYu0gpBZKaS2U0lpqqcbUWowRYxAy56RkzkkJpbQWSmkt' + +'c05K56CkDkJKpaQUS0otVsxJyaCj0kFIqaQSU0mptVBKa6WkFktKMbYUW24x1hxKaS2kEltJKcYU' + +'U20txpojxiBkzknJnJMSSmktlNJa5ZiUDkJKmYOSSkqtlZJSzJyT0kFIqYOOSkkptpJKTKGU1kpK' + +'sYVSWmwx1pxSbDWU0lpJKcaSSmwtxlpbTLV1EFoLpbQWSmmttVZraq3GUEprJaUYS0qxtRZrbjHm' + +'GkppraQSW0mpxRZbji3GmlNrNabWam4x5hpbbT3WmnNKrdbUUo0txppjbb3VmnvvIKQWSmktlNJi' + +'ai3G1mKtoZTWSiqxlZJabDHm2lqMOZTSYkmpxZJSjC3GmltsuaaWamwx5ppSi7Xm2nNsNfbUWqwt' + +'xppTS7XWWnOPufVWAADAgAMAQIAJZaDQkJUAQBQAAEGIUs5JaRByzDkqCULMOSepckxCKSlVzEEI' + +'JbXOOSkpxdY5CCWlFksqLcVWaykptRZrLQAAoMABACDABk2JxQEKDVkJAEQBACDGIMQYhAYZpRiD' + +'0BikFGMQIqUYc05KpRRjzknJGHMOQioZY85BKCmEUEoqKYUQSkklpQIAAAocAAACbNCUWByg0JAV' + +'AUAUAABgDGIMMYYgdFQyKhGETEonqYEQWgutddZSa6XFzFpqrbTYQAithdYySyXG1FpmrcSYWisA' + +'AOzAAQDswEIoNGQlAJAHAEAYoxRjzjlnEGLMOegcNAgx5hyEDirGnIMOQggVY85BCCGEzDkIIYQQ' + +'QuYchBBCCKGDEEIIpZTSQQghhFJK6SCEEEIppXQQQgihlFIKAAAqcAAACLBRZHOCkaBCQ1YCAHkA' + +'AIAxSjkHoZRGKcYglJJSoxRjEEpJqXIMQikpxVY5B6GUlFrsIJTSWmw1dhBKaS3GWkNKrcVYa64h' + +'pdZirDXX1FqMteaaa0otxlprzbkAANwFBwCwAxtFNicYCSo0ZCUAkAcAgCCkFGOMMYYUYoox55xD' + +'CCnFmHPOKaYYc84555RijDnnnHOMMeecc845xphzzjnnHHPOOeecc44555xzzjnnnHPOOeecc845' + +'55xzzgkAACpwAAAIsFFkc4KRoEJDVgIAqQAAABFWYowxxhgbCDHGGGOMMUYSYowxxhhjbDHGGGOM' + +'McaYYowxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHG' + +'GFtrrbXWWmuttdZaa6211lprrQBAvwoHAP8HG1ZHOCkaCyw0ZCUAEA4AABjDmHOOOQYdhIYp6KSE' + +'DkIIoUNKOSglhFBKKSlzTkpKpaSUWkqZc1JSKiWlllLqIKTUWkottdZaByWl1lJqrbXWOgiltNRa' + +'a6212EFIKaXWWostxlBKSq212GKMNYZSUmqtxdhirDGk0lJsLcYYY6yhlNZaazHGGGstKbXWYoy1' + +'xlprSam11mKLNdZaCwDgbnAAgEiwcYaVpLPC0eBCQ1YCACEBAARCjDnnnHMQQgghUoox56CDEEII' + +'IURKMeYcdBBCCCGEjDHnoIMQQgghhJAx5hx0EEIIIYQQOucchBBCCKGEUkrnHHQQQgghlFBC6SCE' + +'EEIIoYRSSikdhBBCKKGEUkopJYQQQgmllFJKKaWEEEIIoYQSSimllBBCCKWUUkoppZQSQgghlFJK' + +'KaWUUkIIoZRQSimllFJKCCGEUkoppZRSSgkhhFBKKaWUUkopIYQSSimllFJKKaUAAIADBwCAACPo' + +'JKPKImw04cIDUGjISgCADAAAcdhq6ynWyCDFnISWS4SQchBiLhFSijlHsWVIGcUY1ZQxpRRTUmvo' + +'nGKMUU+dY0oxw6yUVkookYLScqy1dswBAAAgCAAwECEzgUABFBjIAIADhAQpAKCwwNAxXAQE5BIy' + +'CgwKx4Rz0mkDABCEyAyRiFgMEhOqgaJiOgBYXGDIB4AMjY20iwvoMsAFXdx1IIQgBCGIxQEUkICD' + +'E2544g1PuMEJOkWlDgIAAAAA4AAAHgAAkg0gIiKaOY4Ojw+QEJERkhKTE5QAAAAAALABgA8AgCQF' + +'iIiIZo6jw+MDJERkhKTE5AQlAAAAAAAAAAAACAgIAAAAAAAEAAAACAhPZ2dTAAQYOwAAAAAAAOGp' + +'bkoCAAAAmc74DRgyNjM69TAzOTk74dnLubewsbagmZiNp4d0KbsExSY/I3XUTwJgkeZdn1HY4zoj' + +'33/q9DFtv3Ui1/jmx7lCUtPt18/sYf9MkgAsAGRBd3gMGP4sU+qCPYBy9VrA3YqJosW3W2/ef1iO' + +'/u3cg8ZG/57jU+pPmbGEJUgkfnaI39DbPqxddZphbMRmCc5rKlkUMkyx8iIoug5dJv1OYH9a59c+' + +'3Gevqc7Z2XFdDjL/qHztRfjWEWxJ/aiGezjohu9HsCZdQBKbiH0VtU/3m85lDG2T/+xkZcYnX+E+' + +'aqzv/xTgOoTFG+x7SNqQ4N+oAABSxuVXw77Jd5bmmTmuJakX7509HH0kGYKvARPpwfOSAPySPAc2' + +'EkneDwB2HwAAJlQDYK5586N79GJCjx4+p6aDUd27XSvRyXLJkIC5YZ1jLv5lpOhZTz0s+DmnF1di' + +'ptrnM6UDgIW11Xh8cHTd0/SmbgOAdxcyWwMAAGIrZ3fNSfZbzKiYrK4+tPqtnMVLOeWOG2kVvUY+' + +'p2PJ/hkCl5aFRO4TLGYPZcIU3vYM1hohS4jHFlnyW/2T5J7kGsShXWT8N05V+3C/GPqJ1QdWisGP' + +'xEzHqXISBPIinWDUt7IeJv/f5OtzBxpTzZZQ+CYEhHXfqG4aABQli72GJhN4oJv+hXcApAJSErAW' + +'8G2raAX4NUcABnVt77CzZAB+LsHcVe+Q4h+QB1wh/ZrJTPxSBdI8mgTeAdTsQOoFUEng9BHcVPhx' + +'SRRYkKWZJXOFYP6V4AEripJoEjXgA2wJRZHSExmJDm8F0A6gEXsg5a4ZsALItrMB7+fh7UKLvYWS' + +'dtsDwFf1mzYzS1F82N1h2Oyt2e76B1QdS0SAsQigLPMOgJS9JRC7hFXA6kUsLFNKD5cA5cTRvgSq' + +'Pc3Fl99xW3QTi/MHR8DEm6WnvaVQATwRqRKjywQ9BrrhugR2AKTsPQeQckrAOgDOhbTESyrXQ50C' + +'kNpXdtWjW7W2/3UjeX3U95gIdalfRAoAmqUEiwp53hCdcCwlg47fcbfzlmQMAgaBkh7c+fcDgF+i' + +'fwDXfzegLPcLYJsAAJQArTXjnh/uXGy3v1Hk3pV6/3t5ruW81f6prfbM2Q3WNVy98BwUtbCwhFhA' + +'WuPev6Oe/4ZaFQUcgKrVs4defzh1TADA1DEh5b3VlDaECw5b+bPfkKos3tIAue3vJZOih3ga3l6O' + +'3PSfIkrLv0PAS86PPdL7g8oc2KteNFKKzKRehOv2gJoFLBPXmaXvPBQILgJon0bbWBszrYZYYwE7' + +'jl2j+vTdU7Vpk21LiU0QajPkywAAHqbUC0/YsYOdb4e6BOp7E0cCi04Ao/TgD8ZVAMid6h/A8IeB' + +'Nkp6/xsAACZELEYIk+yvI6Qz1NN6lIftB/6IMWjWJNOqPTMedAmyaj6Es0QBklJpiSWWHnQ2CoYb' + +'GWAmt+0gLQBFKCBnp2QUUQZ/1thtZDBJUpFWY82z34ocorB62oX7qB5y0oPAv/foxH25wVmgIHf2' + +'xFOr8leZcBq1Kx3ZvCq9Bga639AxuHuPNL/71YCF4EywJpqHFAX6XF0sjVbuANnvvdLcrufYwOM/' + +'iDa6iA468AYAAB6mNBMXcgTD8HSRqJ4vw8CjAlCEPACASlX/APwPOJKl9xQAAAPmnev2eWp33Xgy' + +'w3Dvfz6myGk3oyP8YTKsCOvzAgALQi0o1c6Nzs2O2Pg2h4ACIJAgAGP0aNn5x0BDgVfH7u2TtyfD' + +'cRIuYAyQhBF/lvSRAttgA6TPbWZA9gaUrZWAUEAA+Dx47Q3/r87HxUUqZmB0BmUuMlojFjHt1gDu' + +'nnvuX8MImsjSq5WkzSzGS62OEIlOufWWezxWpv6FBgDgJVltfXFYtNAAnqU0xQoD0YLiXo5cF5QV' + +'4CnY1tBLAkZCOABAhbk/AM+/AwSCCdlWAAAMcFjS7owb8GVDzveDiZvznbt2tF4bL5odN1YKl88T' + +'AEABCZvufq9YCTBtMwVAQUEAwGtNltzSaHvADYC3TxLVjqiRA+OZAMhzcqEgRcAOwoCgvdTxsTHL' + +'QEF6+oOb2+PAI8ciPQcXg7pOY+LjxQSv2fjmFuj34gGwz310/bGK6z3xgT887eomWULEaDd04wHe' + +'tYxdjcgV2SxvSwn0VoZXJRqkRC5ASQ/muVoAUsX7AgAQMBNaVwAAlABRxT/1PmfqLqSRNDbhXb07' + +'berpB3b94jpuWEZjBCD2OcdXFpCKEgCDfcFPMw8AAADUwT4lnUm50lmwrpMMhPQIKj6u0E8fr2vG' + +'BngMNdIlrZsigjahljud6AFVg+tzXwUnXL3TJLpajaWKA4VAAAAMiFfqJgKAZ08XrtS3dxtQNYcp' + +'PvYEG8ClvrQRJgBephwnNWJjtGqmp6VEPSvBe7EBiU3qgJbQAwD4Le8LAMDMhHbNAAAlgK+tFs5O' + +'+YyJc9yCnJa3rxLPulGnxwsXV9Fsk2k4PisCAHC8FkwbGE9gJQAAoMnyksj0CdFMZLLgoz8M+Fxz' + +'iwYBgIx+zHiCBAKAlBKNpF1sO9JpVcyEi9ar15YlHgrut5fPJnkdJ6vEwZPyAHQBIEDUrlMcBAAd' + +'2KAS0Qq+JwRsE4AJZtMnAD6GnOYwYlOIZvtzUNdjreB7fiMkWI0CmBB6AIAKc38A9osEFlTSGECB' + +'+cbeRDC0aRpLHqNPplcK/76Lxn2rpmqyXsYJWRi/FQAAAKBQk9MCAOibrQBQADCDsqpooPutd+05' + +'Ce9g6iEdiYXgVmQAI4+4wskEBEiBloNQ6Ki0/KTQ0QjWfjxzi+AeuXKoMjEVfQOZzr0y941qLgM2' + +'AExvbZOqcxZ6J6krlrj4y2j9AdgKDx6GnJsVLhbc42uq584+ouSdNBpoCiCVHrz+WzUA/DDtD8AT' + +'gA3h0lMCAAzcFv+S+fSSNkeYWlTpb34mf2RfmqqJeMeklhHAfu7VoAEACgAApKRktL+KkQDWMwYC' + +'UAAAAHCKsp80xhp91UjqQBw3x45cetqkjQEyu3G9B6N+R650Uq8OVig7wOm6Wun0ea4lKDPoabJs' + +'6aLqgbhPzpv4KR4iODilw88ZpY7q1IOMcbASAOAVtmcCnobcrkG4KGS7/ZnskVWRNF9J0RUHKOnB' + +'yy9WA8Dv6L4AAARMCQUA4GritfVM2lcZfH3Q3T/vZ47J2YHhcmBazjfdyuV25gLAzrc0cwAAAAAY' + +'Ch6PdwAAAGyWjFW4yScjaWa2mGcofHxWxewKALglWBpLUvwwk+UOh5eNGyUOs1/EF+pZr+ud5Ozo' + +'GwYdAABg2p52LiSgAY/ZVlOmilEgHn6G3OcwYjzI7vOj1t6xsx4S3lBY96EUQBF6AIBAmPYH4PoG' + +'YCoJAADWe+OZJZi7/x76/yH7Lzf9M5XzRKnFPmveMsilQHwVAAAAAKB3LQD8PCIAAADga0QujBLy' + +'wzeJ4a6Z/ERVBAUlAEDqvoM7BQBAuAguzFqILtmjH3Kd4wfKobnOhA3z85qWoRPm9hwoOHoDAAlC' + +'bwDAA56FHAuXflHo3fe2ttG9XUDeA9YmYCBQ0oPr/1QC8IvuCwAAApbUAQCK22MmE3O78VAbHQT9' + +'PIPNoT9zNc3l2Oe7TAVLANBufT8MAQAAAGzT4PS8AQAAoELGHb2uaCwwEv1EWhFriUkbAaAZ27/f' + +'VZnTZXbWz3BwWpjUaMZKRj7dZ0J//gUeTdpVEwAAZOFsNxKAjQSgA+ABPoY8Jj5y2wje81jsXc/1' + +'TOQWTDYZBmAkNDiqVwuA2NJ9AQAAEBKAt9Vrsfs/2N19MO91S9rd8EHTZHnzC5MYmfQEACy/FBcA' + +'AADA5c4gi4z8RANs/m6FNXVo9DV46JG1BBDukqlw/Va5G7QbuGVSI+2aZaoLXJrdVj2zlC9Z5QEA' + +'EFz/5QzgVZwAAAAA/oXcxyC6WfTu+09Ve/c766J4VTAGUFmA51+VANKi/QPoPwYgYAkA715OH4S0' + +'s5KDHvj99MMq8TPFc3roKZnGOoT1bmIhVgc7XAMBAAAAAMAW1VbQw3gapzOpJd+Kd2fc4iSO62fJ' + +'v9+movui1wUNPAj059N3OVxzk4gV73PmE8FIA2F5mRq37Evc76vLXfF4rD5UJJAw46hW6LZCb5sN' + +'Ldx+kzMCAAB+hfy95+965ZCLP7B3/VlTHCvDEKtQhTm4KiCgAEAbrfbWTPssAAAAXpee1tVrozYY' + +'n41wD1aeYtkKfswN5/SXPO0JDnhO/4laUortv/s412fybe/nONdncoCHnBVliu0CQGBWlPY/5Kwo' + +'m2L/kruPM6Q7oz4tvDQy+bZ3HzOi+gNHA4DZEgA=' +); + +lib.resource.add('hterm/images/icon-96', 'image/png;base64', +'iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAStklEQVR42u1dBXjrupL+RzIGmjIf' + +'vAcu42NmZub3lpmZmZmZmRkuMzPDYaYyJG0Sa9b2p2z1eQtp7bzefpv/nKnkkSw7Gg1IshNsDtpo' + +'o4022mijDWp/tlTgzbpJSqYvMoFTC9vjRD5JLb9RYaRkpk22SS28P8pacAaPdZ41KYMCI89YB6wN' + +'3JzQJM3UIGqurfTlKQTAZtqENid5SlNdU804VmbbWQtA6HMkAAdADsBeAJ7mxwIhIhFSXJ9iRPw4' + +'JYDEcqmGWEp1HhCI8gAtpXF7scB1ZRH9E3HObANCNy1AoGTegNDnCdE41tfQDH2t+CINQEpJ9Xp9' + +'7oUDh3+nXK48DYAMIWQmANIkNTn6vP69e3d/zctfeu0nXNexmVn3F0gDAMxMlBoHuht0qnsEEekC' + +'42SdGHmNxgVjgk4bPN04Yui8bhc534cQBH35RKrPN9sGdLnB1/Wuv+HW4f+6/tZvBHAaAJvmKr0A' + +'jJGvyQMw8pLrrvqeT378Ax8UwrKeevoFgEhfjcGGO2JO+iuTt1SW5DHzyraDExyTlWwHjCQ/CAJc' + +'ecU+XHn5xWDmVCGQFAKljsLbx8Ynvv3Bhx7/EQCzurimU04jADLsvK3r73/7W1//g1/6hU++uVqt' + +'0X/dcBcKxRIsy9Ji34DPow2et6FzgcXFKk6fOY83vu4VEFKkDiYHB3roSz73sc+Oj08eOHzk+B9o' + +'MyQABGk0gCIyOt9xHPvaD3/wnT/5VV/+meumpmbwD/98A0qdvVEBNhvMDCJaVXtM01GtVlEs+LBt' + +'C1ngzW98tX/m7Llv/emf+83HarX6vbrfGECQRgBmlLP9Ix961499+zd/5XVj45P407/8FxQ7uiGl' + +'QK1Ww1ZCvR6gXq3AsgQ8zwYzUkMIgXe+/Q1Dd9x5/6duv/P+R7QjprQaIHQd/8orLvnCJz/2/pfm' + +'cj7+6rf+DK5XgOu6sT3dQtBawqjW6lhYXIRlSTAjE/T39eLSS/ZeEwqgE8CiYUV4vQIgTULTyFve' + +'9Or3WJZN/3n9HTh3fgrFjhJmZmawFaGUwkJlEffc9xh83wMYqcFg7Noxinw+l9OBikirAabz7eju' + +'6sxJKTE7W4bn5+D7PrYmtI/gAFJasCwb4IzaBMHzXE8LgBJC4I1GQRKAa4Xo6upEsZiH53nIRYLe' + +'olDMCIIq+nq70dFRAGckgFKpAD+UgBaAgfRRkGvbliwUcoh8ABHFYSfWMnBrxOzL12PwKufzSvV5' + +'5Tpmi5a0IASBQCgWcujs7ABn5AQic+b5rhNlAVAmTliTEwnA990wIxEEdUQYnxjHidMnAUIcBYAB' + +'RqNDdC7BM8t0VtfTnGRd8FKdRIjJcVlCsAbPPA5UAK4rXLJjP7aNbkO9XoPrOrEQWHEm69Kua0ca' + +'YEspvCBQ5toSp9EASCkt27ZF1PlCxBOZOPo5feY0Xpg8jHe/7V3YNjhqjDRac3mMVl1Oo40vtREt' + +'W+2FYwdw/S03YHJ6EkODQ1hcXIQUcaeBlUIWsCwZ+QDLdZxcubKAtBpgNmzZliUa6yLMKiRGoBR2' + +'79yN6666FlJYABgvRhAIncUSHn/iCdQrAZjjSAiKFQQRVEhZIRJASJEACICmlAKQUtqhBETjw5ij' + +'uFqr4oWjBwHmF7/jVUHc6aRNXxAoZA3PdYXruvlldJfTaIATaQA4KU/CzNwMDp84DOYXf+hZXiij' + +'hJz+DK0QAEd+RYTOOAcgMw0g24oskNYAIoCXxDpbnsOxM8fB5qacwKZD+3WQcS+VxQrYYXNVNGMh' + +'I1odiIRQSHb8BmbCpgZYjmVLYi0ANmxQNKpOj50FFOB3WnDzEpOnFkGbuOXPimG5Ap0jLqZOLiKo' + +'MyIsVhfB9lLEpFSQ+S26jh2Fo/n0YagRCUlLRhpAAIMIyWl9vBinAkbfoIPXf+0wnrlxAs/dPInK' + +'VB1CUOsFkdhD6Nnp49oP98EvWfjvnzqGak0hVlwwFJsaoADK9vq2Y0eOOKUGJLTAjjQgFgBAy/gT' + +'vbGIyXC0nX66jJd+YgC7X1nCo39/AccfmUVQU1F5y0d9rsvGJW/txuXv7oGqMx7+2/OoVxWIzE5S' + +'OkfaBBGyhGPHc4G8YYjT+wDLDgUgJbQPWDGuL0/VcefvnMLRB2dw3Uf78dZv345D90zjsX++gPGj' + +'C7peC8yNI7DjpSVcE476rlEPB++awmP/dCEaEMtqbAP1Fqzkhn0VaUAegMzABJkaIMG8epNEiE3R' + +'0funce75Mi4NR+MV7+3B6NUFPPnvY3jupslISJkKoW9PDld/sA+7Xt6B8SMV3Pjzx3Di0TkENQaJ' + +'5A1qM8VRljKPgpg58pcNHyCz0ADSTnhNDTBBglCZruPhvz+PY4/M4Jqwg6772AB2vqwDd/zmKYwd' + +'WQAJpMalb+vGSz81AA6Ah/76HJ69KfI7tej6K7RPUKwaWQT1FmiAlJEJykXZZh5cE02FoaEJkpYE' + +'wGsKwNQGAnDhQAUP/915TJ5YwPCleZSG3WwWvwgYvryAYr8Tm5wn/2Mc5cm481c9RzXWobQPyBpS' + +'ikgDGgJAVvMARzY0AARwc7Y5Ckn3vK4TV7+/D5YncN+fnsWpJ+cgsnDICnj0n85DSOCSUBO6Rl08' + +'8g8XcObZ+VgjSKweKRG1xgcIEQnA9QE46aMgwwlHAmBuOFFepeMRd8rI1cU4FBzYn8exh2bw6D9e' + +'wNihCjgrR0wI21vAzb9yIrT/pfha7/y+nXj+5gk8EWrDzJlF/WxQUgMUwEtREGW/5RlpgJdaABq0' + +'pAGicYFVFaBzxMGV7+vFvtd3YfpsFbf+6ok4KqovxqFoph+YBBAsMg7cPonTT83jsnd247J39IQR' + +'UUcceR28cxrVcrBUX2sAa1Nar7dCAwhevCkDN7UADB9gSyEBaBVYYeT37PTw9u/aAbcg8Pi/XMAz' + +'109gfqLhFAktgX46LbrOg395DscemAnD0X68+suGQ+3L4Y7fOhVHRA00nDBRa3wAEGuAA8DbqABI' + +'kyEA2xFSrBHHM2xf4Ozz82HIOb5kbgSh1TDv69wLZdz0S8dxUTgRHLwkD2HRkgCIdBi6NBPmVpgg' + +'L7krBkrnA6xIA0Qjfl4x9Bw7XInDzHo1hblJbZYoNkvP3zqFw/fPIKgqGNC7aNoEtUQDEJkg23Ec' + +'v1qtrhkFiWYeTYzCUCEEeI15QDTSgjpnMerTmyUB1CsKrGACyvABQb1VAnAt13V8NAHRxGqotEMI' + +'QUbJFgGtMhNuqQa4Ui9HbEgDKFknioKIhC4kbGUwFBhsOGHO/AqhCxAh5dOsBZFBMoqCGhpARJv7' + +'ihul35oEt84E6U0ZCv1APp0T1tACsIhEpquZQhJsT2C9UAGjtqA2vDnPzOD/NUEqymcOJ94TcPJZ' + +'zYSFHYKIjHlA+iXk/kvyeO1XDENYtK6J16kn53H375+OBbFukBkFtWoewHAdJ1qQKwAQWcyEtQaQ' + +'4QPSmk6KZ6gXDlVAcn0x9vTpxTSjdhkBcOYmSO+KNTZlKK0GWHYoASJkZoJIABPHFnDbb5zEFxts' + +'hqEtMkG2rfcEtAZsJAoimBpgGRqg062KVmsAmBH2V2NfWKZ1woxYAyIBwFABXma+nE30wytV4rU/' + +'OK9xLWaGUmpJAHE+awEDUsrGnoCERsooyJYALfPaOEHNByBl7BGwKQsy8kYLUZ1kOTXyZprgUYJH' + +'SBzrctLHDZ6huflCLt61qtWDWAMawsgOWgCe5+v+JYN4vT6AtAbIpSCIGuEcRoaG8TrXRcwzCeZ7' + +'u2gcm4QIZn0QEudC5wGYdYxUt2PyjRSAyWsc6mvW6hW0CnpXzAdgQ6NZAdByJsgKBQAQGCp+oQFQ' + +'8ePdhUIBxWJxXfrJYKQHNRUMMK9kuwhzc3O4eO+eeLQqpbLfFfMaAgAnhdDccrSpAZYtAUApxujI' + +'EN725lfg3//7bvT19cOyLJhg44/ZCTo1y40yI79qmT4/5un2jTx0+XLtmAOAlUJXVx6ve83LdFkr' + +'dsWMTZkUTpikjFyAJUxHFr6oDc918cDDT6KyMB8xzVFpmBpAGGZHiCgVZgoRphSlQkCQTvXxEhFk' + +'lMolXnyseY28NMtlIjXaCzsHO7aPoFDIQ6nWCMDzXS2AdJvybMl4HiaSLyK89S2vxRte/wrU6vXG' + +'IFrzOxdWTZcaMNtCgq15a9vNtWyTMjUncwEguSu2ISesO3vp3YDkE2ZSypiyQMO0JO331gTFryoJ' + +'IXylVLrFOCtEpAHmaG5jbQ3Qb8r45XKFN2qCOCJpSUsxi/n5SlOP8rXB0WpoUgC8HgGwQYqI7AMH' + +'j1G9zk2Ea20wgI5iPhqs8dMk6/26GrOyiqharc16nlffvn3EaWtAc/BcBw8+/Ojc+PjkKaMvuWkN' + +'ME+YnZ17+rnnDxweHOi9iCM+gzbLOXLrG8piu46JIO5/4NHD9XpwbEPfEqjJ01R0XecDYcz8lvhF' + +'MSEkwJIBaU76AZA+SsST5oHOmidqvsHQieYk6ya/ucysT/pPon6yLum/5tXN4uV45ocAKHEeWFdQ' + +'YcpKKb4wNnH/xMTUjwGYArBofLHfuhfjeO+eXbu+/ms+946JyWl16NAxWmV80AZGImW+M0z/dxWU' + +'NbvJNQzaqNK4ro13v/NN9C//doP4gz/+mxKAWWNQb2hHzL/s0n1XDfT3W3fe8wRAVmLytCE56HM3' + +'LL/E+bRqb+niFZ9rSvD0nnHzd2Y+M3vs5Ckwc/S9QQMABgGc0cvS9fU8migi0uUDey7asfvQ4eMQ' + +'louuzs74Am0sL4TZQhHHTpzG8FB/qdRR3DU9M/sUgJqmphfjhJaa9H1v9/Ztw/1PPn0QtWoNs7Oz' + +'WBltATiOixMnzuCS/bvtgTBwCQXg6s5fNLdTmnkuSAKww0WrS7q6St7E5Ax6egbWWHpow3EcnDs/' + +'EX8v6fDw4J4XDhzxASwAEOvSAF2Wu2j3jssAQqVSQ6+ULTQ/W3+pQy/dYHauEi9Sbhsd2gGgqB2x' + +'BEDN+gCpy3rCCGjP5OQ0FHO0idGeDTexHRkoxvjEJHZsGxkE0APgnO5TYc6x1hKAIKJtu3dtGzp1' + +'+hyKxY5oB6wpDWibIRenTp3D6OhQl5RyMAiC5w0TRCtpACW+rM8aGR7cPzTYX3ziqQPw/dzmm4gt' + +'YOaYGZ7n4cTJs3jVK67xw++l23723AVtURLhaFIDEuGnG47+S33fo8mpWZQ6XUxPT6ONtfeD7dgR' + +'j6NQyNHQ0MCOUAA2ANmMBpAhhGJo//eFy6lgFsjn823zsw6cnhyHUhw74kcfe8ozfMCKAkjOAYb2' + +'7tk5cubsBTiuF3v35h1w2xwpRmgxZrBj+/AIgA4AY7pfsZYGyIi6uzv3hHOArocefQbMwNTUVFsD' + +'mjdDIUmcDgfv6OhwH4CIjie0gJfVAF3J2bVjWzgB65TnL0ygs7NrnROwthZUqzWcPHUOV1y2txiu' + +'JA/Pzc0/spYJEob5ye/Zs/NiZka5XEVPr4821gfP9xAN3nA9yB4c6Nt+cG5eLvPGDCdNUKNS7769' + +'u3ZGX1NfqwfR+s//C/PDnH5TRq+kxun8fBkdxQJGhgd2Hjx01BBAwgQl7L/I5fyd4RJE3+TUdNjI' + +'PKSc0AJg/T+JxNNnK5Uly3VuterJOpzh3hmts5DWKExy3/j6l2J4eAAjI4PbjG9UF6YQrMaBWRCu' + +'fu4fHRn0Bvp7USzkUS4vmD9as+IP3cSHWL5eXGTUizk6v/IDubodM7+++qs+ENbsg2RxLlE/5pr1' + +'Ew8H25aFnp6u2CFvGx0e0JHQGdMEJTWgkTo7d4xe3NfXg1KpiLe86TWg9ONtc3eKuVX3yatei5m1' + +'AIa6pRT9QaCeb2YporBzx7Zd0chnRkgKbaSLsMLZcK6/rzecU53n5TSAEkw/HPkFy86BpJtq3LRB' + +'IK6jq7NDhPOqPi0A0+cuuxq6EMas5bGJaVQWFWgTbrqVTdEX9f4ZvmfB9/3Il5bW2hNmnZbDB4om' + +'Lpw/h7n5RYCa+3E0ToY4Jp9XiGSYk/WMvHmlxDEn7yN5ffN4mTzrM808G+0leJqVbG81njbfjFJH' + +'Hr4no4lZ3fjRT06GoWxQ+eFHn7rTz/1Tv5QSrBQpZrAmfVMaQJyNOXHOPESjztJfs54uxFJWl5q1' + +'zYuZRzD+RzAPEufoJFln2TyMv8axwUheJPGRVSMFEHe4ZckqMy8cOXLin5f7xVUyyPypwhKAHp13' + +'IjJCVW4iHGAz30Q5mmx3I+dwyvbWE36x0ck1AFW9Gb+g06qmWkMQVuLEQEtuVldyjR/vFJqyjxNb' + +'6+mTA6DV96HMvkx0ej2pAZZxoBL5QJ8oDKIW3jxnfA5twj1xUhPMjjd9wGpOOEgIgUzaxFG8RZ4F' + +'Tgxos9N1atajtd+S1LytA26p8NKbQE7/0+BtpNakNtpoo4022vgf7lRPtKCE39oAAAAASUVORK5C' + +'YII=' +); + +lib.resource.add('hterm/concat/date', 'text/plain', +'Wed, 10 Oct 2018 16:00:59 +0000' +); + +lib.resource.add('hterm/changelog/version', 'text/plain', +'2018-08-29' +); + +lib.resource.add('hterm/changelog/date', 'text/plain', +'1.81' +); + +lib.resource.add('hterm/git/HEAD', 'text/plain', +'991c7a29a9f287fbb760176cde72612cfa144d42' +); + +// This file was generated by libdot/bin/concat.sh. +// It has been marked read-only for your safety. Rather than +// edit it directly, please modify one of these source files. +// +// hterm/js/hterm.js +// hterm/js/hterm_accessibility_reader.js +// hterm/js/hterm_contextmenu.js +// hterm/js/hterm_frame.js +// hterm/js/hterm_keyboard.js +// hterm/js/hterm_keyboard_bindings.js +// hterm/js/hterm_keyboard_keymap.js +// hterm/js/hterm_keyboard_keypattern.js +// hterm/js/hterm_options.js +// hterm/js/hterm_parser.js +// hterm/js/hterm_parser_identifiers.js +// hterm/js/hterm_preference_manager.js +// hterm/js/hterm_pubsub.js +// hterm/js/hterm_screen.js +// hterm/js/hterm_scrollport.js +// hterm/js/hterm_terminal.js +// hterm/js/hterm_terminal_io.js +// hterm/js/hterm_text_attributes.js +// hterm/js/hterm_vt.js +// hterm/js/hterm_vt_character_map.js +// hterm/audio/bell.ogg +// hterm/images/icon-96.png + +'use strict'; + +// SOURCE FILE: hterm/js/hterm.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('lib.Storage'); + +/** + * @fileoverview Declares the hterm.* namespace and some basic shared utilities + * that are too small to deserve dedicated files. + */ +var hterm = {}; + +/** + * The type of window hosting hterm. + * + * This is set as part of hterm.init(). The value is invalid until + * initialization completes. + */ +hterm.windowType = null; + +/** + * The OS we're running under. + * + * Used when setting up OS-specific behaviors. + * + * This is set as part of hterm.init(). The value is invalid until + * initialization completes. + */ +hterm.os = null; + +/** + * Warning message to display in the terminal when browser zoom is enabled. + * + * You can replace it with your own localized message. + */ +hterm.zoomWarningMessage = 'ZOOM != 100%'; + +/** + * Brief overlay message displayed when text is copied to the clipboard. + * + * By default it is the unicode BLACK SCISSORS character, but you can + * replace it with your own localized message. + * + * This is only displayed when the 'enable-clipboard-notice' preference + * is enabled. + */ +hterm.notifyCopyMessage = '\u2702'; + + +/** + * Text shown in a desktop notification for the terminal + * bell. \u226a is a unicode EIGHTH NOTE, %(title) will + * be replaced by the terminal title. + */ +hterm.desktopNotificationTitle = '\u266A %(title) \u266A'; + +/** + * List of known hterm test suites. + * + * A test harness should ensure that they all exist before running. + */ +hterm.testDeps = ['hterm.AccessibilityReader.Tests', 'hterm.ScrollPort.Tests', + 'hterm.Screen.Tests', 'hterm.Terminal.Tests', + 'hterm.VT.Tests', 'hterm.VT.CannedTests']; + +/** + * The hterm init function, registered with lib.registerInit(). + * + * This is called during lib.init(). + * + * @param {function} onInit The function lib.init() wants us to invoke when + * initialization is complete. + */ +lib.registerInit('hterm', function(onInit) { + function initOs(os) { + hterm.os = os; + + onInit(); + } + + function initMessageManager() { + lib.i18n.getAcceptLanguages((languages) => { + if (!hterm.messageManager) + hterm.messageManager = new lib.MessageManager(languages); + + // If OS detection fails, then we'll still set the value to something. + // The OS logic in hterm tends to be best effort anyways. + lib.f.getOs().then(initOs).catch(initOs); + }); + } + + function onWindow(window) { + hterm.windowType = window.type; + initMessageManager(); + } + + function onTab(tab) { + if (tab && window.chrome) { + chrome.windows.get(tab.windowId, null, onWindow); + } else { + // TODO(rginda): This is where we end up for a v1 app's background page. + // Maybe windowType = 'none' would be more appropriate, or something. + hterm.windowType = 'normal'; + initMessageManager(); + } + } + + if (!hterm.defaultStorage) { + if (window.chrome && chrome.storage && chrome.storage.sync) { + hterm.defaultStorage = new lib.Storage.Chrome(chrome.storage.sync); + } else { + hterm.defaultStorage = new lib.Storage.Local(); + } + } + + // The chrome.tabs API is not supported in packaged apps, and detecting if + // you're a packaged app is a little awkward. + var isPackagedApp = false; + if (window.chrome && chrome.runtime && chrome.runtime.getManifest) { + var manifest = chrome.runtime.getManifest(); + isPackagedApp = manifest.app && manifest.app.background; + } + + if (isPackagedApp) { + // Packaged apps are never displayed in browser tabs. + setTimeout(onWindow.bind(null, {type: 'popup'}), 0); + } else { + if (window.chrome && chrome.tabs) { + // The getCurrent method gets the tab that is "currently running", not the + // topmost or focused tab. + chrome.tabs.getCurrent(onTab); + } else { + setTimeout(onWindow.bind(null, {type: 'normal'}), 0); + } + } +}); + +/** + * Return decimal { width, height } for a given dom node. + */ +hterm.getClientSize = function(dom) { + return dom.getBoundingClientRect(); +}; + +/** + * Return decimal width for a given dom node. + */ +hterm.getClientWidth = function(dom) { + return dom.getBoundingClientRect().width; +}; + +/** + * Return decimal height for a given dom node. + */ +hterm.getClientHeight = function(dom) { + return dom.getBoundingClientRect().height; +}; + +/** + * Copy the current selection to the system clipboard. + * + * @param {HTMLDocument} The document with the selection to copy. + */ +hterm.copySelectionToClipboard = function(document) { + try { + document.execCommand('copy'); + } catch (firefoxException) { + // Ignore this. FF throws an exception if there was an error, even though + // the spec says just return false. + } +}; + +/** + * Paste the system clipboard into the element with focus. + * + * Note: In Chrome/Firefox app/extension environments, you'll need the + * "clipboardRead" permission. In other environments, this might always + * fail as the browser frequently blocks access for security reasons. + * + * @param {HTMLDocument} The document to paste into. + * @return {boolean} True if the paste succeeded. + */ +hterm.pasteFromClipboard = function(document) { + try { + return document.execCommand('paste'); + } catch (firefoxException) { + // Ignore this. FF 40 and older would incorrectly throw an exception if + // there was an error instead of returning false. + return false; + } +}; + +/** + * Return a formatted message in the current locale. + * + * @param {string} name The name of the message to return. + * @param {Array=} args The message arguments, if required. + * @param {string=} string The default message text. + * @return {string} The localized message. + */ +hterm.msg = function(name, args = [], string) { + return hterm.messageManager.get('HTERM_' + name, args, string); +}; + +/** + * Create a new notification. + * + * @param {Object} params Various parameters for the notification. + * @param {string} params.title The title (defaults to the window's title). + * @param {string} params.body The message body (main text). + */ +hterm.notify = function(params) { + var def = (curr, fallback) => curr !== undefined ? curr : fallback; + if (params === undefined || params === null) + params = {}; + + // Merge the user's choices with the default settings. We don't take it + // directly in case it was stuffed with excess junk. + var options = { + 'body': params.body, + 'icon': def(params.icon, lib.resource.getDataUrl('hterm/images/icon-96')), + }; + + var title = def(params.title, window.document.title); + if (!title) + title = 'hterm'; + title = lib.f.replaceVars(hterm.desktopNotificationTitle, {'title': title}); + + var n = new Notification(title, options); + n.onclick = function() { + window.focus(); + this.close(); + }; + return n; +}; + +/** + * Launches url in a new tab. + * + * @param {string} url URL to launch in a new tab. + */ +hterm.openUrl = function(url) { + if (window.chrome && chrome.browser && chrome.browser.openTab) { + // For Chrome v2 apps, we need to use this API to properly open windows. + chrome.browser.openTab({'url': url}); + } else { + const win = window.open(url, '_blank'); + win.focus(); + } +}; + +/** + * Constructor for a hterm.Size record. + * + * Instances of this class have public read/write members for width and height. + * + * @param {integer} width The width of this record. + * @param {integer} height The height of this record. + */ +hterm.Size = function(width, height) { + this.width = width; + this.height = height; +}; + +/** + * Adjust the width and height of this record. + * + * @param {integer} width The new width of this record. + * @param {integer} height The new height of this record. + */ +hterm.Size.prototype.resize = function(width, height) { + this.width = width; + this.height = height; +}; + +/** + * Return a copy of this record. + * + * @return {hterm.Size} A new hterm.Size instance with the same width and + * height. + */ +hterm.Size.prototype.clone = function() { + return new hterm.Size(this.width, this.height); +}; + +/** + * Set the height and width of this instance based on another hterm.Size. + * + * @param {hterm.Size} that The object to copy from. + */ +hterm.Size.prototype.setTo = function(that) { + this.width = that.width; + this.height = that.height; +}; + +/** + * Test if another hterm.Size instance is equal to this one. + * + * @param {hterm.Size} that The other hterm.Size instance. + * @return {boolean} True if both instances have the same width/height, false + * otherwise. + */ +hterm.Size.prototype.equals = function(that) { + return this.width == that.width && this.height == that.height; +}; + +/** + * Return a string representation of this instance. + * + * @return {string} A string that identifies the width and height of this + * instance. + */ +hterm.Size.prototype.toString = function() { + return '[hterm.Size: ' + this.width + ', ' + this.height + ']'; +}; + +/** + * Constructor for a hterm.RowCol record. + * + * Instances of this class have public read/write members for row and column. + * + * This class includes an 'overflow' bit which is use to indicate that an + * attempt has been made to move the cursor column passed the end of the + * screen. When this happens we leave the cursor column set to the last column + * of the screen but set the overflow bit. In this state cursor movement + * happens normally, but any attempt to print new characters causes a cr/lf + * first. + * + * @param {integer} row The row of this record. + * @param {integer} column The column of this record. + * @param {boolean} opt_overflow Optional boolean indicating that the RowCol + * has overflowed. + */ +hterm.RowCol = function(row, column, opt_overflow) { + this.row = row; + this.column = column; + this.overflow = !!opt_overflow; +}; + +/** + * Adjust the row and column of this record. + * + * @param {integer} row The new row of this record. + * @param {integer} column The new column of this record. + * @param {boolean} opt_overflow Optional boolean indicating that the RowCol + * has overflowed. + */ +hterm.RowCol.prototype.move = function(row, column, opt_overflow) { + this.row = row; + this.column = column; + this.overflow = !!opt_overflow; +}; + +/** + * Return a copy of this record. + * + * @return {hterm.RowCol} A new hterm.RowCol instance with the same row and + * column. + */ +hterm.RowCol.prototype.clone = function() { + return new hterm.RowCol(this.row, this.column, this.overflow); +}; + +/** + * Set the row and column of this instance based on another hterm.RowCol. + * + * @param {hterm.RowCol} that The object to copy from. + */ +hterm.RowCol.prototype.setTo = function(that) { + this.row = that.row; + this.column = that.column; + this.overflow = that.overflow; +}; + +/** + * Test if another hterm.RowCol instance is equal to this one. + * + * @param {hterm.RowCol} that The other hterm.RowCol instance. + * @return {boolean} True if both instances have the same row/column, false + * otherwise. + */ +hterm.RowCol.prototype.equals = function(that) { + return (this.row == that.row && this.column == that.column && + this.overflow == that.overflow); +}; + +/** + * Return a string representation of this instance. + * + * @return {string} A string that identifies the row and column of this + * instance. + */ +hterm.RowCol.prototype.toString = function() { + return ('[hterm.RowCol: ' + this.row + ', ' + this.column + ', ' + + this.overflow + ']'); +}; +// SOURCE FILE: hterm/js/hterm_accessibility_reader.js +// Copyright 2018 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * AccessibilityReader responsible for rendering command output for AT. + * + * Renders command output for Assistive Technology using a live region. We don't + * use the visible rows of the terminal for rendering command output to the + * screen reader because the rendered content may be different from what we want + * read out by a screen reader. For example, we may not actually render every + * row of a large piece of output to the screen as it wouldn't be performant. + * But we want the screen reader to read it all out in order. + * + * @param {HTMLDivElement} div The div element where the live region should be + * added. + */ +hterm.AccessibilityReader = function(div) { + this.document_ = div.ownerDocument; + + // The live region element to add text to. + const liveRegion = this.document_.createElement('div'); + liveRegion.id = 'hterm:accessibility-live-region'; + liveRegion.style.cssText = `position: absolute; + width: 0; height: 0; + overflow: hidden; + left: 0; top: 0;`; + div.appendChild(liveRegion); + + // Whether command output should be rendered for Assistive Technology. + // This isn't always enabled because it has an impact on performance. + this.accessibilityEnabled = false; + + // This live element is used for command output. + this.liveElement_ = this.document_.createElement('p'); + this.liveElement_.setAttribute('aria-live', 'polite'); + this.liveElement_.setAttribute('aria-label', ''); + liveRegion.appendChild(this.liveElement_); + + // This live element is used for speaking out the current screen when + // navigating through the scrollback buffer. It will interrupt existing + // announcements. + this.assertiveLiveElement_ = this.document_.createElement('p'); + this.assertiveLiveElement_.setAttribute('aria-live', 'assertive'); + this.assertiveLiveElement_.setAttribute('aria-label', ''); + liveRegion.appendChild(this.assertiveLiveElement_); + + // A queue of updates to announce. + this.queue_ = []; + + // A timer which tracks when next to add items to the live region. null when + // not running. This is used to combine updates that occur in a small window, + // as well as to avoid too much output being added to the live region in one + // go which can cause the renderer to hang. + this.nextReadTimer_ = null; + + // This is set to true if the cursor is about to update position on the + // screen. i.e. beforeCursorChange has been called but not afterCursorChange. + this.cursorIsChanging_ = false; + + // This tracks changes that would be added to queue_ while the cursor is + // changing. This is done so that we can decide to discard these changes if + // we announce something as a result of the cursor change. + this.cursorChangeQueue_ = []; + + // The string of text on the row that the cursor was last on. Only valid while + // cursorIsChanging_ is true. + this.lastCursorRowString_ = null; + + // The row that the cursor was last on. Only valid while cursorIsChanging_ is + // true. + this.lastCursorRow_ = null; + + // The column that the cursor was last on. Only valid while cursorIsChanging_ + // is true. + this.lastCursorColumn_ = null; + + // True if a keypress has been performed since the last cursor change. + this.hasUserGesture = false; +}; + +/** + * Delay in ms to use for merging strings to output. + * + * We merge strings together to avoid hanging the terminal and to ensure that + * aria updates make it to the screen reader. We want this to be short so + * there's not a big delay between typing/executing commands and hearing output. + * + * @constant + * @type {integer} + */ +hterm.AccessibilityReader.DELAY = 50; + +/** + * Enable accessibility-friendly features that have a performance impact. + * + * @param {boolean} enabled Whether to enable accessibility-friendly features. + */ +hterm.AccessibilityReader.prototype.setAccessibilityEnabled = + function(enabled) { + if (!enabled) { + this.clear(); + } + + this.accessibilityEnabled = enabled; +}; + +/** + * Decorate the document where the terminal resides. This is needed + * for listening to keystrokes on the screen. + * + * @param {HTMLDocument} doc The document where the resides. + */ +hterm.AccessibilityReader.prototype.decorate = function(doc) { + const handlers = ['keydown', 'keypress', 'keyup', 'textInput']; + handlers.forEach((handler) => { + doc.addEventListener(handler, () => { this.hasUserGesture = true; }); + }); +}; + +/** + * This should be called before the cursor on the screen is about to get + * updated. This allows cursor changes to be tracked and related notifications + * to be announced. + * + * @param {string} cursorRowString The text in the row that the cursor is + * currently on. + * @param {integer} cursorRow The index of the row that the cursor is currently + * on, including rows in the scrollback buffer. + * @param {integer} cursorColumn The index of the column that the cursor is + * currently on. + */ +hterm.AccessibilityReader.prototype.beforeCursorChange = + function(cursorRowString, cursorRow, cursorColumn) { + // If accessibility is enabled we don't announce selection changes as these + // can have a performance impact. + if (!this.accessibilityEnabled) { + return; + } + + // If there is no user gesture that can be tied to the cursor change, we + // don't want to announce anything. + if (!this.hasUserGesture || this.cursorIsChanging_) { + return; + } + + this.cursorIsChanging_ = true; + this.lastCursorRowString_ = cursorRowString; + this.lastCursorRow_ = cursorRow; + this.lastCursorColumn_ = cursorColumn; +}; + +/** + * This should be called after the cursor on the screen has been updated. Note + * that several updates to the cursor may have happened between + * beforeCursorChange and afterCursorChange. + * + * This allows cursor changes to be tracked and related notifications to be + * announced. + * + * @param {string} cursorRowString The text in the row that the cursor is + * currently on. + * @param {integer} cursorRow The index of the row that the cursor is currently + * on, including rows in the scrollback buffer. + * @param {integer} cursorColumn The index of the column that the cursor is + * currently on. + */ +hterm.AccessibilityReader.prototype.afterCursorChange = + function(cursorRowString, cursorRow, cursorColumn) { + // This can happen if clear() is called midway through a cursor change. + if (!this.cursorIsChanging_) { + return; + } + this.cursorIsChanging_ = false; + + if (!this.announceAction_(cursorRowString, cursorRow, cursorColumn)) { + // If we don't announce a special action, we re-queue all the output that + // was queued during the selection change. + for (let i = 0; i < this.cursorChangeQueue_.length; ++i) { + this.announce(this.cursorChangeQueue_[i]); + } + } + + this.cursorChangeQueue_ = []; + this.lastCursorRowString_ = null; + this.lastCursorRow_ = null; + this.lastCursorColumn_ = null; + this.hasUserGesture = false; +}; + +/** + * Announce the command output. + * + * @param {string} str The string to announce using a live region. + */ +hterm.AccessibilityReader.prototype.announce = function(str) { + if (!this.accessibilityEnabled) { + return; + } + + // If the cursor is in the middle of changing, we queue up the output + // separately as we may not want it to be announced if it's part of a cursor + // change announcement. + if (this.cursorIsChanging_) { + this.cursorChangeQueue_.push(str); + return; + } + + // Don't append newlines to the queue if the queue is empty. It won't have any + // impact. + if (str == '\n' && this.queue_.length > 0) { + this.queue_.push(''); + // We don't need to trigger an announcement on newlines because they won't + // change the existing content that's output. + return; + } + + if (this.queue_.length == 0) { + this.queue_.push(str); + } else { + // We put a space between strings that appear on the same line. + // TODO(raymes): We should check the location on the row and not add a space + // if the strings are joined together. + let padding = ''; + if (this.queue_[this.queue_.length - 1].length != 0) { + padding = ' '; + } + this.queue_[this.queue_.length - 1] += padding + str; + } + + // If we've already scheduled text being added to the live region, wait for it + // to happen. + if (this.nextReadTimer_) { + return; + } + + // If there's only one item in the queue, we may get other text being added + // very soon after. In that case, wait a small delay so we can merge the + // related strings. + if (this.queue_.length == 1) { + this.nextReadTimer_ = setTimeout(this.addToLiveRegion_.bind(this), + hterm.AccessibilityReader.DELAY); + } else { + throw new Error( + 'Expected only one item in queue_ or nextReadTimer_ to be running.'); + } +}; + +/** + * Voice an announcement that will interrupt other announcements. + * + * @param {string} str The string to announce using a live region. + */ +hterm.AccessibilityReader.prototype.assertiveAnnounce = function(str) { + if (this.hasUserGesture && str == ' ') { + str = hterm.msg('SPACE_CHARACTER', [], 'Space'); + } + + // If the same string is announced twice, an attribute change won't be + // registered and the screen reader won't know that the string has changed. + // So we slightly change the string to ensure that the attribute change gets + // registered. + str = str.trim(); + if (str == this.assertiveLiveElement_.getAttribute('aria-label')) { + str = '\n' + str; + } + + this.clear(); + this.assertiveLiveElement_.setAttribute('aria-label', str); +}; + +/** + * Add a newline to the text that will be announced to the live region. + */ +hterm.AccessibilityReader.prototype.newLine = function() { + this.announce('\n'); +}; + +/** + * Clear the live region and any in-flight announcements. + */ +hterm.AccessibilityReader.prototype.clear = function() { + this.liveElement_.setAttribute('aria-label', ''); + this.assertiveLiveElement_.setAttribute('aria-label', ''); + clearTimeout(this.nextReadTimer_); + this.nextReadTimer_ = null; + this.queue_ = []; + + this.cursorIsChanging_ = false; + this.cursorChangeQueue_ = []; + this.lastCursorRowString_ = null; + this.lastCursorRow_ = null; + this.lastCursorColumn_ = null; + this.hasUserGesture = false; +}; + +/** + * This will announce an action that is related to a cursor change, for example + * when the user deletes a character we want the character deleted to be + * announced. Similarly, when the user moves the cursor along the line, we want + * the characters selected to be announced. + * + * Note that this function is a heuristic. Because of the nature of terminal + * emulators, we can't distinguish input and output, which means we don't really + * know what output is the result of a keypress and what isn't. Also in some + * terminal applications certain announcements may make sense whereas others may + * not. This function should try to account for the most common cases. + * + * @param {string} cursorRowString The text in the row that the cursor is + * currently on. + * @param {integer} cursorRow The index of the row that the cursor is currently + * on, including rows in the scrollback buffer. + * @param {integer} cursorColumn The index of the column that the cursor is + * currently on. + */ +hterm.AccessibilityReader.prototype.announceAction_ = + function(cursorRowString, cursorRow, cursorColumn) { + // If the cursor changes rows, we don't announce anything at present. + if (this.lastCursorRow_ != cursorRow) { + return false; + } + + // The case when the row of text hasn't changed at all. + if (this.lastCursorRowString_ == cursorRowString) { + // Moving the cursor along the line. We check that no significant changes + // have been queued. If they have, it may not just be a cursor movement and + // it may be better to read those out. + if (this.lastCursorColumn_ != cursorColumn && + this.cursorChangeQueue_.join('').trim() == '') { + // Announce the text between the old cursor position and the new one. + const start = Math.min(this.lastCursorColumn_, cursorColumn); + const len = Math.abs(cursorColumn - this.lastCursorColumn_); + this.assertiveAnnounce( + lib.wc.substr(this.lastCursorRowString_, start, len)); + return true; + } + return false; + } + + // The case when the row of text has changed. + if (this.lastCursorRowString_ != cursorRowString) { + // Spacebar. We manually announce this character since the screen reader may + // not announce the whitespace in a live region. + if (this.lastCursorColumn_ + 1 == cursorColumn) { + if (lib.wc.substr(cursorRowString, cursorColumn - 1, 1) == ' ' && + this.cursorChangeQueue_.length > 0 && + this.cursorChangeQueue_[0] == ' ') { + this.assertiveAnnounce(' '); + return true; + } + } + + // Backspace and deletion. + // The position of the characters deleted is right after the current + // position of the cursor in the case of backspace and delete. + const cursorDeleted = cursorColumn; + // Check that the current row string is shorter than the previous. Also + // check that the start of the strings (up to the cursor) match. + if (lib.wc.strWidth(cursorRowString) <= + lib.wc.strWidth(this.lastCursorRowString_) && + lib.wc.substr(this.lastCursorRowString_, 0, cursorDeleted) == + lib.wc.substr(cursorRowString, 0, cursorDeleted)) { + // Find the length of the current row string ignoring space characters. + // These may be inserted at the end of the string when deleting characters + // so they should be ignored. + let lengthOfCurrentRow = lib.wc.strWidth(cursorRowString); + for (; lengthOfCurrentRow > 0; --lengthOfCurrentRow) { + if (lengthOfCurrentRow == cursorDeleted || + lib.wc.substr(cursorRowString, lengthOfCurrentRow - 1, 1) != ' ') { + break; + } + } + + const numCharsDeleted = + lib.wc.strWidth(this.lastCursorRowString_) - lengthOfCurrentRow; + + // Check that the end of the strings match. + const lengthOfEndOfString = lengthOfCurrentRow - cursorDeleted; + const endOfLastRowString = lib.wc.substr( + this.lastCursorRowString_, cursorDeleted + numCharsDeleted, + lengthOfEndOfString); + const endOfCurrentRowString = + lib.wc.substr(cursorRowString, cursorDeleted, lengthOfEndOfString); + if (endOfLastRowString == endOfCurrentRowString) { + const deleted = lib.wc.substr( + this.lastCursorRowString_, cursorDeleted, numCharsDeleted); + if (deleted != '') { + this.assertiveAnnounce(deleted); + return true; + } + } + } + return false; + } + + return false; +}; + +/** + * Add text from queue_ to the live region. + * + */ +hterm.AccessibilityReader.prototype.addToLiveRegion_ = function() { + this.nextReadTimer_ = null; + + let str = this.queue_.join('\n').trim(); + + // If the same string is announced twice, an attribute change won't be + // registered and the screen reader won't know that the string has changed. + // So we slightly change the string to ensure that the attribute change gets + // registered. + if (str == this.liveElement_.getAttribute('aria-label')) { + str = '\n' + str; + } + + this.liveElement_.setAttribute('aria-label', str); + this.queue_ = []; +}; +// SOURCE FILE: hterm/js/hterm_contextmenu.js +// Copyright 2018 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview Context menu handling. + */ + +/** + * Manage the context menu usually shown when right clicking. + */ +hterm.ContextMenu = function() { + // The document that contains this context menu. + this.document_ = null; + // The generated context menu (i.e. HTML elements). + this.element_ = null; + // The structured menu (i.e. JS objects). + this.menu_ = []; +}; + +/** + * Constant to add a separator to the context menu. + */ +hterm.ContextMenu.SEPARATOR = {}; + +/** + * Bind context menu to a specific document element. + * + * @param {HTMLDocument} document The document to use when creating elements. + */ +hterm.ContextMenu.prototype.setDocument = function(document) { + if (this.element_) { + this.element_.remove(); + this.element_ = null; + } + this.document_ = document; + this.regenerate_(); + this.document_.body.appendChild(this.element_); +}; + +/** + * Regenerate the HTML elements based on internal menu state. + */ +hterm.ContextMenu.prototype.regenerate_ = function() { + if (!this.element_) { + this.element_ = this.document_.createElement('menu'); + this.element_.id = 'hterm:context-menu'; + this.element_.style.cssText = ` + display: none; + border: solid 1px; + position: absolute; + `; + } else { + this.hide(); + } + + // Clear out existing menu entries. + while (this.element_.firstChild) { + this.element_.removeChild(this.element_.firstChild); + } + + this.menu_.forEach(([name, action]) => { + const menuitem = this.document_.createElement('menuitem'); + if (name === hterm.ContextMenu.SEPARATOR) { + menuitem.innerHTML = '
'; + menuitem.className = 'separator'; + } else { + menuitem.innerText = name; + menuitem.addEventListener('mousedown', function(e) { + e.preventDefault(); + action(e); + }); + } + this.element_.appendChild(menuitem); + }); +}; + +/** + * Set all the entries in the context menu. + * + * This is an array of arrays. The first element in the array is the string to + * display while the second element is the function to call. + * + * The first element may also be the SEPARATOR constant to add a separator. + * + * This resets all existing menu entries. + * + * @param {Array>} items The menu entries. + */ +hterm.ContextMenu.prototype.setItems = function(items) { + this.menu_ = items; + this.regenerate_(); +}; + +/** + * Show the context menu. + * + * The event is used to determine where to show the menu. + * + * If no menu entries are defined, then nothing will be shown. + * + * @param {Event} e The event triggering this display. + * @param {hterm.Terminal=} terminal The terminal object to get style info from. + */ +hterm.ContextMenu.prototype.show = function(e, terminal) { + // If there are no menu entries, then don't try to show anything. + if (this.menu_.length == 0) { + return; + } + + // If we have the terminal, sync the style preferences over. + if (terminal) { + this.element_.style.backgroundColor = terminal.getBackgroundColor(); + this.element_.style.color = terminal.getForegroundColor(); + this.element_.style.fontSize = terminal.getFontSize(); + this.element_.style.fontFamily = terminal.getFontFamily(); + } + + this.element_.style.top = `${e.clientY}px`; + this.element_.style.left = `${e.clientX}px`; + const docSize = hterm.getClientSize(this.document_.body); + + this.element_.style.display = 'block'; + + // We can't calculate sizes until after it's displayed. + const eleSize = hterm.getClientSize(this.element_); + // Make sure the menu isn't clipped outside of the current element. + const minY = Math.max(0, docSize.height - eleSize.height); + const minX = Math.max(0, docSize.width - eleSize.width); + if (minY < e.clientY) { + this.element_.style.top = `${minY}px`; + } + if (minX < e.clientX) { + this.element_.style.left = `${minX}px`; + } +}; + +/** + * Hide the context menu. + */ +hterm.ContextMenu.prototype.hide = function() { + if (!this.element_) { + return; + } + + this.element_.style.display = 'none'; +}; +// SOURCE FILE: hterm/js/hterm_frame.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('lib.f'); + +/** + * First draft of the interface between the terminal and a third party dialog. + * + * This is rough. It's just the terminal->dialog layer. To complete things + * we'll also need a command->terminal layer. That will have to facilitate + * command->terminal->dialog or direct command->dialog communication. + * + * I imagine this class will change significantly when that happens. + */ + +/** + * Construct a new frame for the given terminal. + * + * @param terminal {hterm.Terminal} The parent terminal object. + * @param url {String} The url to load in the frame. + * @param opt_options {Object} Optional options for the frame. Not implemented. + */ +hterm.Frame = function(terminal, url, opt_options) { + this.terminal_ = terminal; + this.div_ = terminal.div_; + this.url = url; + this.options = opt_options || {}; + this.iframe_ = null; + this.container_ = null; + this.messageChannel_ = null; +}; + +/** + * Handle messages from the iframe. + */ +hterm.Frame.prototype.onMessage_ = function(e) { + switch (e.data.name) { + case 'ipc-init-ok': + // We get this response after we send them ipc-init and they finish. + this.sendTerminalInfo_(); + return; + case 'terminal-info-ok': + // We get this response after we send them terminal-info and they finish. + // Show the finished frame, and then rebind our message handler to the + // callback below. + this.container_.style.display = 'flex'; + this.postMessage('visible'); + this.messageChannel_.port1.onmessage = this.onMessage.bind(this); + this.onLoad(); + return; + default: + console.log('Unknown message from frame:', e.data); + return; + } +}; + +/** + * Clients could override this, I guess. + * + * It doesn't support multiple listeners, but I'm not sure that would make sense + * here. It's probably better to speak directly to our parents. + */ +hterm.Frame.prototype.onMessage = function() {}; + +/** + * Handle iframe onLoad event. + */ +hterm.Frame.prototype.onLoad_ = function() { + this.messageChannel_ = new MessageChannel(); + this.messageChannel_.port1.onmessage = this.onMessage_.bind(this); + this.messageChannel_.port1.start(); + this.iframe_.contentWindow.postMessage( + {name: 'ipc-init', argv: [{messagePort: this.messageChannel_.port2}]}, + this.url, [this.messageChannel_.port2]); +}; + +/** + * Clients may override this. + */ +hterm.Frame.prototype.onLoad = function() {}; + +/** + * Sends the terminal-info message to the iframe. + */ +hterm.Frame.prototype.sendTerminalInfo_ = function() { + lib.i18n.getAcceptLanguages(function(languages) { + this.postMessage('terminal-info', [{ + acceptLanguages: languages, + foregroundColor: this.terminal_.getForegroundColor(), + backgroundColor: this.terminal_.getBackgroundColor(), + cursorColor: this.terminal_.getCursorColor(), + fontSize: this.terminal_.getFontSize(), + fontFamily: this.terminal_.getFontFamily(), + baseURL: lib.f.getURL('/') + }] + ); + }.bind(this)); +}; + +/** + * User clicked the close button on the frame decoration. + */ +hterm.Frame.prototype.onCloseClicked_ = function() { + this.close(); +}; + +/** + * Close this frame. + */ +hterm.Frame.prototype.close = function() { + if (!this.container_ || !this.container_.parentNode) + return; + + this.container_.parentNode.removeChild(this.container_); + this.onClose(); +}; + + +/** + * Clients may override this. + */ +hterm.Frame.prototype.onClose = function() {}; + +/** + * Send a message to the iframe. + */ +hterm.Frame.prototype.postMessage = function(name, argv) { + if (!this.messageChannel_) + throw new Error('Message channel is not set up.'); + + this.messageChannel_.port1.postMessage({name: name, argv: argv}); +}; + +/** + * Show the UI for this frame. + * + * The iframe src is not loaded until this method is called. + */ +hterm.Frame.prototype.show = function() { + var self = this; + + function opt(name, defaultValue) { + if (name in self.options) + return self.options[name]; + + return defaultValue; + } + + var self = this; + + if (this.container_ && this.container_.parentNode) { + console.error('Frame already visible'); + return; + } + + var headerHeight = '16px'; + + var divSize = hterm.getClientSize(this.div_); + + var width = opt('width', 640); + var height = opt('height', 480); + var left = (divSize.width - width) / 2; + var top = (divSize.height - height) / 2; + + var document = this.terminal_.document_; + + var container = this.container_ = document.createElement('div'); + container.style.cssText = ( + 'position: absolute;' + + 'display: none;' + + 'flex-direction: column;' + + 'top: 10%;' + + 'left: 4%;' + + 'width: 90%;' + + 'height: 80%;' + + 'min-height: 20%;' + + 'max-height: 80%;' + + 'box-shadow: 0 0 2px ' + this.terminal_.getForegroundColor() + ';' + + 'border: 2px ' + this.terminal_.getForegroundColor() + ' solid;'); + + if (false) { + // No use for the close button, so no use for the window header either. + var header = document.createElement('div'); + header.style.cssText = ( + 'display: flex;' + + 'justify-content: flex-end;' + + 'height: ' + headerHeight + ';' + + 'background-color: ' + this.terminal_.getForegroundColor() + ';' + + 'color: ' + this.terminal_.getBackgroundColor() + ';' + + 'font-size: 16px;' + + 'font-family: ' + this.terminal_.getFontFamily()); + container.appendChild(header); + + var button = document.createElement('div'); + button.setAttribute('role', 'button'); + button.style.cssText = ( + 'margin-top: -3px;' + + 'margin-right: 3px;' + + 'cursor: pointer;'); + button.textContent = '\u2a2f'; + button.addEventListener('click', this.onCloseClicked_.bind(this)); + header.appendChild(button); + } + + var iframe = this.iframe_ = document.createElement('iframe'); + iframe.onload = this.onLoad_.bind(this); + iframe.style.cssText = ( + 'display: flex;' + + 'flex: 1;' + + 'width: 100%'); + iframe.setAttribute('src', this.url); + iframe.setAttribute('seamless', true); + container.appendChild(iframe); + + this.div_.appendChild(container); +}; +// SOURCE FILE: hterm/js/hterm_keyboard.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('hterm.Keyboard.KeyMap'); + +/** + * Keyboard handler. + * + * Consumes onKey* events and invokes onVTKeystroke on the associated + * hterm.Terminal object. + * + * See also: [XTERM] as referenced in vt.js. + * + * @param {hterm.Terminal} The Terminal object associated with this keyboard. + */ +hterm.Keyboard = function(terminal) { + // The parent vt interpreter. + this.terminal = terminal; + + // The element we're currently capturing keyboard events for. + this.keyboardElement_ = null; + + // The event handlers we are interested in, and their bound callbacks, saved + // so they can be uninstalled with removeEventListener, when required. + this.handlers_ = [ + ['focusout', this.onFocusOut_.bind(this)], + ['keydown', this.onKeyDown_.bind(this)], + ['keypress', this.onKeyPress_.bind(this)], + ['keyup', this.onKeyUp_.bind(this)], + ['textInput', this.onTextInput_.bind(this)] + ]; + + /** + * The current key map. + */ + this.keyMap = new hterm.Keyboard.KeyMap(this); + + this.bindings = new hterm.Keyboard.Bindings(this); + + /** + * none: Disable any AltGr related munging. + * ctrl-alt: Assume Ctrl+Alt means AltGr. + * left-alt: Assume left Alt means AltGr. + * right-alt: Assume right Alt means AltGr. + */ + this.altGrMode = 'none'; + + /** + * If true, Shift-Insert will fall through to the browser as a paste. + * If false, the keystroke will be sent to the host. + */ + this.shiftInsertPaste = true; + + /** + * If true, home/end will control the terminal scrollbar and shift home/end + * will send the VT keycodes. If false then home/end sends VT codes and + * shift home/end scrolls. + */ + this.homeKeysScroll = false; + + /** + * Same as above, except for page up/page down. + */ + this.pageKeysScroll = false; + + /** + * If true, Ctrl-Plus/Minus/Zero controls zoom. + * If false, Ctrl-Shift-Plus/Minus/Zero controls zoom, Ctrl-Minus sends ^_, + * Ctrl-Plus/Zero do nothing. + */ + this.ctrlPlusMinusZeroZoom = true; + + /** + * Ctrl+C copies if true, sends ^C to host if false. + * Ctrl+Shift+C sends ^C to host if true, copies if false. + */ + this.ctrlCCopy = false; + + /** + * Ctrl+V pastes if true, sends ^V to host if false. + * Ctrl+Shift+V sends ^V to host if true, pastes if false. + */ + this.ctrlVPaste = false; + + /** + * Enable/disable application keypad. + * + * This changes the way numeric keys are sent from the keyboard. + */ + this.applicationKeypad = false; + + /** + * Enable/disable the application cursor mode. + * + * This changes the way cursor keys are sent from the keyboard. + */ + this.applicationCursor = false; + + /** + * If true, the backspace should send BS ('\x08', aka ^H). Otherwise + * the backspace key should send '\x7f'. + */ + this.backspaceSendsBackspace = false; + + /** + * The encoding method for data sent to the host. + */ + this.characterEncoding = 'utf-8'; + + /** + * Set whether the meta key sends a leading escape or not. + */ + this.metaSendsEscape = true; + + /** + * Set whether meta-V gets passed to host. + */ + this.passMetaV = true; + + /** + * Controls how the alt key is handled. + * + * escape....... Send an ESC prefix. + * 8-bit........ Add 128 to the unshifted character as in xterm. + * browser-key.. Wait for the keypress event and see what the browser says. + * (This won't work well on platforms where the browser + * performs a default action for some alt sequences.) + * + * This setting only matters when alt is distinct from meta (altIsMeta is + * false.) + */ + this.altSendsWhat = 'escape'; + + /** + * Set whether the alt key acts as a meta key, instead of producing 8-bit + * characters. + * + * True to enable, false to disable, null to autodetect based on platform. + */ + this.altIsMeta = false; + + /** + * If true, tries to detect DEL key events that are from alt-backspace on + * Chrome OS vs from a true DEL key press. + * + * Background: At the time of writing, on Chrome OS, alt-backspace is mapped + * to DEL. Some users may be happy with this, but others may be frustrated + * that it's impossible to do meta-backspace. If the user enables this pref, + * we use a trick to tell a true DEL keypress from alt-backspace: on + * alt-backspace, we will see the alt key go down, then get a DEL keystroke + * that indicates that alt is not pressed. See https://crbug.com/174410 . + */ + this.altBackspaceIsMetaBackspace = false; + + /** + * Used to keep track of the current alt-key state, which is necessary for + * the altBackspaceIsMetaBackspace preference above and for the altGrMode + * preference. This is a bitmap with where bit positions correspond to the + * "location" property of the key event. + */ + this.altKeyPressed = 0; + + /** + * If true, Chrome OS media keys will be mapped to their F-key equivalent. + * E.g. "Back" will be mapped to F1. If false, Chrome will handle the keys. + */ + this.mediaKeysAreFKeys = false; + + /** + * Holds the previous setting of altSendsWhat when DECSET 1039 is used. When + * DECRST 1039 is used, altSendsWhat is changed back to this and this is + * nulled out. + */ + this.previousAltSendsWhat_ = null; +}; + +/** + * Special handling for keyCodes in a keyboard layout. + */ +hterm.Keyboard.KeyActions = { + /** + * Call preventDefault and stopPropagation for this key event and nothing + * else. + */ + CANCEL: lib.f.createEnum('CANCEL'), + + /** + * This performs the default terminal action for the key. If used in the + * 'normal' action and the the keystroke represents a printable key, the + * character will be sent to the host. If used in one of the modifier + * actions, the terminal will perform the normal action after (possibly) + * altering it. + * + * - If the normal sequence starts with CSI, the sequence will be adjusted + * to include the modifier parameter as described in [XTERM] in the final + * table of the "PC-Style Function Keys" section. + * + * - If the control key is down and the key represents a printable character, + * and the uppercase version of the unshifted keycap is between + * 64 (ASCII '@') and 95 (ASCII '_'), then the uppercase version of the + * unshifted keycap minus 64 is sent. This makes '^@' send '\x00' and + * '^_' send '\x1f'. (Note that one higher that 0x1f is 0x20, which is + * the first printable ASCII value.) + * + * - If the alt key is down and the key represents a printable character then + * the value of the character is shifted up by 128. + * + * - If meta is down and configured to send an escape, '\x1b' will be sent + * before the normal action is performed. + */ + DEFAULT: lib.f.createEnum('DEFAULT'), + + /** + * Causes the terminal to opt out of handling the key event, instead letting + * the browser deal with it. + */ + PASS: lib.f.createEnum('PASS'), + + /** + * Insert the first or second character of the keyCap, based on e.shiftKey. + * The key will be handled in onKeyDown, and e.preventDefault() will be + * called. + * + * It is useful for a modified key action, where it essentially strips the + * modifier while preventing the browser from reacting to the key. + */ + STRIP: lib.f.createEnum('STRIP') +}; + +/** + * Encode a string according to the 'send-encoding' preference. + */ +hterm.Keyboard.prototype.encode = function(str) { + if (this.characterEncoding == 'utf-8') + return this.terminal.vt.encodeUTF8(str); + + return str; +}; + +/** + * Capture keyboard events sent to the associated element. + * + * This enables the keyboard. Captured events are consumed by this class + * and will not perform their default action or bubble to other elements. + * + * Passing a null element will uninstall the keyboard handlers. + * + * @param {HTMLElement} element The element whose events should be captured, or + * null to disable the keyboard. + */ +hterm.Keyboard.prototype.installKeyboard = function(element) { + if (element == this.keyboardElement_) + return; + + if (element && this.keyboardElement_) + this.installKeyboard(null); + + for (var i = 0; i < this.handlers_.length; i++) { + var handler = this.handlers_[i]; + if (element) { + element.addEventListener(handler[0], handler[1]); + } else { + this.keyboardElement_.removeEventListener(handler[0], handler[1]); + } + } + + this.keyboardElement_ = element; +}; + +/** + * Disable keyboard event capture. + * + * This will allow the browser to process key events normally. + */ +hterm.Keyboard.prototype.uninstallKeyboard = function() { + this.installKeyboard(null); +}; + +/** + * Handle onTextInput events. + * + * These are generated when using IMEs, Virtual Keyboards (VKs), compose keys, + * Unicode input, etc... + */ +hterm.Keyboard.prototype.onTextInput_ = function(e) { + if (!e.data) + return; + + // Just pass the generated buffer straight down. No need for us to split it + // up or otherwise parse it ahead of times. + this.terminal.onVTKeystroke(e.data); +}; + +/** + * Handle onKeyPress events. + */ +hterm.Keyboard.prototype.onKeyPress_ = function(e) { + var code; + + var key = String.fromCharCode(e.which); + var lowerKey = key.toLowerCase(); + if ((e.ctrlKey || e.metaKey) && (lowerKey == 'c' || lowerKey == 'v')) { + // On FF the key press (not key down) event gets fired for copy/paste. + // Let it fall through for the default browser behavior. + return; + } + + if (e.keyCode == 9 /* Tab */) { + // On FF, a key press event will be fired in addition of key down for the + // Tab key if key down isn't handled. This would only happen if a custom + // PASS binding has been created and therefore this should be handled by the + // browser. + return; + } + + if (e.altKey && this.altSendsWhat == 'browser-key' && e.charCode == 0) { + // If we got here because we were expecting the browser to handle an + // alt sequence but it didn't do it, then we might be on an OS without + // an enabled IME system. In that case we fall back to xterm-like + // behavior. + // + // This happens here only as a fallback. Typically these platforms should + // set altSendsWhat to either 'escape' or '8-bit'. + var ch = String.fromCharCode(e.keyCode); + if (!e.shiftKey) + ch = ch.toLowerCase(); + code = ch.charCodeAt(0) + 128; + + } else if (e.charCode >= 32) { + ch = e.charCode; + } + + if (ch) + this.terminal.onVTKeystroke(String.fromCharCode(ch)); + + e.preventDefault(); + e.stopPropagation(); +}; + +/** + * Prevent default handling for non-ctrl-shifted event. + * + * When combined with Chrome permission 'app.window.fullscreen.overrideEsc', + * and called for both key down and key up events, + * the ESC key remains usable within fullscreen Chrome app windows. + */ +hterm.Keyboard.prototype.preventChromeAppNonCtrlShiftDefault_ = function(e) { + if (!window.chrome || !window.chrome.app || !window.chrome.app.window) + return; + if (!e.ctrlKey || !e.shiftKey) + e.preventDefault(); +}; + +hterm.Keyboard.prototype.onFocusOut_ = function(e) { + this.altKeyPressed = 0; +}; + +hterm.Keyboard.prototype.onKeyUp_ = function(e) { + if (e.keyCode == 18) + this.altKeyPressed = this.altKeyPressed & ~(1 << (e.location - 1)); + + if (e.keyCode == 27) + this.preventChromeAppNonCtrlShiftDefault_(e); +}; + +/** + * Handle onKeyDown events. + */ +hterm.Keyboard.prototype.onKeyDown_ = function(e) { + if (e.keyCode == 18) + this.altKeyPressed = this.altKeyPressed | (1 << (e.location - 1)); + + if (e.keyCode == 27) + this.preventChromeAppNonCtrlShiftDefault_(e); + + var keyDef = this.keyMap.keyDefs[e.keyCode]; + if (!keyDef) { + // If this key hasn't been explicitly registered, fall back to the unknown + // key mapping (keyCode == 0), and then automatically register it to avoid + // any further warnings here. + console.warn(`No definition for key ${e.key} (keyCode ${e.keyCode})`); + keyDef = this.keyMap.keyDefs[0]; + this.keyMap.addKeyDef(e.keyCode, keyDef); + } + + // The type of action we're going to use. + var resolvedActionType = null; + + var self = this; + function getAction(name) { + // Get the key action for the given action name. If the action is a + // function, dispatch it. If the action defers to the normal action, + // resolve that instead. + + resolvedActionType = name; + + var action = keyDef[name]; + if (typeof action == 'function') + action = action.apply(self.keyMap, [e, keyDef]); + + if (action === DEFAULT && name != 'normal') + action = getAction('normal'); + + return action; + } + + // Note that we use the triple-equals ('===') operator to test equality for + // these constants, in order to distinguish usage of the constant from usage + // of a literal string that happens to contain the same bytes. + var CANCEL = hterm.Keyboard.KeyActions.CANCEL; + var DEFAULT = hterm.Keyboard.KeyActions.DEFAULT; + var PASS = hterm.Keyboard.KeyActions.PASS; + var STRIP = hterm.Keyboard.KeyActions.STRIP; + + var control = e.ctrlKey; + var alt = this.altIsMeta ? false : e.altKey; + var meta = this.altIsMeta ? (e.altKey || e.metaKey) : e.metaKey; + + // In the key-map, we surround the keyCap for non-printables in "[...]" + var isPrintable = !(/^\[\w+\]$/.test(keyDef.keyCap)); + + switch (this.altGrMode) { + case 'ctrl-alt': + if (isPrintable && control && alt) { + // ctrl-alt-printable means altGr. We clear out the control and + // alt modifiers and wait to see the charCode in the keydown event. + control = false; + alt = false; + } + break; + + case 'right-alt': + if (isPrintable && (this.terminal.keyboard.altKeyPressed & 2)) { + control = false; + alt = false; + } + break; + + case 'left-alt': + if (isPrintable && (this.terminal.keyboard.altKeyPressed & 1)) { + control = false; + alt = false; + } + break; + } + + var action; + + if (control) { + action = getAction('control'); + } else if (alt) { + action = getAction('alt'); + } else if (meta) { + action = getAction('meta'); + } else { + action = getAction('normal'); + } + + // If e.maskShiftKey was set (during getAction) it means the shift key is + // already accounted for in the action, and we should not act on it any + // further. This is currently only used for Ctrl-Shift-Tab, which should send + // "CSI Z", not "CSI 1 ; 2 Z". + var shift = !e.maskShiftKey && e.shiftKey; + + var keyDown = { + keyCode: e.keyCode, + shift: e.shiftKey, // not `var shift` from above. + ctrl: control, + alt: alt, + meta: meta + }; + + var binding = this.bindings.getBinding(keyDown); + + if (binding) { + // Clear out the modifier bits so we don't try to munge the sequence + // further. + shift = control = alt = meta = false; + resolvedActionType = 'normal'; + action = binding.action; + + if (typeof action == 'function') + action = action.call(this, this.terminal, keyDown); + } + + if (alt && this.altSendsWhat == 'browser-key' && action == DEFAULT) { + // When altSendsWhat is 'browser-key', we wait for the keypress event. + // In keypress, the browser should have set the event.charCode to the + // appropriate character. + // TODO(rginda): Character compositions will need some black magic. + action = PASS; + } + + if (action === PASS || (action === DEFAULT && !(control || alt || meta))) { + // If this key is supposed to be handled by the browser, or it is an + // unmodified key with the default action, then exit this event handler. + // If it's an unmodified key, it'll be handled in onKeyPress where we + // can tell for sure which ASCII code to insert. + // + // This block needs to come before the STRIP test, otherwise we'll strip + // the modifier and think it's ok to let the browser handle the keypress. + // The browser won't know we're trying to ignore the modifiers and might + // perform some default action. + return; + } + + if (action === STRIP) { + alt = control = false; + action = keyDef.normal; + if (typeof action == 'function') + action = action.apply(this.keyMap, [e, keyDef]); + + if (action == DEFAULT && keyDef.keyCap.length == 2) + action = keyDef.keyCap.substr((shift ? 1 : 0), 1); + } + + e.preventDefault(); + e.stopPropagation(); + + if (action === CANCEL) + return; + + if (action !== DEFAULT && typeof action != 'string') { + console.warn('Invalid action: ' + JSON.stringify(action)); + return; + } + + // Strip the modifier that is associated with the action, since we assume that + // modifier has already been accounted for in the action. + if (resolvedActionType == 'control') { + control = false; + } else if (resolvedActionType == 'alt') { + alt = false; + } else if (resolvedActionType == 'meta') { + meta = false; + } + + if (action.substr(0, 2) == '\x1b[' && (alt || control || shift || meta)) { + // The action is an escape sequence that and it was triggered in the + // presence of a keyboard modifier, we may need to alter the action to + // include the modifier before sending it. + + // The math is funky but aligns w/xterm. + let imod = 1; + if (shift) + imod += 1; + if (alt) + imod += 2; + if (control) + imod += 4; + if (meta) + imod += 8; + let mod = ';' + imod; + + if (action.length == 3) { + // Some of the CSI sequences have zero parameters unless modified. + action = '\x1b[1' + mod + action.substr(2, 1); + } else { + // Others always have at least one parameter. + action = action.substr(0, action.length - 1) + mod + + action.substr(action.length - 1); + } + + } else { + if (action === DEFAULT) { + action = keyDef.keyCap.substr((shift ? 1 : 0), 1); + + if (control) { + var unshifted = keyDef.keyCap.substr(0, 1); + var code = unshifted.charCodeAt(0); + if (code >= 64 && code <= 95) { + action = String.fromCharCode(code - 64); + } + } + } + + if (alt && this.altSendsWhat == '8-bit' && action.length == 1) { + var code = action.charCodeAt(0) + 128; + action = String.fromCharCode(code); + } + + // We respect alt/metaSendsEscape even if the keymap action was a literal + // string. Otherwise, every overridden alt/meta action would have to + // check alt/metaSendsEscape. + if ((alt && this.altSendsWhat == 'escape') || + (meta && this.metaSendsEscape)) { + action = '\x1b' + action; + } + } + + this.terminal.onVTKeystroke(action); +}; +// SOURCE FILE: hterm/js/hterm_keyboard_bindings.js +// Copyright (c) 2015 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * A mapping from hterm.Keyboard.KeyPattern to an action. + * + * TODO(rginda): For now this bindings code is only used for user overrides. + * hterm.Keyboard.KeyMap still handles all of the built-in key mappings. + * It'd be nice if we migrated that over to be hterm.Keyboard.Bindings based. + */ +hterm.Keyboard.Bindings = function() { + this.bindings_ = {}; +}; + +/** + * Remove all bindings. + */ +hterm.Keyboard.Bindings.prototype.clear = function () { + this.bindings_ = {}; +}; + +/** + * Add a new binding. + * + * Internal API that assumes parsed objects as inputs. + * See the public addBinding for more details. + * + * @param {hterm.Keyboard.KeyPattern} keyPattern + * @param {string|function|hterm.Keyboard.KeyAction} action + */ +hterm.Keyboard.Bindings.prototype.addBinding_ = function(keyPattern, action) { + var binding = null; + var list = this.bindings_[keyPattern.keyCode]; + if (list) { + for (var i = 0; i < list.length; i++) { + if (list[i].keyPattern.matchKeyPattern(keyPattern)) { + binding = list[i]; + break; + } + } + } + + if (binding) { + binding.action = action; + } else { + binding = {keyPattern: keyPattern, action: action}; + + if (!list) { + this.bindings_[keyPattern.keyCode] = [binding]; + } else { + this.bindings_[keyPattern.keyCode].push(binding); + + list.sort(function(a, b) { + return hterm.Keyboard.KeyPattern.sortCompare( + a.keyPattern, b.keyPattern); + }); + } + } +}; + +/** + * Add a new binding. + * + * If a binding for the keyPattern already exists it will be overridden. + * + * More specific keyPatterns take precedence over those with wildcards. Given + * bindings for "Ctrl-A" and "Ctrl-*-A", and a "Ctrl-A" keydown, the "Ctrl-A" + * binding will match even if "Ctrl-*-A" was created last. + * + * If action is a string, it will be passed through hterm.Parser.parseKeyAction. + * + * For example: + * // Will replace Ctrl-P keystrokes with the string "hiya!". + * addBinding('Ctrl-P', "'hiya!'"); + * // Will cancel the keystroke entirely (make it do nothing). + * addBinding('Alt-D', hterm.Keyboard.KeyActions.CANCEL); + * // Will execute the code and return the action. + * addBinding('Ctrl-T', function() { + * console.log('Got a T!'); + * return hterm.Keyboard.KeyActions.PASS; + * }); + * + * @param {string|hterm.Keyboard.KeyPattern} keyPattern + * @param {string|function|hterm.Keyboard.KeyAction} action + */ +hterm.Keyboard.Bindings.prototype.addBinding = function(key, action) { + // If we're given a hterm.Keyboard.KeyPattern object, pass it down. + if (typeof key != 'string') { + this.addBinding_(key, action); + return; + } + + // Here we treat key as a string. + var p = new hterm.Parser(); + + p.reset(key); + var sequence; + + try { + sequence = p.parseKeySequence(); + } catch (ex) { + console.error(ex); + return; + } + + if (!p.isComplete()) { + console.error(p.error('Expected end of sequence: ' + sequence)); + return; + } + + // If action is a string, parse it. Otherwise assume it's callable. + if (typeof action == 'string') { + p.reset(action); + try { + action = p.parseKeyAction(); + } catch (ex) { + console.error(ex); + return; + } + } + + if (!p.isComplete()) { + console.error(p.error('Expected end of sequence: ' + sequence)); + return; + } + + this.addBinding_(new hterm.Keyboard.KeyPattern(sequence), action); +}; + +/** + * Add multiple bindings at a time using a map of {string: string, ...} + * + * This uses hterm.Parser to parse the maps key into KeyPatterns, and the + * map values into {string|function|KeyAction}. + * + * For example: + * { + * // Will replace Ctrl-P keystrokes with the string "hiya!". + * 'Ctrl-P': "'hiya!'", + * // Will cancel the keystroke entirely (make it do nothing). + * 'Alt-D': hterm.Keyboard.KeyActions.CANCEL, + * } + * + * @param {Object} map + */ +hterm.Keyboard.Bindings.prototype.addBindings = function(map) { + for (var key in map) { + this.addBinding(key, map[key]); + } +}; + +/** + * Return the binding that is the best match for the given keyDown record, + * or null if there is no match. + * + * @param {Object} keyDown An object with a keyCode property and zero or + * more boolean properties representing key modifiers. These property names + * must match those defined in hterm.Keyboard.KeyPattern.modifiers. + */ +hterm.Keyboard.Bindings.prototype.getBinding = function(keyDown) { + var list = this.bindings_[keyDown.keyCode]; + if (!list) + return null; + + for (var i = 0; i < list.length; i++) { + var binding = list[i]; + if (binding.keyPattern.matchKeyDown(keyDown)) + return binding; + } + + return null; +}; +// SOURCE FILE: hterm/js/hterm_keyboard_keymap.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('hterm.Keyboard.KeyActions'); + +/** + * The default key map for hterm. + * + * Contains a mapping of keyCodes to keyDefs (aka key definitions). The key + * definition tells the hterm.Keyboard class how to handle keycodes. + * + * This should work for most cases, as the printable characters get handled + * in the keypress event. In that case, even if the keycap is wrong in the + * key map, the correct character should be sent. + * + * Different layouts, such as Dvorak should work with this keymap, as those + * layouts typically move keycodes around on the keyboard without disturbing + * the actual keycaps. + * + * There may be issues with control keys on non-US keyboards or with keyboards + * that very significantly from the expectations here, in which case we may + * have to invent new key maps. + * + * The sequences defined in this key map come from [XTERM] as referenced in + * vt.js, starting with the section titled "Alt and Meta Keys". + */ +hterm.Keyboard.KeyMap = function(keyboard) { + this.keyboard = keyboard; + this.keyDefs = {}; + this.reset(); +}; + +/** + * Add a single key definition. + * + * The definition is an object containing the following fields: 'keyCap', + * 'normal', 'control', 'alt', and 'meta'. + * + * - keyCap is a string identifying the key on the keyboard. For printable + * keys, the key cap should be exactly two characters, starting with the + * unshifted version. For example, 'aA', 'bB', '1!' and '=+'. For + * non-printable the key cap should be surrounded in square braces, as in + * '[INS]', '[LEFT]'. By convention, non-printable keycaps are in uppercase + * but this is not a strict requirement. + * + * - Normal is the action that should be performed when the key is pressed + * in the absence of any modifier. See below for the supported actions. + * + * - Control is the action that should be performed when the key is pressed + * along with the control modifier. See below for the supported actions. + * + * - Alt is the action that should be performed when the key is pressed + * along with the alt modifier. See below for the supported actions. + * + * - Meta is the action that should be performed when the key is pressed + * along with the meta modifier. See below for the supported actions. + * + * Actions can be one of the hterm.Keyboard.KeyActions as documented below, + * a literal string, or an array. If the action is a literal string then + * the string is sent directly to the host. If the action is an array it + * is taken to be an escape sequence that may be altered by modifier keys. + * The second-to-last element of the array will be overwritten with the + * state of the modifier keys, as specified in the final table of "PC-Style + * Function Keys" from [XTERM]. + */ +hterm.Keyboard.KeyMap.prototype.addKeyDef = function(keyCode, def) { + if (keyCode in this.keyDefs) + console.warn('Duplicate keyCode: ' + keyCode); + + this.keyDefs[keyCode] = def; +}; + +/** + * Add multiple key definitions in a single call. + * + * This function takes the key definitions as variable argument list. Each + * argument is the key definition specified as an array. + * + * (If the function took everything as one big hash we couldn't detect + * duplicates, and there would be a lot more typing involved.) + * + * Each key definition should have 6 elements: (keyCode, keyCap, normal action, + * control action, alt action and meta action). See KeyMap.addKeyDef for the + * meaning of these elements. + */ +hterm.Keyboard.KeyMap.prototype.addKeyDefs = function(var_args) { + for (var i = 0; i < arguments.length; i++) { + this.addKeyDef(arguments[i][0], + { keyCap: arguments[i][1], + normal: arguments[i][2], + control: arguments[i][3], + alt: arguments[i][4], + meta: arguments[i][5] + }); + } +}; + +/** + * Set up the default state for this keymap. + */ +hterm.Keyboard.KeyMap.prototype.reset = function() { + this.keyDefs = {}; + + var self = this; + + // This function is used by the "macro" functions below. It makes it + // possible to use the call() macro as an argument to any other macro. + function resolve(action, e, k) { + if (typeof action == 'function') + return action.apply(self, [e, k]); + + return action; + } + + // If not application keypad a, else b. The keys that care about + // application keypad ignore it when the key is modified. + function ak(a, b) { + return function(e, k) { + var action = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || + !self.keyboard.applicationKeypad) ? a : b; + return resolve(action, e, k); + }; + } + + // If mod or not application cursor a, else b. The keys that care about + // application cursor ignore it when the key is modified. + function ac(a, b) { + return function(e, k) { + var action = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || + !self.keyboard.applicationCursor) ? a : b; + return resolve(action, e, k); + }; + } + + // If not backspace-sends-backspace keypad a, else b. + function bs(a, b) { + return function(e, k) { + var action = !self.keyboard.backspaceSendsBackspace ? a : b; + return resolve(action, e, k); + }; + } + + // If not e.shiftKey a, else b. + function sh(a, b) { + return function(e, k) { + var action = !e.shiftKey ? a : b; + e.maskShiftKey = true; + return resolve(action, e, k); + }; + } + + // If not e.altKey a, else b. + function alt(a, b) { + return function(e, k) { + var action = !e.altKey ? a : b; + return resolve(action, e, k); + }; + } + + // If no modifiers a, else b. + function mod(a, b) { + return function(e, k) { + var action = !(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) ? a : b; + return resolve(action, e, k); + }; + } + + // Compute a control character for a given character. + function ctl(ch) { return String.fromCharCode(ch.charCodeAt(0) - 64); } + + // Call a method on the keymap instance. + function c(m) { return function(e, k) { return this[m](e, k); }; } + + // Ignore if not trapping media keys. + function med(fn) { + return function(e, k) { + if (!self.keyboard.mediaKeysAreFKeys) { + // Block Back, Forward, and Reload keys to avoid navigating away from + // the current page. + return (e.keyCode == 166 || e.keyCode == 167 || e.keyCode == 168) ? + hterm.Keyboard.KeyActions.CANCEL : + hterm.Keyboard.KeyActions.PASS; + } + return resolve(fn, e, k); + }; + } + + // Browser-specific differences. + if (window.navigator && navigator.userAgent) { + if (navigator.userAgent.includes('Firefox')) { + // Firefox defines some keys uniquely. No other browser defines these is + // this way. Some even conflict. The keyCode field isn't well documented + // as it isn't standardized. At some point we should switch to "key". + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode + // http://unixpapa.com/js/key.html + var keycapMute = 181; // Mute + var keycapVolDn = 182; // Volume Down + var keycapVolUp = 183; // Volume Up + var keycapSC = 59; // ;: + var keycapEP = 61; // =+ + var keycapMU = 173; // -_ + + this.addKeyDefs( + // Firefox Italian +*. + [171, '+*', DEFAULT, c('onPlusMinusZero_'), DEFAULT, c('onPlusMinusZero_')] + ); + } else { + // All other browsers use these mappings. + var keycapMute = 173; // Mute + var keycapVolDn = 174; // Volume Down + var keycapVolUp = 175; // Volume Up + var keycapSC = 186; // ;: + var keycapEP = 187; // =+ + var keycapMU = 189; // -_ + } + } + + var ESC = '\x1b'; + var CSI = '\x1b['; + var SS3 = '\x1bO'; + + var CANCEL = hterm.Keyboard.KeyActions.CANCEL; + var DEFAULT = hterm.Keyboard.KeyActions.DEFAULT; + var PASS = hterm.Keyboard.KeyActions.PASS; + var STRIP = hterm.Keyboard.KeyActions.STRIP; + + this.addKeyDefs( + // These fields are: [keycode, keycap, normal, control, alt, meta] + + // The browser sends the keycode 0 for some keys. We'll just assume it's + // going to do the right thing by default for those keys. + [0, '[UNKNOWN]', PASS, PASS, PASS, PASS], + + // First row. + // These bindings match xterm for lack of a better standard. The emitted + // values might look like they're skipping values, but it's what xterm does. + // https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-PC-Style-Function-Keys + [27, '[ESC]', ESC, DEFAULT, DEFAULT, DEFAULT], + [112, '[F1]', mod(SS3 + 'P', CSI + 'P'), DEFAULT, CSI + "23~", DEFAULT], + [113, '[F2]', mod(SS3 + 'Q', CSI + 'Q'), DEFAULT, CSI + "24~", DEFAULT], + [114, '[F3]', mod(SS3 + 'R', CSI + 'R'), DEFAULT, CSI + "25~", DEFAULT], + [115, '[F4]', mod(SS3 + 'S', CSI + 'S'), DEFAULT, CSI + "26~", DEFAULT], + [116, '[F5]', CSI + '15~', DEFAULT, CSI + "28~", DEFAULT], + [117, '[F6]', CSI + '17~', DEFAULT, CSI + "29~", DEFAULT], + [118, '[F7]', CSI + '18~', DEFAULT, CSI + "31~", DEFAULT], + [119, '[F8]', CSI + '19~', DEFAULT, CSI + "32~", DEFAULT], + [120, '[F9]', CSI + '20~', DEFAULT, CSI + "33~", DEFAULT], + [121, '[F10]', CSI + '21~', DEFAULT, CSI + "34~", DEFAULT], + [122, '[F11]', c('onF11_'), DEFAULT, CSI + "42~", DEFAULT], + [123, '[F12]', CSI + '24~', DEFAULT, CSI + "43~", DEFAULT], + + // Second row. + [192, '`~', DEFAULT, sh(ctl('@'), ctl('^')), DEFAULT, PASS], + [49, '1!', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [50, '2@', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [51, '3#', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [52, '4$', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [53, '5%', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [54, '6^', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [55, '7&', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [56, '8*', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [57, '9(', DEFAULT, c('onCtrlNum_'), c('onAltNum_'), c('onMetaNum_')], + [48, '0)', DEFAULT, c('onPlusMinusZero_'),c('onAltNum_'),c('onPlusMinusZero_')], + [keycapMU, '-_', DEFAULT, c('onPlusMinusZero_'), DEFAULT, c('onPlusMinusZero_')], + [keycapEP, '=+', DEFAULT, c('onPlusMinusZero_'), DEFAULT, c('onPlusMinusZero_')], + + [8, '[BKSP]', bs('\x7f', '\b'), bs('\b', '\x7f'), DEFAULT, DEFAULT], + + // Third row. + [9, '[TAB]', sh('\t', CSI + 'Z'), STRIP, PASS, DEFAULT], + [81, 'qQ', DEFAULT, ctl('Q'), DEFAULT, DEFAULT], + [87, 'wW', DEFAULT, ctl('W'), DEFAULT, DEFAULT], + [69, 'eE', DEFAULT, ctl('E'), DEFAULT, DEFAULT], + [82, 'rR', DEFAULT, ctl('R'), DEFAULT, DEFAULT], + [84, 'tT', DEFAULT, ctl('T'), DEFAULT, DEFAULT], + [89, 'yY', DEFAULT, ctl('Y'), DEFAULT, DEFAULT], + [85, 'uU', DEFAULT, ctl('U'), DEFAULT, DEFAULT], + [73, 'iI', DEFAULT, ctl('I'), DEFAULT, DEFAULT], + [79, 'oO', DEFAULT, ctl('O'), DEFAULT, DEFAULT], + [80, 'pP', DEFAULT, ctl('P'), DEFAULT, DEFAULT], + [219, '[{', DEFAULT, ctl('['), DEFAULT, DEFAULT], + [221, ']}', DEFAULT, ctl(']'), DEFAULT, DEFAULT], + [220, '\\|', DEFAULT, ctl('\\'), DEFAULT, DEFAULT], + + // Fourth row. (We let Ctrl-Shift-J pass for Chrome DevTools.) + [20, '[CAPS]', PASS, PASS, PASS, DEFAULT], + [65, 'aA', DEFAULT, ctl('A'), DEFAULT, DEFAULT], + [83, 'sS', DEFAULT, ctl('S'), DEFAULT, DEFAULT], + [68, 'dD', DEFAULT, ctl('D'), DEFAULT, DEFAULT], + [70, 'fF', DEFAULT, ctl('F'), DEFAULT, DEFAULT], + [71, 'gG', DEFAULT, ctl('G'), DEFAULT, DEFAULT], + [72, 'hH', DEFAULT, ctl('H'), DEFAULT, DEFAULT], + [74, 'jJ', DEFAULT, sh(ctl('J'), PASS), DEFAULT, DEFAULT], + [75, 'kK', DEFAULT, sh(ctl('K'), c('onClear_')), DEFAULT, DEFAULT], + [76, 'lL', DEFAULT, sh(ctl('L'), PASS), DEFAULT, DEFAULT], + [keycapSC, ';:', DEFAULT, STRIP, DEFAULT, DEFAULT], + [222, '\'"', DEFAULT, STRIP, DEFAULT, DEFAULT], + [13, '[ENTER]', '\r', CANCEL, CANCEL, DEFAULT], + + // Fifth row. This includes the copy/paste shortcuts. On some + // platforms it's Ctrl-C/V, on others it's Meta-C/V. We assume either + // Ctrl-C/Meta-C should pass to the browser when there is a selection, + // and Ctrl-Shift-V/Meta-*-V should always pass to the browser (since + // these seem to be recognized as paste too). + [16, '[SHIFT]', PASS, PASS, PASS, DEFAULT], + [90, 'zZ', DEFAULT, ctl('Z'), DEFAULT, DEFAULT], + [88, 'xX', DEFAULT, ctl('X'), DEFAULT, DEFAULT], + [67, 'cC', DEFAULT, c('onCtrlC_'), DEFAULT, c('onMetaC_')], + [86, 'vV', DEFAULT, c('onCtrlV_'), DEFAULT, c('onMetaV_')], + [66, 'bB', DEFAULT, sh(ctl('B'), PASS), DEFAULT, sh(DEFAULT, PASS)], + [78, 'nN', DEFAULT, c('onCtrlN_'), DEFAULT, c('onMetaN_')], + [77, 'mM', DEFAULT, ctl('M'), DEFAULT, DEFAULT], + [188, ',<', DEFAULT, alt(STRIP, PASS), DEFAULT, DEFAULT], + [190, '.>', DEFAULT, alt(STRIP, PASS), DEFAULT, DEFAULT], + [191, '/?', DEFAULT, sh(ctl('_'), ctl('?')), DEFAULT, DEFAULT], + + // Sixth and final row. + [17, '[CTRL]', PASS, PASS, PASS, PASS], + [18, '[ALT]', PASS, PASS, PASS, PASS], + [91, '[LAPL]', PASS, PASS, PASS, PASS], + [32, ' ', DEFAULT, ctl('@'), DEFAULT, DEFAULT], + [92, '[RAPL]', PASS, PASS, PASS, PASS], + [93, '[RMENU]', PASS, PASS, PASS, PASS], + + // These things. + [42, '[PRTSCR]', PASS, PASS, PASS, PASS], + [145, '[SCRLK]', PASS, PASS, PASS, PASS], + [19, '[BREAK]', PASS, PASS, PASS, PASS], + + // The block of six keys above the arrows. + [45, '[INSERT]', c('onKeyInsert_'), DEFAULT, DEFAULT, DEFAULT], + [36, '[HOME]', c('onKeyHome_'), DEFAULT, DEFAULT, DEFAULT], + [33, '[PGUP]', c('onKeyPageUp_'), DEFAULT, DEFAULT, DEFAULT], + [46, '[DEL]', c('onKeyDel_'), DEFAULT, DEFAULT, DEFAULT], + [35, '[END]', c('onKeyEnd_'), DEFAULT, DEFAULT, DEFAULT], + [34, '[PGDOWN]', c('onKeyPageDown_'), DEFAULT, DEFAULT, DEFAULT], + + // Arrow keys. When unmodified they respect the application cursor state, + // otherwise they always send the CSI codes. + [38, '[UP]', c('onKeyArrowUp_'), DEFAULT, DEFAULT, DEFAULT], + [40, '[DOWN]', c('onKeyArrowDown_'), DEFAULT, DEFAULT, DEFAULT], + [39, '[RIGHT]', ac(CSI + 'C', SS3 + 'C'), DEFAULT, DEFAULT, DEFAULT], + [37, '[LEFT]', ac(CSI + 'D', SS3 + 'D'), DEFAULT, DEFAULT, DEFAULT], + + [144, '[NUMLOCK]', PASS, PASS, PASS, PASS], + + // On Apple keyboards, the NumLock key is a Clear key. It also tends to be + // what KP5 sends when numlock is off. Not clear if we could do anything + // useful with it, so just pass it along. + [12, '[CLEAR]', PASS, PASS, PASS, PASS], + + // With numlock off, the keypad generates the same key codes as the arrows + // and 'block of six' for some keys, and null key codes for the rest. + + // Keypad with numlock on generates unique key codes... + [96, '[KP0]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [97, '[KP1]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [98, '[KP2]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [99, '[KP3]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [100, '[KP4]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [101, '[KP5]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [102, '[KP6]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [103, '[KP7]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [104, '[KP8]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [105, '[KP9]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [107, '[KP+]', DEFAULT, c('onPlusMinusZero_'), DEFAULT, c('onPlusMinusZero_')], + [109, '[KP-]', DEFAULT, c('onPlusMinusZero_'), DEFAULT, c('onPlusMinusZero_')], + [106, '[KP*]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [111, '[KP/]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + [110, '[KP.]', DEFAULT, DEFAULT, DEFAULT, DEFAULT] + ); + + // OS-specific differences. + if (hterm.os == 'cros') { + this.addKeyDefs( + // Chrome OS keyboard top row. The media-keys-are-fkeys preference allows + // users to make these always behave as function keys (see those bindings + // above for more details). + [166, '[BACK]', med(mod(SS3+'P', CSI+'P')), DEFAULT, CSI+'23~', DEFAULT], // F1 + [167, '[FWD]', med(mod(SS3+'Q', CSI+'Q')), DEFAULT, CSI+'24~', DEFAULT], // F2 + [168, '[RELOAD]', med(mod(SS3+'R', CSI+'R')), DEFAULT, CSI+'25~', DEFAULT], // F3 + [183, '[FSCR]', med(mod(SS3+'S', CSI+'S')), DEFAULT, CSI+'26~', DEFAULT], // F4 + [182, '[WINS]', med(CSI + '15~'), DEFAULT, CSI+'28~', DEFAULT], // F5 + [216, '[BRIT-]', med(CSI + '17~'), DEFAULT, CSI+'29~', DEFAULT], // F6 + [217, '[BRIT+]', med(CSI + '18~'), DEFAULT, CSI+'31~', DEFAULT], // F7 + [173, '[MUTE]', med(CSI + '19~'), DEFAULT, CSI+'32~', DEFAULT], // F8 + [174, '[VOL-]', med(CSI + '20~'), DEFAULT, CSI+'33~', DEFAULT], // F9 + [175, '[VOL+]', med(CSI + '21~'), DEFAULT, CSI+'34~', DEFAULT], // F10 + + // We could make this into F11, but it'd be a bit weird. Chrome allows us + // to see this and react, but it doesn't actually allow us to block or + // cancel it, so it makes the screen flash/lock still. + [152, '[POWER]', DEFAULT, DEFAULT, DEFAULT, DEFAULT], + + // The Pixelbook has a slightly different layout. This means half the keys + // above are off by one. https://crbug.com/807513 + [179, '[PLAY]', med(CSI + '18~'), DEFAULT, CSI + '31~', DEFAULT], // F7 + // The settings / hamburgers / three hot dogs / menu / whatever-it's-called. + [154, '[DOGS]', med(CSI + '23~'), DEFAULT, CSI + '42~', DEFAULT], // F11 + + // We don't use this for anything, but keep it from popping up by default. + [153, '[ASSIST]', DEFAULT, DEFAULT, DEFAULT, DEFAULT] + ); + } +}; + +/** + * Either allow the paste or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyInsert_ = function(e) { + if (this.keyboard.shiftInsertPaste && e.shiftKey) + return hterm.Keyboard.KeyActions.PASS; + + return '\x1b[2~'; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyHome_ = function(e) { + if (!this.keyboard.homeKeysScroll ^ e.shiftKey) { + if ((e.altey || e.ctrlKey || e.shiftKey) || + !this.keyboard.applicationCursor) { + return '\x1b[H'; + } + + return '\x1bOH'; + } + + this.keyboard.terminal.scrollHome(); + return hterm.Keyboard.KeyActions.CANCEL; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyEnd_ = function(e) { + if (!this.keyboard.homeKeysScroll ^ e.shiftKey) { + if ((e.altKey || e.ctrlKey || e.shiftKey) || + !this.keyboard.applicationCursor) { + return '\x1b[F'; + } + + return '\x1bOF'; + } + + this.keyboard.terminal.scrollEnd(); + return hterm.Keyboard.KeyActions.CANCEL; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyPageUp_ = function(e) { + if (!this.keyboard.pageKeysScroll ^ e.shiftKey) + return '\x1b[5~'; + + this.keyboard.terminal.scrollPageUp(); + return hterm.Keyboard.KeyActions.CANCEL; +}; + +/** + * Either send a true DEL, or sub in meta-backspace. + * + * On Chrome OS, if we know the alt key is down, but we get a DEL event that + * claims that the alt key is not pressed, we know the DEL was a synthetic + * one from a user that hit alt-backspace. Based on a user pref, we can sub + * in meta-backspace in this case. + */ +hterm.Keyboard.KeyMap.prototype.onKeyDel_ = function(e) { + if (this.keyboard.altBackspaceIsMetaBackspace && + this.keyboard.altKeyPressed && !e.altKey) + return '\x1b\x7f'; + return '\x1b[3~'; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyPageDown_ = function(e) { + if (!this.keyboard.pageKeysScroll ^ e.shiftKey) + return '\x1b[6~'; + + this.keyboard.terminal.scrollPageDown(); + return hterm.Keyboard.KeyActions.CANCEL; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyArrowUp_ = function(e) { + if (!this.keyboard.applicationCursor && e.shiftKey) { + this.keyboard.terminal.scrollLineUp(); + return hterm.Keyboard.KeyActions.CANCEL; + } + + return (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || + !this.keyboard.applicationCursor) ? '\x1b[A' : '\x1bOA'; +}; + +/** + * Either scroll the scrollback buffer or send a key sequence. + */ +hterm.Keyboard.KeyMap.prototype.onKeyArrowDown_ = function(e) { + if (!this.keyboard.applicationCursor && e.shiftKey) { + this.keyboard.terminal.scrollLineDown(); + return hterm.Keyboard.KeyActions.CANCEL; + } + + return (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || + !this.keyboard.applicationCursor) ? '\x1b[B' : '\x1bOB'; +}; + +/** + * Clear the primary/alternate screens and the scrollback buffer. + */ +hterm.Keyboard.KeyMap.prototype.onClear_ = function(e, keyDef) { + this.keyboard.terminal.wipeContents(); + return hterm.Keyboard.KeyActions.CANCEL; +}; + +/** + * Handle F11 behavior (fullscreen) when not in a window. + * + * It would be nice to use the Fullscreen API, but the UX is slightly different + * a bad way: the Escape key is automatically registered for exiting. If we let + * the browser handle F11 directly though, we still get to capture Escape. + */ +hterm.Keyboard.KeyMap.prototype.onF11_ = function(e, keyDef) { + if (hterm.windowType != 'popup') + return hterm.Keyboard.KeyActions.PASS; + else + return '\x1b[23~'; +}; + +/** + * Either pass Ctrl-1..9 to the browser or send them to the host. + * + * Note that Ctrl-1 and Ctrl-9 don't actually have special sequences mapped + * to them in xterm or gnome-terminal. The range is really Ctrl-2..8, but + * we handle 1..9 since Chrome treats the whole range special. + */ +hterm.Keyboard.KeyMap.prototype.onCtrlNum_ = function(e, keyDef) { + // Compute a control character for a given character. + function ctl(ch) { return String.fromCharCode(ch.charCodeAt(0) - 64); } + + if (this.keyboard.terminal.passCtrlNumber && !e.shiftKey) + return hterm.Keyboard.KeyActions.PASS; + + switch (keyDef.keyCap.substr(0, 1)) { + case '1': return '1'; + case '2': return ctl('@'); + case '3': return ctl('['); + case '4': return ctl('\\'); + case '5': return ctl(']'); + case '6': return ctl('^'); + case '7': return ctl('_'); + case '8': return '\x7f'; + case '9': return '9'; + } +}; + +/** + * Either pass Alt-1..9 to the browser or send them to the host. + */ +hterm.Keyboard.KeyMap.prototype.onAltNum_ = function(e, keyDef) { + if (this.keyboard.terminal.passAltNumber && !e.shiftKey) + return hterm.Keyboard.KeyActions.PASS; + + return hterm.Keyboard.KeyActions.DEFAULT; +}; + +/** + * Either pass Meta-1..9 to the browser or send them to the host. + */ +hterm.Keyboard.KeyMap.prototype.onMetaNum_ = function(e, keyDef) { + if (this.keyboard.terminal.passMetaNumber && !e.shiftKey) + return hterm.Keyboard.KeyActions.PASS; + + return hterm.Keyboard.KeyActions.DEFAULT; +}; + +/** + * Either send a ^C or interpret the keystroke as a copy command. + */ +hterm.Keyboard.KeyMap.prototype.onCtrlC_ = function(e, keyDef) { + var selection = this.keyboard.terminal.getDocument().getSelection(); + + if (!selection.isCollapsed) { + if (this.keyboard.ctrlCCopy && !e.shiftKey) { + // Ctrl-C should copy if there is a selection, send ^C otherwise. + // Perform the copy by letting the browser handle Ctrl-C. On most + // browsers, this is the *only* way to place text on the clipboard from + // the 'drive-by' web. + if (this.keyboard.terminal.clearSelectionAfterCopy) { + setTimeout(selection.collapseToEnd.bind(selection), 50); + } + return hterm.Keyboard.KeyActions.PASS; + } + + if (!this.keyboard.ctrlCCopy && e.shiftKey) { + // Ctrl-Shift-C should copy if there is a selection, send ^C otherwise. + // Perform the copy manually. This only works in situations where + // document.execCommand('copy') is allowed. + if (this.keyboard.terminal.clearSelectionAfterCopy) { + setTimeout(selection.collapseToEnd.bind(selection), 50); + } + this.keyboard.terminal.copySelectionToClipboard(); + return hterm.Keyboard.KeyActions.CANCEL; + } + } + + return '\x03'; +}; + +/** + * Either send a ^N or open a new window to the same location. + */ +hterm.Keyboard.KeyMap.prototype.onCtrlN_ = function(e, keyDef) { + if (e.shiftKey) { + window.open(document.location.href, '', + 'chrome=no,close=yes,resize=yes,scrollbars=yes,' + + 'minimizable=yes,width=' + window.innerWidth + + ',height=' + window.innerHeight); + return hterm.Keyboard.KeyActions.CANCEL; + } + + return '\x0e'; +}; + +/** + * Either send a ^V or issue a paste command. + * + * The default behavior is to paste if the user presses Ctrl-Shift-V, and send + * a ^V if the user presses Ctrl-V. This can be flipped with the + * 'ctrl-v-paste' preference. + * + */ +hterm.Keyboard.KeyMap.prototype.onCtrlV_ = function(e, keyDef) { + if ((!e.shiftKey && this.keyboard.ctrlVPaste) || + (e.shiftKey && !this.keyboard.ctrlVPaste)) { + // We try to do the pasting ourselves as not all browsers/OSs bind Ctrl-V to + // pasting. Notably, on macOS, Ctrl-V/Ctrl-Shift-V do nothing. + // However, this might run into web restrictions, so if it fails, we still + // fallback to the letting the native behavior (hopefully) save us. + if (this.keyboard.terminal.paste()) + return hterm.Keyboard.KeyActions.CANCEL; + else + return hterm.Keyboard.KeyActions.PASS; + } + + return '\x16'; +}; + +/** + * Either the default action or open a new window to the same location. + */ +hterm.Keyboard.KeyMap.prototype.onMetaN_ = function(e, keyDef) { + if (e.shiftKey) { + window.open(document.location.href, '', + 'chrome=no,close=yes,resize=yes,scrollbars=yes,' + + 'minimizable=yes,width=' + window.outerWidth + + ',height=' + window.outerHeight); + return hterm.Keyboard.KeyActions.CANCEL; + } + + return hterm.Keyboard.KeyActions.DEFAULT; +}; + +/** + * Either send a Meta-C or allow the browser to interpret the keystroke as a + * copy command. + * + * If there is no selection, or if the user presses Meta-Shift-C, then we'll + * transmit an '\x1b' (if metaSendsEscape is on) followed by 'c' or 'C'. + * + * If there is a selection, we defer to the browser. In this case we clear out + * the selection so the user knows we heard them, and also to give them a + * chance to send a Meta-C by just hitting the key again. + */ +hterm.Keyboard.KeyMap.prototype.onMetaC_ = function(e, keyDef) { + var document = this.keyboard.terminal.getDocument(); + if (e.shiftKey || document.getSelection().isCollapsed) { + // If the shift key is being held, or there is no document selection, send + // a Meta-C. The keyboard code will add the ESC if metaSendsEscape is true, + // we just have to decide between 'c' and 'C'. + return keyDef.keyCap.substr(e.shiftKey ? 1 : 0, 1); + } + + // Otherwise let the browser handle it as a copy command. + if (this.keyboard.terminal.clearSelectionAfterCopy) { + setTimeout(function() { document.getSelection().collapseToEnd(); }, 50); + } + return hterm.Keyboard.KeyActions.PASS; +}; + +/** + * Either PASS or DEFAULT Meta-V, depending on preference. + * + * Always PASS Meta-Shift-V to allow browser to interpret the keystroke as + * a paste command. + */ +hterm.Keyboard.KeyMap.prototype.onMetaV_ = function(e, keyDef) { + if (e.shiftKey) + return hterm.Keyboard.KeyActions.PASS; + + return this.keyboard.passMetaV ? + hterm.Keyboard.KeyActions.PASS : + hterm.Keyboard.KeyActions.DEFAULT; +}; + +/** + * Handle font zooming. + * + * The browser's built-in zoom has a bit of an issue at certain zoom levels. + * At some magnifications, the measured height of a row of text differs from + * the height that was explicitly set. + * + * We override the browser zoom keys to change the ScrollPort's font size to + * avoid the issue. + */ +hterm.Keyboard.KeyMap.prototype.onPlusMinusZero_ = function(e, keyDef) { + if (!(this.keyboard.ctrlPlusMinusZeroZoom ^ e.shiftKey)) { + // If ctrl-PMZ controls zoom and the shift key is pressed, or + // ctrl-shift-PMZ controls zoom and this shift key is not pressed, + // then we want to send the control code instead of affecting zoom. + if (keyDef.keyCap == '-_') + return '\x1f'; // ^_ + + // Only ^_ is valid, the other sequences have no meaning. + return hterm.Keyboard.KeyActions.CANCEL; + } + + if (this.keyboard.terminal.getZoomFactor() != 1) { + // If we're not at 1:1 zoom factor, let the Ctrl +/-/0 keys control the + // browser zoom, so it's easier to for the user to get back to 100%. + return hterm.Keyboard.KeyActions.PASS; + } + + var cap = keyDef.keyCap.substr(0, 1); + if (cap == '0') { + this.keyboard.terminal.setFontSize(0); + } else { + var size = this.keyboard.terminal.getFontSize(); + + if (cap == '-' || keyDef.keyCap == '[KP-]') { + size -= 1; + } else { + size += 1; + } + + this.keyboard.terminal.setFontSize(size); + } + + return hterm.Keyboard.KeyActions.CANCEL; +}; +// SOURCE FILE: hterm/js/hterm_keyboard_keypattern.js +// Copyright (c) 2015 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * A record of modifier bits and keycode used to define a key binding. + * + * The modifier names are enumerated in the static KeyPattern.modifiers + * property below. Each modifier can be true, false, or "*". True means + * the modifier key must be present, false means it must not, and "*" means + * it doesn't matter. + */ +hterm.Keyboard.KeyPattern = function(spec) { + this.wildcardCount = 0; + this.keyCode = spec.keyCode; + + hterm.Keyboard.KeyPattern.modifiers.forEach(function(mod) { + this[mod] = spec[mod] || false; + if (this[mod] == '*') + this.wildcardCount++; + }.bind(this)); +}; + +/** + * Valid modifier names. + */ +hterm.Keyboard.KeyPattern.modifiers = [ + 'shift', 'ctrl', 'alt', 'meta' +]; + +/** + * A compare callback for Array.prototype.sort(). + * + * The bindings code wants to be sure to search through the strictest key + * patterns first, so that loosely defined patterns have a lower priority than + * exact patterns. + * + * @param {hterm.Keyboard.KeyPattern} a + * @param {hterm.Keyboard.KeyPattern} b + */ +hterm.Keyboard.KeyPattern.sortCompare = function(a, b) { + if (a.wildcardCount < b.wildcardCount) + return -1; + + if (a.wildcardCount > b.wildcardCount) + return 1; + + return 0; +}; + +/** + * Private method used to match this key pattern against other key patterns + * or key down events. + * + * @param {Object} The object to match. + * @param {boolean} True if we should ignore wildcards. Useful when you want + * to perform and exact match against another key pattern. + */ +hterm.Keyboard.KeyPattern.prototype.match_ = function(obj, exactMatch) { + if (this.keyCode != obj.keyCode) + return false; + + var rv = true; + + hterm.Keyboard.KeyPattern.modifiers.forEach(function(mod) { + var modValue = (mod in obj) ? obj[mod] : false; + if (!rv || (!exactMatch && this[mod] == '*') || this[mod] == modValue) + return; + + rv = false; + }.bind(this)); + + return rv; +}; + +/** + * Return true if the given keyDown object is a match for this key pattern. + * + * @param {Object} keyDown An object with a keyCode property and zero or + * more boolean properties representing key modifiers. These property names + * must match those defined in hterm.Keyboard.KeyPattern.modifiers. + */ +hterm.Keyboard.KeyPattern.prototype.matchKeyDown = function(keyDown) { + return this.match_(keyDown, false); +}; + +/** + * Return true if the given hterm.Keyboard.KeyPattern is exactly the same as + * this one. + * + * @param {hterm.Keyboard.KeyPattern} + */ +hterm.Keyboard.KeyPattern.prototype.matchKeyPattern = function(keyPattern) { + return this.match_(keyPattern, true); +}; +// SOURCE FILE: hterm/js/hterm_options.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview This file implements the hterm.Options class, + * which stores current operating conditions for the terminal. This object is + * used instead of a series of parameters to allow saving/restoring of cursor + * conditions easily, and to provide an easy place for common configuration + * options. + * + * Original code by Cory Maccarrone. + */ + +/** + * Constructor for the hterm.Options class, optionally acting as a copy + * constructor. + * + * The defaults are as defined in http://www.vt100.net/docs/vt510-rm/DECSTR + * except that we enable autowrap (wraparound) by default since that seems to + * be what xterm does. + * + * @param {hterm.Options=} opt_copy Optional instance to copy. + * @constructor + */ +hterm.Options = function(opt_copy) { + // All attributes in this class are public to allow easy access by the + // terminal. + + this.wraparound = opt_copy ? opt_copy.wraparound : true; + this.reverseWraparound = opt_copy ? opt_copy.reverseWraparound : false; + this.originMode = opt_copy ? opt_copy.originMode : false; + this.autoCarriageReturn = opt_copy ? opt_copy.autoCarriageReturn : false; + this.cursorVisible = opt_copy ? opt_copy.cursorVisible : false; + this.cursorBlink = opt_copy ? opt_copy.cursorBlink : false; + this.insertMode = opt_copy ? opt_copy.insertMode : false; + this.reverseVideo = opt_copy ? opt_copy.reverseVideo : false; + this.bracketedPaste = opt_copy ? opt_copy.bracketedPaste : false; +}; +// SOURCE FILE: hterm/js/hterm_parser.js +// Copyright (c) 2015 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('hterm.Keyboard.KeyActions'); + +/** + * @constructor + * Parses the key definition syntax used for user keyboard customizations. + */ +hterm.Parser = function() { + /** + * @type {string} The source string. + */ + this.source = ''; + + /** + * @type {number} The current position. + */ + this.pos = 0; + + /** + * @type {string?} The character at the current position. + */ + this.ch = null; +}; + +hterm.Parser.prototype.error = function(message) { + return new Error('Parse error at ' + this.pos + ': ' + message); +}; + +hterm.Parser.prototype.isComplete = function() { + return this.pos == this.source.length; +}; + +hterm.Parser.prototype.reset = function(source, opt_pos) { + this.source = source; + this.pos = opt_pos || 0; + this.ch = source.substr(0, 1); +}; + +/** + * Parse a key sequence. + * + * A key sequence is zero or more of the key modifiers defined in + * hterm.Parser.identifiers.modifierKeys followed by a key code. Key + * codes can be an integer or an identifier from + * hterm.Parser.identifiers.keyCodes. Modifiers and keyCodes should be joined + * by the dash character. + * + * An asterisk "*" can be used to indicate that the unspecified modifiers + * are optional. + * + * For example: + * A: Matches only an unmodified "A" character. + * 65: Same as above. + * 0x41: Same as above. + * Ctrl-A: Matches only Ctrl-A. + * Ctrl-65: Same as above. + * Ctrl-0x41: Same as above. + * Ctrl-Shift-A: Matches only Ctrl-Shift-A. + * Ctrl-*-A: Matches Ctrl-A, as well as any other key sequence that includes + * at least the Ctrl and A keys. + * + * @return {Object} An object with shift, ctrl, alt, meta, keyCode + * properties. + */ +hterm.Parser.prototype.parseKeySequence = function() { + var rv = { + keyCode: null + }; + + for (var k in hterm.Parser.identifiers.modifierKeys) { + rv[hterm.Parser.identifiers.modifierKeys[k]] = false; + } + + while (this.pos < this.source.length) { + this.skipSpace(); + + var token = this.parseToken(); + if (token.type == 'integer') { + rv.keyCode = token.value; + + } else if (token.type == 'identifier') { + var ucValue = token.value.toUpperCase(); + if (ucValue in hterm.Parser.identifiers.modifierKeys && + hterm.Parser.identifiers.modifierKeys.hasOwnProperty(ucValue)) { + var mod = hterm.Parser.identifiers.modifierKeys[ucValue]; + if (rv[mod] && rv[mod] != '*') + throw this.error('Duplicate modifier: ' + token.value); + rv[mod] = true; + + } else if (ucValue in hterm.Parser.identifiers.keyCodes && + hterm.Parser.identifiers.keyCodes.hasOwnProperty(ucValue)) { + rv.keyCode = hterm.Parser.identifiers.keyCodes[ucValue]; + + } else { + throw this.error('Unknown key: ' + token.value); + } + + } else if (token.type == 'symbol') { + if (token.value == '*') { + for (var id in hterm.Parser.identifiers.modifierKeys) { + var p = hterm.Parser.identifiers.modifierKeys[id]; + if (!rv[p]) + rv[p] = '*'; + } + } else { + throw this.error('Unexpected symbol: ' + token.value); + } + } else { + throw this.error('Expected integer or identifier'); + } + + this.skipSpace(); + + if (this.ch != '-') + break; + + if (rv.keyCode != null) + throw this.error('Extra definition after target key'); + + this.advance(1); + } + + if (rv.keyCode == null) + throw this.error('Missing target key'); + + return rv; +}; + +hterm.Parser.prototype.parseKeyAction = function() { + this.skipSpace(); + + var token = this.parseToken(); + + if (token.type == 'string') + return token.value; + + if (token.type == 'identifier') { + if (token.value in hterm.Parser.identifiers.actions && + hterm.Parser.identifiers.actions.hasOwnProperty(token.value)) + return hterm.Parser.identifiers.actions[token.value]; + + throw this.error('Unknown key action: ' + token.value); + } + + throw this.error('Expected string or identifier'); + +}; + +hterm.Parser.prototype.peekString = function() { + return this.ch == '\'' || this.ch == '"'; +}; + +hterm.Parser.prototype.peekIdentifier = function() { + return this.ch.match(/[a-z_]/i); +}; + +hterm.Parser.prototype.peekInteger = function() { + return this.ch.match(/[0-9]/); +}; + +hterm.Parser.prototype.parseToken = function() { + if (this.ch == '*') { + var rv = {type: 'symbol', value: this.ch}; + this.advance(1); + return rv; + } + + if (this.peekIdentifier()) + return {type: 'identifier', value: this.parseIdentifier()}; + + if (this.peekString()) + return {type: 'string', value: this.parseString()}; + + if (this.peekInteger()) + return {type: 'integer', value: this.parseInteger()}; + + + throw this.error('Unexpected token'); +}; + +hterm.Parser.prototype.parseIdentifier = function() { + if (!this.peekIdentifier()) + throw this.error('Expected identifier'); + + return this.parsePattern(/[a-z0-9_]+/ig); +}; + +hterm.Parser.prototype.parseInteger = function() { + var base = 10; + + if (this.ch == '0' && this.pos < this.source.length - 1 && + this.source.substr(this.pos + 1, 1) == 'x') { + return parseInt(this.parsePattern(/0x[0-9a-f]+/gi)); + } + + return parseInt(this.parsePattern(/\d+/g)); +}; + +/** + * Parse a single or double quoted string. + * + * The current position should point at the initial quote character. Single + * quoted strings will be treated literally, double quoted will process escapes. + * + * TODO(rginda): Variable interpolation. + * + * @param {ParseState} parseState + * @param {string} quote A single or double-quote character. + * @return {string} + */ +hterm.Parser.prototype.parseString = function() { + var result = ''; + + var quote = this.ch; + if (quote != '"' && quote != '\'') + throw this.error('String expected'); + + this.advance(1); + + var re = new RegExp('[\\\\' + quote + ']', 'g'); + + while (this.pos < this.source.length) { + re.lastIndex = this.pos; + if (!re.exec(this.source)) + throw this.error('Unterminated string literal'); + + result += this.source.substring(this.pos, re.lastIndex - 1); + + this.advance(re.lastIndex - this.pos - 1); + + if (quote == '"' && this.ch == '\\') { + this.advance(1); + result += this.parseEscape(); + continue; + } + + if (quote == '\'' && this.ch == '\\') { + result += this.ch; + this.advance(1); + continue; + } + + if (this.ch == quote) { + this.advance(1); + return result; + } + } + + throw this.error('Unterminated string literal'); +}; + + +/** + * Parse an escape code from the current position (which should point to + * the first character AFTER the leading backslash.) + * + * @return {string} + */ +hterm.Parser.prototype.parseEscape = function() { + var map = { + '"': '"', + '\'': '\'', + '\\': '\\', + 'a': '\x07', + 'b': '\x08', + 'e': '\x1b', + 'f': '\x0c', + 'n': '\x0a', + 'r': '\x0d', + 't': '\x09', + 'v': '\x0b', + 'x': function() { + var value = this.parsePattern(/[a-z0-9]{2}/ig); + return String.fromCharCode(parseInt(value, 16)); + }, + 'u': function() { + var value = this.parsePattern(/[a-z0-9]{4}/ig); + return String.fromCharCode(parseInt(value, 16)); + } + }; + + if (!(this.ch in map && map.hasOwnProperty(this.ch))) + throw this.error('Unknown escape: ' + this.ch); + + var value = map[this.ch]; + this.advance(1); + + if (typeof value == 'function') + value = value.call(this); + + return value; +}; + +/** + * Parse the given pattern starting from the current position. + * + * @param {RegExp} pattern A pattern representing the characters to span. MUST + * include the "global" RegExp flag. + * @return {string} + */ +hterm.Parser.prototype.parsePattern = function(pattern) { + if (!pattern.global) + throw this.error('Internal error: Span patterns must be global'); + + pattern.lastIndex = this.pos; + var ary = pattern.exec(this.source); + + if (!ary || pattern.lastIndex - ary[0].length != this.pos) + throw this.error('Expected match for: ' + pattern); + + this.pos = pattern.lastIndex - 1; + this.advance(1); + + return ary[0]; +}; + + +/** + * Advance the current position. + * + * @param {number} count + */ +hterm.Parser.prototype.advance = function(count) { + this.pos += count; + this.ch = this.source.substr(this.pos, 1); +}; + +/** + * @param {string=} opt_expect A list of valid non-whitespace characters to + * terminate on. + * @return {void} + */ +hterm.Parser.prototype.skipSpace = function(opt_expect) { + if (!/\s/.test(this.ch)) + return; + + var re = /\s+/gm; + re.lastIndex = this.pos; + + var source = this.source; + if (re.exec(source)) + this.pos = re.lastIndex; + + this.ch = this.source.substr(this.pos, 1); + + if (opt_expect) { + if (this.ch.indexOf(opt_expect) == -1) { + throw this.error('Expected one of ' + opt_expect + ', found: ' + + this.ch); + } + } +}; +// SOURCE FILE: hterm/js/hterm_parser_identifiers.js +// Copyright (c) 2015 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Collections of identifier for hterm.Parser. + */ +hterm.Parser.identifiers = {}; + +/** + * Modifier key names used when defining key sequences. + * + * These are upper case so we can normalize the user input and be forgiving. + * "CTRL-A" and "Ctrl-A" and "ctrl-a" are all accepted. + * + * Note: Names here cannot overlap with hterm.Parser.identifiers.keyCodes. + */ +hterm.Parser.identifiers.modifierKeys = { + SHIFT: 'shift', + CTRL: 'ctrl', + // Common alias. + CONTROL: 'ctrl', + ALT: 'alt', + META: 'meta' +}; + +/** + * Key codes useful when defining key sequences. + * + * Punctuation is mostly left out of this list because they can move around + * based on keyboard locale and browser. + * + * In a key sequence like "Ctrl-ESC", the ESC comes from this list of + * identifiers. It is equivalent to "Ctrl-27" and "Ctrl-0x1b". + * + * These are upper case so we can normalize the user input and be forgiving. + * "Ctrl-ESC" and "Ctrl-Esc" an "Ctrl-esc" are all accepted. + * + * We also include common aliases for the same key. "Esc" and "Escape" are the + * same key. + * + * Note: Names here cannot overlap with hterm.Parser.identifiers.modifierKeys. + */ +hterm.Parser.identifiers.keyCodes = { + // Top row. + ESCAPE: 27, + ESC: 27, + F1: 112, + F2: 113, + F3: 114, + F4: 115, + F5: 116, + F6: 117, + F7: 118, + F8: 119, + F9: 120, + F10: 121, + F11: 122, + F12: 123, + + // Row two. + ONE: 49, + TWO: 50, + THREE: 51, + FOUR: 52, + FIVE: 53, + SIX: 54, + SEVEN: 55, + EIGHT: 56, + NINE: 57, + ZERO: 48, + BACKSPACE: 8, + BKSP: 8, + BS: 8, + + // Row three. + TAB: 9, + Q: 81, + W: 87, + E: 69, + R: 82, + T: 84, + Y: 89, + U: 85, + I: 73, + O: 79, + P: 80, + + // Row four. + CAPS_LOCK: 20, + CAPSLOCK: 20, + CAPS: 20, + A: 65, + S: 83, + D: 68, + F: 70, + G: 71, + H: 72, + J: 74, + K: 75, + L: 76, + // We map enter and return together even though enter should really be 10 + // because most people don't know or care about the history here. Plus, + // most keyboards/programs map them together already. If they really want + // to bind them differently, they can also use the numeric value. + ENTER: 13, + ENT: 13, + RETURN: 13, + RET: 13, + + // Row five. + Z: 90, + X: 88, + C: 67, + V: 86, + B: 66, + N: 78, + M: 77, + + // Etc. + SPACE: 32, + SP: 32, + PRINT_SCREEN: 42, + PRTSC: 42, + SCROLL_LOCK: 145, + SCRLK: 145, + BREAK: 19, + BRK: 19, + INSERT: 45, + INS: 45, + HOME: 36, + PAGE_UP: 33, + PGUP: 33, + DELETE: 46, + DEL: 46, + END: 35, + PAGE_DOWN: 34, + PGDOWN: 34, + PGDN: 34, + UP: 38, + DOWN: 40, + RIGHT: 39, + LEFT: 37, + NUMLOCK: 144, + + // Keypad + KP0: 96, + KP1: 97, + KP2: 98, + KP3: 99, + KP4: 100, + KP5: 101, + KP6: 102, + KP7: 103, + KP8: 104, + KP9: 105, + KP_PLUS: 107, + KP_ADD: 107, + KP_MINUS: 109, + KP_SUBTRACT: 109, + KP_STAR: 106, + KP_MULTIPLY: 106, + KP_DIVIDE: 111, + KP_DECIMAL: 110, + KP_PERIOD: 110, + + // Chrome OS media keys + NAVIGATE_BACK: 166, + NAVIGATE_FORWARD: 167, + RELOAD: 168, + FULL_SCREEN: 183, + WINDOW_OVERVIEW: 182, + BRIGHTNESS_UP: 216, + BRIGHTNESS_DOWN: 217 +}; + +/** + * Identifiers for use in key actions. + */ +hterm.Parser.identifiers.actions = { + /** + * Prevent the browser and operating system from handling the event. + */ + CANCEL: hterm.Keyboard.KeyActions.CANCEL, + + /** + * Wait for a "keypress" event, send the keypress charCode to the host. + */ + DEFAULT: hterm.Keyboard.KeyActions.DEFAULT, + + /** + * Let the browser or operating system handle the key. + */ + PASS: hterm.Keyboard.KeyActions.PASS, + + /** + * Scroll the terminal one line up. + */ + scrollLineUp: function(terminal) { + terminal.scrollLineUp(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Scroll the terminal one line down. + */ + scrollLineDown: function(terminal) { + terminal.scrollLineDown(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Scroll the terminal one page up. + */ + scrollPageUp: function(terminal) { + terminal.scrollPageUp(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Scroll the terminal one page down. + */ + scrollPageDown: function(terminal) { + terminal.scrollPageDown(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Scroll the terminal to the top. + */ + scrollToTop: function(terminal) { + terminal.scrollHome(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Scroll the terminal to the bottom. + */ + scrollToBottom: function(terminal) { + terminal.scrollEnd(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Clear the active screen and move the cursor to (0,0). + */ + clearScreen: function(terminal) { + terminal.clearHome(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Clear the scrollback buffer. + */ + clearScrollback: function(terminal) { + terminal.clearScrollback(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Clear the terminal and scrollback buffer and move the cursor to (0,0). + */ + clearTerminal: function(terminal) { + terminal.wipeContents(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Perform a full terminal reset. + */ + fullReset: function(terminal) { + terminal.reset(); + return hterm.Keyboard.KeyActions.CANCEL; + }, + + /** + * Perform a soft terminal reset. + */ + softReset: function(terminal) { + terminal.softReset(); + return hterm.Keyboard.KeyActions.CANCEL; + }, +}; +// SOURCE FILE: hterm/js/hterm_preference_manager.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('lib.f', 'lib.Storage'); + +/** + * PreferenceManager subclass managing global NaSSH preferences. + * + * This is currently just an ordered list of known connection profiles. + */ +hterm.PreferenceManager = function(profileId) { + lib.PreferenceManager.call(this, hterm.defaultStorage, + hterm.PreferenceManager.prefix_ + profileId); + var defs = hterm.PreferenceManager.defaultPreferences; + Object.keys(defs).forEach(function(key) { + this.definePreference(key, defs[key][1]); + }.bind(this)); +}; + +/** + * The storage key prefix to namespace the preferences. + */ +hterm.PreferenceManager.prefix_ = '/hterm/profiles/'; + +/** + * List all the defined profiles. + * + * @param {function(Array)} callback Called with the list of profiles. + */ +hterm.PreferenceManager.listProfiles = function(callback) { + hterm.defaultStorage.getItems(null, (items) => { + const profiles = {}; + for (let key of Object.keys(items)) { + if (key.startsWith(hterm.PreferenceManager.prefix_)) { + // Turn "/hterm/profiles/foo/bar/cow" to "foo/bar/cow". + const subKey = key.slice(hterm.PreferenceManager.prefix_.length); + // Turn "foo/bar/cow" into "foo". + profiles[subKey.split('/', 1)[0]] = true; + } + } + callback(Object.keys(profiles)); + }); +}; + +hterm.PreferenceManager.categories = {}; +hterm.PreferenceManager.categories.Keyboard = 'Keyboard'; +hterm.PreferenceManager.categories.Appearance = 'Appearance'; +hterm.PreferenceManager.categories.CopyPaste = 'CopyPaste'; +hterm.PreferenceManager.categories.Sounds = 'Sounds'; +hterm.PreferenceManager.categories.Scrolling = 'Scrolling'; +hterm.PreferenceManager.categories.Encoding = 'Encoding'; +hterm.PreferenceManager.categories.Extensions = 'Extensions'; +hterm.PreferenceManager.categories.Miscellaneous = 'Miscellaneous'; + +/** + * List of categories, ordered by display order (top to bottom) + */ +hterm.PreferenceManager.categoryDefinitions = [ + { id: hterm.PreferenceManager.categories.Appearance, + text: 'Appearance (fonts, colors, images)'}, + { id: hterm.PreferenceManager.categories.CopyPaste, + text: 'Copy & Paste'}, + { id: hterm.PreferenceManager.categories.Encoding, + text: 'Encoding'}, + { id: hterm.PreferenceManager.categories.Keyboard, + text: 'Keyboard'}, + { id: hterm.PreferenceManager.categories.Scrolling, + text: 'Scrolling'}, + { id: hterm.PreferenceManager.categories.Sounds, + text: 'Sounds'}, + { id: hterm.PreferenceManager.categories.Extensions, + text: 'Extensions'}, + { id: hterm.PreferenceManager.categories.Miscellaneous, + text: 'Miscellaneous'} +]; + + +hterm.PreferenceManager.defaultPreferences = { + 'alt-gr-mode': + [hterm.PreferenceManager.categories.Keyboard, null, + [null, 'none', 'ctrl-alt', 'left-alt', 'right-alt'], + 'Select an AltGr detection heuristic.\n' + + '\n' + + '\'null\': Autodetect based on navigator.language:\n' + + ' \'en-us\' => \'none\', else => \'right-alt\'\n' + + '\'none\': Disable any AltGr related munging.\n' + + '\'ctrl-alt\': Assume Ctrl+Alt means AltGr.\n' + + '\'left-alt\': Assume left Alt means AltGr.\n' + + '\'right-alt\': Assume right Alt means AltGr.'], + + 'alt-backspace-is-meta-backspace': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'If set, undoes the Chrome OS Alt-Backspace->DEL remap, so that ' + + 'Alt-Backspace indeed is Alt-Backspace.'], + + 'alt-is-meta': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'Whether the Alt key acts as a Meta key or as a distinct Alt key.'], + + 'alt-sends-what': + [hterm.PreferenceManager.categories.Keyboard, 'escape', + ['escape', '8-bit', 'browser-key'], + 'Controls how the Alt key is handled.\n' + + '\n' + + ' escape: Send an ESC prefix.\n' + + ' 8-bit: Add 128 to the typed character as in xterm.\n' + + ' browser-key: Wait for the keypress event and see what the browser\n' + + ' says. (This won\'t work well on platforms where the browser\n' + + ' performs a default action for some Alt sequences.)' + ], + + 'audible-bell-sound': + [hterm.PreferenceManager.categories.Sounds, 'lib-resource:hterm/audio/bell', + 'url', + 'URL of the terminal bell sound. Empty string for no audible bell.'], + + 'desktop-notification-bell': + [hterm.PreferenceManager.categories.Sounds, false, 'bool', + 'If true, terminal bells in the background will create a Web ' + + 'Notification. https://www.w3.org/TR/notifications/\n' + + '\n'+ + 'Displaying notifications requires permission from the user. When this ' + + 'option is set to true, hterm will attempt to ask the user for permission ' + + 'if necessary. Browsers may not show this permission request if it was ' + + 'not triggered by a user action.\n' + + '\n' + + 'Chrome extensions with the "notifications" permission have permission to ' + + 'display notifications.'], + + 'background-color': + [hterm.PreferenceManager.categories.Appearance, 'rgb(16, 16, 16)', 'color', + 'The background color for text with no other color attributes.'], + + 'background-image': + [hterm.PreferenceManager.categories.Appearance, '', 'string', + 'CSS value of the background image. Empty string for no image.\n' + + '\n' + + 'For example:\n' + + ' url(https://goo.gl/anedTK)\n' + + ' linear-gradient(top bottom, blue, red)'], + + 'background-size': + [hterm.PreferenceManager.categories.Appearance, '', 'string', + 'CSS value of the background image size.'], + + 'background-position': + [hterm.PreferenceManager.categories.Appearance, '', 'string', + 'CSS value of the background image position.\n' + + '\n' + + 'For example:\n' + + ' 10% 10%\n' + + ' center'], + + 'backspace-sends-backspace': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'If true, the backspace should send BS (\'\\x08\', aka ^H). Otherwise ' + + 'the backspace key should send \'\\x7f\'.'], + + 'character-map-overrides': + [hterm.PreferenceManager.categories.Appearance, null, 'value', + 'This is specified as an object. It is a sparse array, where each ' + + 'property is the character set code and the value is an object that is ' + + 'a sparse array itself. In that sparse array, each property is the ' + + 'received character and the value is the displayed character.\n' + + '\n' + + 'For example:\n' + + ' {"0":{"+":"\\u2192",",":"\\u2190","-":"\\u2191",".":"\\u2193", ' + + '"0":"\\u2588"}}' + ], + + 'close-on-exit': + [hterm.PreferenceManager.categories.Miscellaneous, true, 'bool', + 'Whether to close the window when the command finishes executing.'], + + 'cursor-blink': + [hterm.PreferenceManager.categories.Appearance, false, 'bool', + 'Whether the text cursor blinks by default. This can be toggled at ' + + 'runtime via terminal escape sequences.'], + + 'cursor-blink-cycle': + [hterm.PreferenceManager.categories.Appearance, [1000, 500], 'value', + 'The text cursor blink rate in milliseconds.\n' + + '\n' + + 'A two element array, the first of which is how long the text cursor ' + + 'should be on, second is how long it should be off.'], + + 'cursor-color': + [hterm.PreferenceManager.categories.Appearance, 'rgba(255, 0, 0, 0.5)', + 'color', + 'The color of the visible text cursor.'], + + 'color-palette-overrides': + [hterm.PreferenceManager.categories.Appearance, null, 'value', + 'Override colors in the default palette.\n' + + '\n' + + 'This can be specified as an array or an object. If specified as an ' + + 'object it is assumed to be a sparse array, where each property ' + + 'is a numeric index into the color palette.\n' + + '\n' + + 'Values can be specified as almost any CSS color value. This ' + + 'includes #RGB, #RRGGBB, rgb(...), rgba(...), and any color names ' + + 'that are also part of the standard X11 rgb.txt file.\n' + + '\n' + + 'You can use \'null\' to specify that the default value should be not ' + + 'be changed. This is useful for skipping a small number of indices ' + + 'when the value is specified as an array.\n' + + '\n' + + 'For example, these both set color index 1 to blue:\n' + + ' {1: "#0000ff"}\n' + + ' [null, "#0000ff"]'], + + 'copy-on-select': + [hterm.PreferenceManager.categories.CopyPaste, true, 'bool', + 'Automatically copy mouse selection to the clipboard.'], + + 'use-default-window-copy': + [hterm.PreferenceManager.categories.CopyPaste, false, 'bool', + 'Whether to use the default browser/OS\'s copy behavior.\n' + + '\n' + + 'Allow the browser/OS to handle the copy event directly which might ' + + 'improve compatibility with some systems (where copying doesn\'t work ' + + 'at all), but makes the text selection less robust.\n' + + '\n' + + 'For example, long lines that were automatically line wrapped will ' + + 'be copied with the newlines still in them.'], + + 'clear-selection-after-copy': + [hterm.PreferenceManager.categories.CopyPaste, true, 'bool', + 'Whether to clear the selection after copying.'], + + 'ctrl-plus-minus-zero-zoom': + [hterm.PreferenceManager.categories.Keyboard, true, 'bool', + 'If true, Ctrl-Plus/Minus/Zero controls zoom.\n' + + 'If false, Ctrl-Shift-Plus/Minus/Zero controls zoom, Ctrl-Minus sends ^_, ' + + 'Ctrl-Plus/Zero do nothing.'], + + 'ctrl-c-copy': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'Ctrl-C copies if true, send ^C to host if false.\n' + + 'Ctrl-Shift-C sends ^C to host if true, copies if false.'], + + 'ctrl-v-paste': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'Ctrl-V pastes if true, send ^V to host if false.\n' + + 'Ctrl-Shift-V sends ^V to host if true, pastes if false.'], + + 'east-asian-ambiguous-as-two-column': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'Whether East Asian Ambiguous characters have two column width.'], + + 'enable-8-bit-control': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'True to enable 8-bit control characters, false to ignore them.\n' + + '\n' + + 'We\'ll respect the two-byte versions of these control characters ' + + 'regardless of this setting.'], + + 'enable-bold': + [hterm.PreferenceManager.categories.Appearance, null, 'tristate', + 'If true, use bold weight font for text with the bold/bright attribute. ' + + 'False to use the normal weight font. Null to autodetect.'], + + 'enable-bold-as-bright': + [hterm.PreferenceManager.categories.Appearance, true, 'bool', + 'If true, use bright colors (8-15 on a 16 color palette) for any text ' + + 'with the bold attribute. False otherwise.'], + + 'enable-blink': + [hterm.PreferenceManager.categories.Appearance, true, 'bool', + 'If true, respect the blink attribute. False to ignore it.'], + + 'enable-clipboard-notice': + [hterm.PreferenceManager.categories.CopyPaste, true, 'bool', + 'Whether to show a message in the terminal when the host writes to the ' + + 'clipboard.'], + + 'enable-clipboard-write': + [hterm.PreferenceManager.categories.CopyPaste, true, 'bool', + 'Allow the remote host to write directly to the local system clipboard.\n' + + 'Read access is never granted regardless of this setting.\n' + + '\n' + + 'This is used to control access to features like OSC-52.'], + + 'enable-dec12': + [hterm.PreferenceManager.categories.Miscellaneous, false, 'bool', + 'Respect the host\'s attempt to change the text cursor blink status using ' + + 'DEC Private Mode 12.'], + + 'enable-csi-j-3': + [hterm.PreferenceManager.categories.Miscellaneous, true, 'bool', + 'Whether CSI-J (Erase Display) mode 3 may clear the terminal scrollback ' + + 'buffer.\n' + + '\n' + + 'Enabling this by default is safe.'], + + 'environment': + [hterm.PreferenceManager.categories.Miscellaneous, + { + // Signal ncurses based apps to use UTF-8 output instead of legacy drawing + // modes (which only work in ISO-2022 mode). Since hterm is always UTF-8, + // this shouldn't cause problems. + 'NCURSES_NO_UTF8_ACS': '1', + 'TERM': 'xterm-256color', + // Set this env var that a bunch of mainstream terminal emulators set to + // indicate we support true colors. + // https://gist.github.com/XVilka/8346728 + 'COLORTERM': 'truecolor', + }, + 'value', + 'The initial set of environment variables, as an object.'], + + 'font-family': + [hterm.PreferenceManager.categories.Appearance, + '"DejaVu Sans Mono", "Noto Sans Mono", "Everson Mono", ' + + 'FreeMono, Menlo, Terminal, monospace', 'string', + 'Default font family for the terminal text.'], + + 'font-size': + [hterm.PreferenceManager.categories.Appearance, 15, 'int', + 'The default font size in pixels.'], + + 'font-smoothing': + [hterm.PreferenceManager.categories.Appearance, 'antialiased', 'string', + 'CSS font-smoothing property.'], + + 'foreground-color': + [hterm.PreferenceManager.categories.Appearance, 'rgb(240, 240, 240)', 'color', + 'The foreground color for text with no other color attributes.'], + + 'hide-mouse-while-typing': + [hterm.PreferenceManager.categories.Keyboard, null, 'tristate', + 'Whether to automatically hide the mouse cursor when typing. ' + + 'By default, autodetect whether the platform/OS handles this.\n' + + '\n' + + 'Note: Some operating systems may override this setting and thus you ' + + 'might not be able to always disable it.'], + + 'home-keys-scroll': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'If true, Home/End controls the terminal scrollbar and Shift-Home/' + + 'Shift-End are sent to the remote host. If false, then Home/End are ' + + 'sent to the remote host and Shift-Home/Shift-End scrolls.'], + + 'keybindings': + [hterm.PreferenceManager.categories.Keyboard, null, 'value', + 'A map of key sequence to key actions. Key sequences include zero or ' + + 'more modifier keys followed by a key code. Key codes can be decimal or ' + + 'hexadecimal numbers, or a key identifier. Key actions can be specified ' + + 'as a string to send to the host, or an action identifier. For a full ' + + 'explanation of the format, see https://goo.gl/LWRndr.\n' + + '\n' + + 'Sample keybindings:\n' + + '{\n' + + ' "Ctrl-Alt-K": "clearTerminal",\n' + + ' "Ctrl-Shift-L": "PASS",\n' + + ' "Ctrl-H": "\'Hello World\'"\n' + + '}'], + + 'media-keys-are-fkeys': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'If true, convert media keys to their Fkey equivalent. If false, let ' + + 'the browser handle the keys.'], + + 'meta-sends-escape': + [hterm.PreferenceManager.categories.Keyboard, true, 'bool', + 'Send an ESC prefix when pressing a key while holding the Meta key.\n' + + '\n' + + 'For example, when enabled, pressing Meta-K will send ^[k as if you ' + + 'typed Escape then k. When disabled, only k will be sent.'], + + 'mouse-right-click-paste': + [hterm.PreferenceManager.categories.CopyPaste, true, 'bool', + 'Paste on right mouse button clicks.\n' + + '\n' + + 'This option is independent of the "mouse-paste-button" setting.\n' + + '\n' + + 'Note: This will handle left & right handed mice correctly.'], + + 'mouse-paste-button': + [hterm.PreferenceManager.categories.CopyPaste, null, + [null, 0, 1, 2, 3, 4, 5, 6], + 'Mouse paste button, or null to autodetect.\n' + + '\n' + + 'For autodetect, we\'ll use the middle mouse button for non-X11 ' + + 'platforms (including Chrome OS). On X11, we\'ll use the right mouse ' + + 'button (since the native window manager should paste via the middle ' + + 'mouse button).\n' + + '\n' + + '0 == left (primary) button.\n' + + '1 == middle (auxiliary) button.\n' + + '2 == right (secondary) button.\n' + + '\n' + + 'This option is independent of the setting for right-click paste.\n' + + '\n' + + 'Note: This will handle left & right handed mice correctly.'], + + 'word-break-match-left': + [hterm.PreferenceManager.categories.CopyPaste, + '[^\\s\\[\\](){}<>"\'\\^!@#$%&*,;:`]', 'string', + 'Regular expression to halt matching to the left (start) of a selection.\n' + + '\n' + + 'Normally this is a character class to reject specific characters.\n' + + 'We allow "~" and "." by default as paths frequently start with those.'], + + 'word-break-match-right': + [hterm.PreferenceManager.categories.CopyPaste, + '[^\\s\\[\\](){}<>"\'\\^!@#$%&*,;:~.`]', 'string', + 'Regular expression to halt matching to the right (end) of a selection.\n' + + '\n' + + 'Normally this is a character class to reject specific characters.'], + + 'word-break-match-middle': + [hterm.PreferenceManager.categories.CopyPaste, + '[^\\s\\[\\](){}<>"\'\\^]*', 'string', + 'Regular expression to match all the characters in the middle.\n' + + '\n' + + 'Normally this is a character class to reject specific characters.\n' + + '\n' + + 'Used to expand the selection surrounding the starting point.'], + + 'page-keys-scroll': + [hterm.PreferenceManager.categories.Keyboard, false, 'bool', + 'If true, Page Up/Page Down controls the terminal scrollbar and ' + + 'Shift-Page Up/Shift-Page Down are sent to the remote host. If false, ' + + 'then Page Up/Page Down are sent to the remote host and Shift-Page Up/' + + 'Shift-Page Down scrolls.'], + + 'pass-alt-number': + [hterm.PreferenceManager.categories.Keyboard, null, 'tristate', + 'Whether Alt-1..9 is passed to the browser.\n' + + '\n' + + 'This is handy when running hterm in a browser tab, so that you don\'t ' + + 'lose Chrome\'s "switch to tab" keyboard accelerators. When not running ' + + 'in a tab it\'s better to send these keys to the host so they can be ' + + 'used in vim or emacs.\n' + + '\n' + + 'If true, Alt-1..9 will be handled by the browser. If false, Alt-1..9 ' + + 'will be sent to the host. If null, autodetect based on browser platform ' + + 'and window type.'], + + 'pass-ctrl-number': + [hterm.PreferenceManager.categories.Keyboard, null, 'tristate', + 'Whether Ctrl-1..9 is passed to the browser.\n' + + '\n' + + 'This is handy when running hterm in a browser tab, so that you don\'t ' + + 'lose Chrome\'s "switch to tab" keyboard accelerators. When not running ' + + 'in a tab it\'s better to send these keys to the host so they can be ' + + 'used in vim or emacs.\n' + + '\n' + + 'If true, Ctrl-1..9 will be handled by the browser. If false, Ctrl-1..9 ' + + 'will be sent to the host. If null, autodetect based on browser platform ' + + 'and window type.'], + + 'pass-meta-number': + [hterm.PreferenceManager.categories.Keyboard, null, 'tristate', + 'Whether Meta-1..9 is passed to the browser.\n' + + '\n' + + 'This is handy when running hterm in a browser tab, so that you don\'t ' + + 'lose Chrome\'s "switch to tab" keyboard accelerators. When not running ' + + 'in a tab it\'s better to send these keys to the host so they can be ' + + 'used in vim or emacs.\n' + + '\n' + + 'If true, Meta-1..9 will be handled by the browser. If false, Meta-1..9 ' + + 'will be sent to the host. If null, autodetect based on browser platform ' + + 'and window type.'], + + 'pass-meta-v': + [hterm.PreferenceManager.categories.Keyboard, true, 'bool', + 'Whether Meta-V gets passed to host.'], + + 'receive-encoding': + [hterm.PreferenceManager.categories.Encoding, 'utf-8', ['utf-8', 'raw'], + 'Set the expected encoding for data received from the host.\n' + + 'If the encodings do not match, visual bugs are likely to be observed.\n' + + '\n' + + 'Valid values are \'utf-8\' and \'raw\'.'], + + 'scroll-on-keystroke': + [hterm.PreferenceManager.categories.Scrolling, true, 'bool', + 'Whether to scroll to the bottom on any keystroke.'], + + 'scroll-on-output': + [hterm.PreferenceManager.categories.Scrolling, false, 'bool', + 'Whether to scroll to the bottom on terminal output.'], + + 'scrollbar-visible': + [hterm.PreferenceManager.categories.Scrolling, true, 'bool', + 'The vertical scrollbar mode.'], + + 'scroll-wheel-may-send-arrow-keys': + [hterm.PreferenceManager.categories.Scrolling, false, 'bool', + 'When using the alternative screen buffer, and DECCKM (Application Cursor ' + + 'Keys) is active, mouse wheel scroll events will emulate arrow keys.\n' + + '\n' + + 'It can be temporarily disabled by holding the Shift key.\n' + + '\n' + + 'This frequently comes up when using pagers (less) or reading man pages ' + + 'or text editors (vi/nano) or using screen/tmux.'], + + 'scroll-wheel-move-multiplier': + [hterm.PreferenceManager.categories.Scrolling, 1, 'int', + 'The multiplier for scroll wheel events when measured in pixels.\n' + + '\n' + + 'Alters how fast the page scrolls.'], + + 'send-encoding': + [hterm.PreferenceManager.categories.Encoding, 'utf-8', ['utf-8', 'raw'], + 'Set the encoding for data sent to host.'], + + 'terminal-encoding': + [hterm.PreferenceManager.categories.Encoding, 'utf-8', + ['iso-2022', 'utf-8', 'utf-8-locked'], + 'The default terminal encoding (DOCS).\n' + + '\n' + + 'ISO-2022 enables character map translations (like graphics maps).\n' + + 'UTF-8 disables support for those.\n' + + '\n' + + 'The locked variant means the encoding cannot be changed at runtime ' + + 'via terminal escape sequences.\n' + + '\n' + + 'You should stick with UTF-8 unless you notice broken rendering with ' + + 'legacy applications.'], + + 'shift-insert-paste': + [hterm.PreferenceManager.categories.Keyboard, true, 'bool', + 'Whether Shift-Insert is used for pasting or is sent to the remote host.'], + + 'user-css': + [hterm.PreferenceManager.categories.Appearance, '', 'url', + 'URL of user stylesheet to include in the terminal document.'], + + 'user-css-text': + [hterm.PreferenceManager.categories.Appearance, '', 'multiline-string', + 'Custom CSS text for styling the terminal.'], + + 'allow-images-inline': + [hterm.PreferenceManager.categories.Extensions, null, 'tristate', + 'Whether to allow the remote host to display images in the terminal.\n' + + '\n' + + 'By default, we prompt until a choice is made.'], +}; + +hterm.PreferenceManager.prototype = + Object.create(lib.PreferenceManager.prototype); +hterm.PreferenceManager.constructor = hterm.PreferenceManager; +// SOURCE FILE: hterm/js/hterm_pubsub.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * Utility class used to add publish/subscribe/unsubscribe functionality to + * an existing object. + */ +hterm.PubSub = function() { + this.observers_ = {}; +}; + +/** + * Add publish, subscribe, and unsubscribe methods to an existing object. + * + * No other properties of the object are touched, so there is no need to + * worry about clashing private properties. + * + * @param {Object} obj The object to add this behavior to. + */ +hterm.PubSub.addBehavior = function(obj) { + var pubsub = new hterm.PubSub(); + for (var m in hterm.PubSub.prototype) { + obj[m] = hterm.PubSub.prototype[m].bind(pubsub); + } +}; + +/** + * Subscribe to be notified of messages about a subject. + * + * @param {string} subject The subject to subscribe to. + * @param {function(Object)} callback The function to invoke for notifications. + */ +hterm.PubSub.prototype.subscribe = function(subject, callback) { + if (!(subject in this.observers_)) + this.observers_[subject] = []; + + this.observers_[subject].push(callback); +}; + +/** + * Unsubscribe from a subject. + * + * @param {string} subject The subject to unsubscribe from. + * @param {function(Object)} callback A callback previously registered via + * subscribe(). + */ +hterm.PubSub.prototype.unsubscribe = function(subject, callback) { + var list = this.observers_[subject]; + if (!list) + throw 'Invalid subject: ' + subject; + + var i = list.indexOf(callback); + if (i < 0) + throw 'Not subscribed: ' + subject; + + list.splice(i, 1); +}; + +/** + * Publish a message about a subject. + * + * Subscribers (and the optional final callback) are invoked asynchronously. + * This method will return before anyone is actually notified. + * + * @param {string} subject The subject to publish about. + * @param {Object} e An arbitrary object associated with this notification. + * @param {function(Object)} opt_lastCallback An optional function to call after + * all subscribers have been notified. + */ +hterm.PubSub.prototype.publish = function(subject, e, opt_lastCallback) { + function notifyList(i) { + // Set this timeout before invoking the callback, so we don't have to + // concern ourselves with exceptions. + if (i < list.length - 1) + setTimeout(notifyList, 0, i + 1); + + list[i](e); + } + + var list = this.observers_[subject]; + if (list) { + // Copy the list, in case it changes while we're notifying. + list = [].concat(list); + } + + if (opt_lastCallback) { + if (list) { + list.push(opt_lastCallback); + } else { + list = [opt_lastCallback]; + } + } + + if (list) + setTimeout(notifyList, 0, 0); +}; +// SOURCE FILE: hterm/js/hterm_screen.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('lib.f', 'lib.wc', + 'hterm.RowCol', 'hterm.Size', 'hterm.TextAttributes'); + +/** + * @fileoverview This class represents a single terminal screen full of text. + * + * It maintains the current cursor position and has basic methods for text + * insert and overwrite, and adding or removing rows from the screen. + * + * This class has no knowledge of the scrollback buffer. + * + * The number of rows on the screen is determined only by the number of rows + * that the caller inserts into the screen. If a caller wants to ensure a + * constant number of rows on the screen, it's their responsibility to remove a + * row for each row inserted. + * + * The screen width, in contrast, is enforced locally. + * + * + * In practice... + * - The hterm.Terminal class holds two hterm.Screen instances. One for the + * primary screen and one for the alternate screen. + * + * - The html.Screen class only cares that rows are HTMLElements. In the + * larger context of hterm, however, the rows happen to be displayed by an + * hterm.ScrollPort and have to follow a few rules as a result. Each + * row must be rooted by the custom HTML tag 'x-row', and each must have a + * rowIndex property that corresponds to the index of the row in the context + * of the scrollback buffer. These invariants are enforced by hterm.Terminal + * because that is the class using the hterm.Screen in the context of an + * hterm.ScrollPort. + */ + +/** + * Create a new screen instance. + * + * The screen initially has no rows and a maximum column count of 0. + * + * @param {integer} opt_columnCount The maximum number of columns for this + * screen. See insertString() and overwriteString() for information about + * what happens when too many characters are added too a row. Defaults to + * 0 if not provided. + */ +hterm.Screen = function(opt_columnCount) { + /** + * Public, read-only access to the rows in this screen. + */ + this.rowsArray = []; + + // The max column width for this screen. + this.columnCount_ = opt_columnCount || 80; + + // The current color, bold, underline and blink attributes. + this.textAttributes = new hterm.TextAttributes(window.document); + + // Current zero-based cursor coordinates. + this.cursorPosition = new hterm.RowCol(0, 0); + + // Saved state used by DECSC and related settings. This is only for saving + // and restoring specific state, not for the current/active state. + this.cursorState_ = new hterm.Screen.CursorState(this); + + // The node containing the row that the cursor is positioned on. + this.cursorRowNode_ = null; + + // The node containing the span of text that the cursor is positioned on. + this.cursorNode_ = null; + + // The offset in column width into cursorNode_ where the cursor is positioned. + this.cursorOffset_ = null; + + // Regexes for expanding word selections. + this.wordBreakMatchLeft = null; + this.wordBreakMatchRight = null; + this.wordBreakMatchMiddle = null; +}; + +/** + * Return the screen size as an hterm.Size object. + * + * @return {hterm.Size} hterm.Size object representing the current number + * of rows and columns in this screen. + */ +hterm.Screen.prototype.getSize = function() { + return new hterm.Size(this.columnCount_, this.rowsArray.length); +}; + +/** + * Return the current number of rows in this screen. + * + * @return {integer} The number of rows in this screen. + */ +hterm.Screen.prototype.getHeight = function() { + return this.rowsArray.length; +}; + +/** + * Return the current number of columns in this screen. + * + * @return {integer} The number of columns in this screen. + */ +hterm.Screen.prototype.getWidth = function() { + return this.columnCount_; +}; + +/** + * Set the maximum number of columns per row. + * + * @param {integer} count The maximum number of columns per row. + */ +hterm.Screen.prototype.setColumnCount = function(count) { + this.columnCount_ = count; + + if (this.cursorPosition.column >= count) + this.setCursorPosition(this.cursorPosition.row, count - 1); +}; + +/** + * Remove the first row from the screen and return it. + * + * @return {HTMLElement} The first row in this screen. + */ +hterm.Screen.prototype.shiftRow = function() { + return this.shiftRows(1)[0]; +}; + +/** + * Remove rows from the top of the screen and return them as an array. + * + * @param {integer} count The number of rows to remove. + * @return {Array.} The selected rows. + */ +hterm.Screen.prototype.shiftRows = function(count) { + return this.rowsArray.splice(0, count); +}; + +/** + * Insert a row at the top of the screen. + * + * @param {HTMLElement} row The row to insert. + */ +hterm.Screen.prototype.unshiftRow = function(row) { + this.rowsArray.splice(0, 0, row); +}; + +/** + * Insert rows at the top of the screen. + * + * @param {Array.} rows The rows to insert. + */ +hterm.Screen.prototype.unshiftRows = function(rows) { + this.rowsArray.unshift.apply(this.rowsArray, rows); +}; + +/** + * Remove the last row from the screen and return it. + * + * @return {HTMLElement} The last row in this screen. + */ +hterm.Screen.prototype.popRow = function() { + return this.popRows(1)[0]; +}; + +/** + * Remove rows from the bottom of the screen and return them as an array. + * + * @param {integer} count The number of rows to remove. + * @return {Array.} The selected rows. + */ +hterm.Screen.prototype.popRows = function(count) { + return this.rowsArray.splice(this.rowsArray.length - count, count); +}; + +/** + * Insert a row at the bottom of the screen. + * + * @param {HTMLElement} row The row to insert. + */ +hterm.Screen.prototype.pushRow = function(row) { + this.rowsArray.push(row); +}; + +/** + * Insert rows at the bottom of the screen. + * + * @param {Array.} rows The rows to insert. + */ +hterm.Screen.prototype.pushRows = function(rows) { + rows.push.apply(this.rowsArray, rows); +}; + +/** + * Insert a row at the specified row of the screen. + * + * @param {integer} index The index to insert the row. + * @param {HTMLElement} row The row to insert. + */ +hterm.Screen.prototype.insertRow = function(index, row) { + this.rowsArray.splice(index, 0, row); +}; + +/** + * Insert rows at the specified row of the screen. + * + * @param {integer} index The index to insert the rows. + * @param {Array.} rows The rows to insert. + */ +hterm.Screen.prototype.insertRows = function(index, rows) { + for (var i = 0; i < rows.length; i++) { + this.rowsArray.splice(index + i, 0, rows[i]); + } +}; + +/** + * Remove a row from the screen and return it. + * + * @param {integer} index The index of the row to remove. + * @return {HTMLElement} The selected row. + */ +hterm.Screen.prototype.removeRow = function(index) { + return this.rowsArray.splice(index, 1)[0]; +}; + +/** + * Remove rows from the bottom of the screen and return them as an array. + * + * @param {integer} index The index to start removing rows. + * @param {integer} count The number of rows to remove. + * @return {Array.} The selected rows. + */ +hterm.Screen.prototype.removeRows = function(index, count) { + return this.rowsArray.splice(index, count); +}; + +/** + * Invalidate the current cursor position. + * + * This sets this.cursorPosition to (0, 0) and clears out some internal + * data. + * + * Attempting to insert or overwrite text while the cursor position is invalid + * will raise an obscure exception. + */ +hterm.Screen.prototype.invalidateCursorPosition = function() { + this.cursorPosition.move(0, 0); + this.cursorRowNode_ = null; + this.cursorNode_ = null; + this.cursorOffset_ = null; +}; + +/** + * Clear the contents of the cursor row. + */ +hterm.Screen.prototype.clearCursorRow = function() { + this.cursorRowNode_.innerHTML = ''; + this.cursorRowNode_.removeAttribute('line-overflow'); + this.cursorOffset_ = 0; + this.cursorPosition.column = 0; + this.cursorPosition.overflow = false; + + var text; + if (this.textAttributes.isDefault()) { + text = ''; + } else { + text = lib.f.getWhitespace(this.columnCount_); + } + + // We shouldn't honor inverse colors when clearing an area, to match + // xterm's back color erase behavior. + var inverse = this.textAttributes.inverse; + this.textAttributes.inverse = false; + this.textAttributes.syncColors(); + + var node = this.textAttributes.createContainer(text); + this.cursorRowNode_.appendChild(node); + this.cursorNode_ = node; + + this.textAttributes.inverse = inverse; + this.textAttributes.syncColors(); +}; + +/** + * Mark the current row as having overflowed to the next line. + * + * The line overflow state is used when converting a range of rows into text. + * It makes it possible to recombine two or more overflow terminal rows into + * a single line. + * + * This is distinct from the cursor being in the overflow state. Cursor + * overflow indicates that printing at the cursor position will commit a + * line overflow, unless it is preceded by a repositioning of the cursor + * to a non-overflow state. + */ +hterm.Screen.prototype.commitLineOverflow = function() { + this.cursorRowNode_.setAttribute('line-overflow', true); +}; + +/** + * Relocate the cursor to a give row and column. + * + * @param {integer} row The zero based row. + * @param {integer} column The zero based column. + */ +hterm.Screen.prototype.setCursorPosition = function(row, column) { + if (!this.rowsArray.length) { + console.warn('Attempt to set cursor position on empty screen.'); + return; + } + + if (row >= this.rowsArray.length) { + console.error('Row out of bounds: ' + row); + row = this.rowsArray.length - 1; + } else if (row < 0) { + console.error('Row out of bounds: ' + row); + row = 0; + } + + if (column >= this.columnCount_) { + console.error('Column out of bounds: ' + column); + column = this.columnCount_ - 1; + } else if (column < 0) { + console.error('Column out of bounds: ' + column); + column = 0; + } + + this.cursorPosition.overflow = false; + + var rowNode = this.rowsArray[row]; + var node = rowNode.firstChild; + + if (!node) { + node = rowNode.ownerDocument.createTextNode(''); + rowNode.appendChild(node); + } + + var currentColumn = 0; + + if (rowNode == this.cursorRowNode_) { + if (column >= this.cursorPosition.column - this.cursorOffset_) { + node = this.cursorNode_; + currentColumn = this.cursorPosition.column - this.cursorOffset_; + } + } else { + this.cursorRowNode_ = rowNode; + } + + this.cursorPosition.move(row, column); + + while (node) { + var offset = column - currentColumn; + var width = hterm.TextAttributes.nodeWidth(node); + if (!node.nextSibling || width > offset) { + this.cursorNode_ = node; + this.cursorOffset_ = offset; + return; + } + + currentColumn += width; + node = node.nextSibling; + } +}; + +/** + * Set the provided selection object to be a caret selection at the current + * cursor position. + */ +hterm.Screen.prototype.syncSelectionCaret = function(selection) { + try { + selection.collapse(this.cursorNode_, this.cursorOffset_); + } catch (firefoxIgnoredException) { + // FF can throw an exception if the range is off, rather than just not + // performing the collapse. + } +}; + +/** + * Split a single node into two nodes at the given offset. + * + * For example: + * Given the DOM fragment '
Hello World
', call splitNode_ + * passing the span and an offset of 6. This would modify the fragment to + * become: '
Hello World
'. If the span + * had any attributes they would have been copied to the new span as well. + * + * The to-be-split node must have a container, so that the new node can be + * placed next to it. + * + * @param {HTMLNode} node The node to split. + * @param {integer} offset The offset into the node where the split should + * occur. + */ +hterm.Screen.prototype.splitNode_ = function(node, offset) { + var afterNode = node.cloneNode(false); + + var textContent = node.textContent; + node.textContent = hterm.TextAttributes.nodeSubstr(node, 0, offset); + afterNode.textContent = lib.wc.substr(textContent, offset); + + if (afterNode.textContent) + node.parentNode.insertBefore(afterNode, node.nextSibling); + if (!node.textContent) + node.parentNode.removeChild(node); +}; + +/** + * Ensure that text is clipped and the cursor is clamped to the column count. + */ +hterm.Screen.prototype.maybeClipCurrentRow = function() { + var width = hterm.TextAttributes.nodeWidth(this.cursorRowNode_); + + if (width <= this.columnCount_) { + // Current row does not need clipping, but may need clamping. + if (this.cursorPosition.column >= this.columnCount_) { + this.setCursorPosition(this.cursorPosition.row, this.columnCount_ - 1); + this.cursorPosition.overflow = true; + } + + return; + } + + // Save off the current column so we can maybe restore it later. + var currentColumn = this.cursorPosition.column; + + // Move the cursor to the final column. + this.setCursorPosition(this.cursorPosition.row, this.columnCount_ - 1); + + // Remove any text that partially overflows. + width = hterm.TextAttributes.nodeWidth(this.cursorNode_); + + if (this.cursorOffset_ < width - 1) { + this.cursorNode_.textContent = hterm.TextAttributes.nodeSubstr( + this.cursorNode_, 0, this.cursorOffset_ + 1); + } + + // Remove all nodes after the cursor. + var rowNode = this.cursorRowNode_; + var node = this.cursorNode_.nextSibling; + + while (node) { + rowNode.removeChild(node); + node = this.cursorNode_.nextSibling; + } + + if (currentColumn < this.columnCount_) { + // If the cursor was within the screen before we started then restore its + // position. + this.setCursorPosition(this.cursorPosition.row, currentColumn); + } else { + // Otherwise leave it at the the last column in the overflow state. + this.cursorPosition.overflow = true; + } +}; + +/** + * Insert a string at the current character position using the current + * text attributes. + * + * You must call maybeClipCurrentRow() after in order to clip overflowed + * text and clamp the cursor. + * + * It is also up to the caller to properly maintain the line overflow state + * using hterm.Screen..commitLineOverflow(). + */ +hterm.Screen.prototype.insertString = function(str, wcwidth=undefined) { + var cursorNode = this.cursorNode_; + var cursorNodeText = cursorNode.textContent; + + this.cursorRowNode_.removeAttribute('line-overflow'); + + // We may alter the width of the string by prepending some missing + // whitespaces, so we need to record the string width ahead of time. + if (wcwidth === undefined) + wcwidth = lib.wc.strWidth(str); + + // No matter what, before this function exits the cursor column will have + // moved this much. + this.cursorPosition.column += wcwidth; + + // Local cache of the cursor offset. + var offset = this.cursorOffset_; + + // Reverse offset is the offset measured from the end of the string. + // Zero implies that the cursor is at the end of the cursor node. + var reverseOffset = hterm.TextAttributes.nodeWidth(cursorNode) - offset; + + if (reverseOffset < 0) { + // A negative reverse offset means the cursor is positioned past the end + // of the characters on this line. We'll need to insert the missing + // whitespace. + var ws = lib.f.getWhitespace(-reverseOffset); + + // This whitespace should be completely unstyled. Underline, background + // color, and strikethrough would be visible on whitespace, so we can't use + // one of those spans to hold the text. + if (!(this.textAttributes.underline || + this.textAttributes.strikethrough || + this.textAttributes.background || + this.textAttributes.wcNode || + !this.textAttributes.asciiNode || + this.textAttributes.tileData != null)) { + // Best case scenario, we can just pretend the spaces were part of the + // original string. + str = ws + str; + } else if (cursorNode.nodeType == Node.TEXT_NODE || + !(cursorNode.wcNode || + !cursorNode.asciiNode || + cursorNode.tileNode || + cursorNode.style.textDecoration || + cursorNode.style.textDecorationStyle || + cursorNode.style.textDecorationLine || + cursorNode.style.backgroundColor)) { + // Second best case, the current node is able to hold the whitespace. + cursorNode.textContent = (cursorNodeText += ws); + } else { + // Worst case, we have to create a new node to hold the whitespace. + var wsNode = cursorNode.ownerDocument.createTextNode(ws); + this.cursorRowNode_.insertBefore(wsNode, cursorNode.nextSibling); + this.cursorNode_ = cursorNode = wsNode; + this.cursorOffset_ = offset = -reverseOffset; + cursorNodeText = ws; + } + + // We now know for sure that we're at the last character of the cursor node. + reverseOffset = 0; + } + + if (this.textAttributes.matchesContainer(cursorNode)) { + // The new text can be placed directly in the cursor node. + if (reverseOffset == 0) { + cursorNode.textContent = cursorNodeText + str; + } else if (offset == 0) { + cursorNode.textContent = str + cursorNodeText; + } else { + cursorNode.textContent = + hterm.TextAttributes.nodeSubstr(cursorNode, 0, offset) + + str + hterm.TextAttributes.nodeSubstr(cursorNode, offset); + } + + this.cursorOffset_ += wcwidth; + return; + } + + // The cursor node is the wrong style for the new text. If we're at the + // beginning or end of the cursor node, then the adjacent node is also a + // potential candidate. + + if (offset == 0) { + // At the beginning of the cursor node, the check the previous sibling. + var previousSibling = cursorNode.previousSibling; + if (previousSibling && + this.textAttributes.matchesContainer(previousSibling)) { + previousSibling.textContent += str; + this.cursorNode_ = previousSibling; + this.cursorOffset_ = lib.wc.strWidth(previousSibling.textContent); + return; + } + + var newNode = this.textAttributes.createContainer(str); + this.cursorRowNode_.insertBefore(newNode, cursorNode); + this.cursorNode_ = newNode; + this.cursorOffset_ = wcwidth; + return; + } + + if (reverseOffset == 0) { + // At the end of the cursor node, the check the next sibling. + var nextSibling = cursorNode.nextSibling; + if (nextSibling && + this.textAttributes.matchesContainer(nextSibling)) { + nextSibling.textContent = str + nextSibling.textContent; + this.cursorNode_ = nextSibling; + this.cursorOffset_ = lib.wc.strWidth(str); + return; + } + + var newNode = this.textAttributes.createContainer(str); + this.cursorRowNode_.insertBefore(newNode, nextSibling); + this.cursorNode_ = newNode; + // We specifically need to include any missing whitespace here, since it's + // going in a new node. + this.cursorOffset_ = hterm.TextAttributes.nodeWidth(newNode); + return; + } + + // Worst case, we're somewhere in the middle of the cursor node. We'll + // have to split it into two nodes and insert our new container in between. + this.splitNode_(cursorNode, offset); + var newNode = this.textAttributes.createContainer(str); + this.cursorRowNode_.insertBefore(newNode, cursorNode.nextSibling); + this.cursorNode_ = newNode; + this.cursorOffset_ = wcwidth; +}; + +/** + * Overwrite the text at the current cursor position. + * + * You must call maybeClipCurrentRow() after in order to clip overflowed + * text and clamp the cursor. + * + * It is also up to the caller to properly maintain the line overflow state + * using hterm.Screen..commitLineOverflow(). + */ +hterm.Screen.prototype.overwriteString = function(str, wcwidth=undefined) { + var maxLength = this.columnCount_ - this.cursorPosition.column; + if (!maxLength) + return [str]; + + if (wcwidth === undefined) + wcwidth = lib.wc.strWidth(str); + + if (this.textAttributes.matchesContainer(this.cursorNode_) && + this.cursorNode_.textContent.substr(this.cursorOffset_) == str) { + // This overwrite would be a no-op, just move the cursor and return. + this.cursorOffset_ += wcwidth; + this.cursorPosition.column += wcwidth; + return; + } + + this.deleteChars(Math.min(wcwidth, maxLength)); + this.insertString(str, wcwidth); +}; + +/** + * Forward-delete one or more characters at the current cursor position. + * + * Text to the right of the deleted characters is shifted left. Only affects + * characters on the same row as the cursor. + * + * @param {integer} count The column width of characters to delete. This is + * clamped to the column width minus the cursor column. + * @return {integer} The column width of the characters actually deleted. + */ +hterm.Screen.prototype.deleteChars = function(count) { + var node = this.cursorNode_; + var offset = this.cursorOffset_; + + var currentCursorColumn = this.cursorPosition.column; + count = Math.min(count, this.columnCount_ - currentCursorColumn); + if (!count) + return 0; + + var rv = count; + var startLength, endLength; + + while (node && count) { + // Sanity check so we don't loop forever, but we don't also go quietly. + if (count < 0) { + console.error(`Deleting ${rv} chars went negative: ${count}`); + break; + } + + startLength = hterm.TextAttributes.nodeWidth(node); + node.textContent = hterm.TextAttributes.nodeSubstr(node, 0, offset) + + hterm.TextAttributes.nodeSubstr(node, offset + count); + endLength = hterm.TextAttributes.nodeWidth(node); + + // Deal with splitting wide characters. There are two ways: we could delete + // the first column or the second column. In both cases, we delete the wide + // character and replace one of the columns with a space (since the other + // was deleted). If there are more chars to delete, the next loop will pick + // up the slack. + if (node.wcNode && offset < startLength && + ((endLength && startLength == endLength) || (!endLength && offset == 1))) { + // No characters were deleted when there should be. We're probably trying + // to delete one column width from a wide character node. We remove the + // wide character node here and replace it with a single space. + var spaceNode = this.textAttributes.createContainer(' '); + node.parentNode.insertBefore(spaceNode, offset ? node : node.nextSibling); + node.textContent = ''; + endLength = 0; + count -= 1; + } else + count -= startLength - endLength; + + var nextNode = node.nextSibling; + if (endLength == 0 && node != this.cursorNode_) { + node.parentNode.removeChild(node); + } + node = nextNode; + offset = 0; + } + + // Remove this.cursorNode_ if it is an empty non-text node. + if (this.cursorNode_.nodeType != Node.TEXT_NODE && + !this.cursorNode_.textContent) { + var cursorNode = this.cursorNode_; + if (cursorNode.previousSibling) { + this.cursorNode_ = cursorNode.previousSibling; + this.cursorOffset_ = hterm.TextAttributes.nodeWidth( + cursorNode.previousSibling); + } else if (cursorNode.nextSibling) { + this.cursorNode_ = cursorNode.nextSibling; + this.cursorOffset_ = 0; + } else { + var emptyNode = this.cursorRowNode_.ownerDocument.createTextNode(''); + this.cursorRowNode_.appendChild(emptyNode); + this.cursorNode_ = emptyNode; + this.cursorOffset_ = 0; + } + this.cursorRowNode_.removeChild(cursorNode); + } + + return rv; +}; + +/** + * Finds first X-ROW of a line containing specified X-ROW. + * Used to support line overflow. + * + * @param {Node} row X-ROW to begin search for first row of line. + * @return {Node} The X-ROW that is at the beginning of the line. + **/ +hterm.Screen.prototype.getLineStartRow_ = function(row) { + while (row.previousSibling && + row.previousSibling.hasAttribute('line-overflow')) { + row = row.previousSibling; + } + return row; +}; + +/** + * Gets text of a line beginning with row. + * Supports line overflow. + * + * @param {Node} row First X-ROW of line. + * @return {string} Text content of line. + **/ +hterm.Screen.prototype.getLineText_ = function(row) { + var rowText = ""; + while (row) { + rowText += row.textContent; + if (row.hasAttribute('line-overflow')) { + row = row.nextSibling; + } else { + break; + } + } + return rowText; +}; + +/** + * Returns X-ROW that is ancestor of the node. + * + * @param {Node} node Node to get X-ROW ancestor for. + * @return {Node} X-ROW ancestor of node, or null if not found. + **/ +hterm.Screen.prototype.getXRowAncestor_ = function(node) { + while (node) { + if (node.nodeName === 'X-ROW') + break; + node = node.parentNode; + } + return node; +}; + +/** + * Returns position within line of character at offset within node. + * Supports line overflow. + * + * @param {Node} row X-ROW at beginning of line. + * @param {Node} node Node to get position of. + * @param {integer} offset Offset into node. + * + * @return {integer} Position within line of character at offset within node. + **/ +hterm.Screen.prototype.getPositionWithOverflow_ = function(row, node, offset) { + if (!node) + return -1; + var ancestorRow = this.getXRowAncestor_(node); + if (!ancestorRow) + return -1; + var position = 0; + while (ancestorRow != row) { + position += hterm.TextAttributes.nodeWidth(row); + if (row.hasAttribute('line-overflow') && row.nextSibling) { + row = row.nextSibling; + } else { + return -1; + } + } + return position + this.getPositionWithinRow_(row, node, offset); +}; + +/** + * Returns position within row of character at offset within node. + * Does not support line overflow. + * + * @param {Node} row X-ROW to get position within. + * @param {Node} node Node to get position for. + * @param {integer} offset Offset within node to get position for. + * @return {integer} Position within row of character at offset within node. + **/ +hterm.Screen.prototype.getPositionWithinRow_ = function(row, node, offset) { + if (node.parentNode != row) { + // If we traversed to the top node, then there's nothing to find here. + if (node.parentNode == null) + return -1; + + return this.getPositionWithinRow_(node.parentNode, node, offset) + + this.getPositionWithinRow_(row, node.parentNode, 0); + } + var position = 0; + for (var i = 0; i < row.childNodes.length; i++) { + var currentNode = row.childNodes[i]; + if (currentNode == node) + return position + offset; + position += hterm.TextAttributes.nodeWidth(currentNode); + } + return -1; +}; + +/** + * Returns the node and offset corresponding to position within line. + * Supports line overflow. + * + * @param {Node} row X-ROW at beginning of line. + * @param {integer} position Position within line to retrieve node and offset. + * @return {Array} Two element array containing node and offset respectively. + **/ +hterm.Screen.prototype.getNodeAndOffsetWithOverflow_ = function(row, position) { + while (row && position > hterm.TextAttributes.nodeWidth(row)) { + if (row.hasAttribute('line-overflow') && row.nextSibling) { + position -= hterm.TextAttributes.nodeWidth(row); + row = row.nextSibling; + } else { + return -1; + } + } + return this.getNodeAndOffsetWithinRow_(row, position); +}; + +/** + * Returns the node and offset corresponding to position within row. + * Does not support line overflow. + * + * @param {Node} row X-ROW to get position within. + * @param {integer} position Position within row to retrieve node and offset. + * @return {Array} Two element array containing node and offset respectively. + **/ +hterm.Screen.prototype.getNodeAndOffsetWithinRow_ = function(row, position) { + for (var i = 0; i < row.childNodes.length; i++) { + var node = row.childNodes[i]; + var nodeTextWidth = hterm.TextAttributes.nodeWidth(node); + if (position <= nodeTextWidth) { + if (node.nodeName === 'SPAN') { + /** Drill down to node contained by SPAN. **/ + return this.getNodeAndOffsetWithinRow_(node, position); + } else { + return [node, position]; + } + } + position -= nodeTextWidth; + } + return null; +}; + +/** + * Returns the node and offset corresponding to position within line. + * Supports line overflow. + * + * @param {Node} row X-ROW at beginning of line. + * @param {integer} start Start position of range within line. + * @param {integer} end End position of range within line. + * @param {Range} range Range to modify. + **/ +hterm.Screen.prototype.setRange_ = function(row, start, end, range) { + var startNodeAndOffset = this.getNodeAndOffsetWithOverflow_(row, start); + if (startNodeAndOffset == null) + return; + var endNodeAndOffset = this.getNodeAndOffsetWithOverflow_(row, end); + if (endNodeAndOffset == null) + return; + range.setStart(startNodeAndOffset[0], startNodeAndOffset[1]); + range.setEnd(endNodeAndOffset[0], endNodeAndOffset[1]); +}; + +/** + * Expands selection to surrounding string with word break matches. + * + * @param {Selection} selection Selection to expand. + * @param {string} leftMatch left word break match. + * @param {string} rightMatch right word break match. + * @param {string} insideMatch inside word break match. + */ +hterm.Screen.prototype.expandSelectionWithWordBreakMatches_ = + function(selection, leftMatch, rightMatch, insideMatch) { + if (!selection) + return; + + var range = selection.getRangeAt(0); + if (!range || range.toString().match(/\s/)) + return; + + const rowElement = this.getXRowAncestor_(range.startContainer); + if (!rowElement) + return; + const row = this.getLineStartRow_(rowElement); + if (!row) + return; + + var startPosition = this.getPositionWithOverflow_(row, + range.startContainer, + range.startOffset); + if (startPosition == -1) + return; + var endPosition = this.getPositionWithOverflow_(row, + range.endContainer, + range.endOffset); + if (endPosition == -1) + return; + + //Move start to the left. + var rowText = this.getLineText_(row); + var lineUpToRange = lib.wc.substring(rowText, 0, endPosition); + var leftRegularExpression = new RegExp(leftMatch + insideMatch + "$"); + var expandedStart = lineUpToRange.search(leftRegularExpression); + if (expandedStart == -1 || expandedStart > startPosition) + return; + + //Move end to the right. + var lineFromRange = lib.wc.substring(rowText, startPosition, + lib.wc.strWidth(rowText)); + var rightRegularExpression = new RegExp("^" + insideMatch + rightMatch); + var found = lineFromRange.match(rightRegularExpression); + if (!found) + return; + var expandedEnd = startPosition + lib.wc.strWidth(found[0]); + if (expandedEnd == -1 || expandedEnd < endPosition) + return; + + this.setRange_(row, expandedStart, expandedEnd, range); + selection.addRange(range); +}; + +/** + * Expands selection to surrounding string using the user's settings. + * + * @param {Selection} selection Selection to expand. + */ +hterm.Screen.prototype.expandSelection = function(selection) { + this.expandSelectionWithWordBreakMatches_( + selection, + this.wordBreakMatchLeft, + this.wordBreakMatchRight, + this.wordBreakMatchMiddle); +}; + +/** + * Expands selection to surrounding URL using a set of fixed match settings. + * + * @param {Selection} selection Selection to expand. + */ +hterm.Screen.prototype.expandSelectionForUrl = function(selection) { + this.expandSelectionWithWordBreakMatches_( + selection, + "[^\\s\\[\\](){}<>\"'\\^!@#$%&*,;:`]", + "[^\\s\\[\\](){}<>\"'\\^!@#$%&*,;:~.`]", + "[^\\s\\[\\](){}<>\"'\\^]*"); +}; + +/** + * Save the current cursor state to the corresponding screens. + * + * @param {hterm.VT} vt The VT object to read graphic codeset details from. + */ +hterm.Screen.prototype.saveCursorAndState = function(vt) { + this.cursorState_.save(vt); +}; + +/** + * Restore the saved cursor state in the corresponding screens. + * + * @param {hterm.VT} vt The VT object to write graphic codeset details to. + */ +hterm.Screen.prototype.restoreCursorAndState = function(vt) { + this.cursorState_.restore(vt); +}; + +/** + * Track all the things related to the current "cursor". + * + * The set of things saved & restored here is defined by DEC: + * https://vt100.net/docs/vt510-rm/DECSC.html + * - Cursor position + * - Character attributes set by the SGR command + * - Character sets (G0, G1, G2, or G3) currently in GL and GR + * - Wrap flag (autowrap or no autowrap) + * - State of origin mode (DECOM) + * - Selective erase attribute + * - Any single shift 2 (SS2) or single shift 3 (SS3) functions sent + * + * These are done on a per-screen basis. + */ +hterm.Screen.CursorState = function(screen) { + this.screen_ = screen; + this.cursor = null; + this.textAttributes = null; + this.GL = this.GR = this.G0 = this.G1 = this.G2 = this.G3 = null; +}; + +/** + * Save all the cursor state. + * + * @param {hterm.VT} vt The VT object to read graphic codeset details from. + */ +hterm.Screen.CursorState.prototype.save = function(vt) { + this.cursor = vt.terminal.saveCursor(); + + this.textAttributes = this.screen_.textAttributes.clone(); + + this.GL = vt.GL; + this.GR = vt.GR; + + this.G0 = vt.G0; + this.G1 = vt.G1; + this.G2 = vt.G2; + this.G3 = vt.G3; +}; + +/** + * Restore the previously saved cursor state. + * + * @param {hterm.VT} vt The VT object to write graphic codeset details to. + */ +hterm.Screen.CursorState.prototype.restore = function(vt) { + vt.terminal.restoreCursor(this.cursor); + + // Cursor restore includes char attributes (bold/etc...), but does not change + // the color palette (which are a terminal setting). + const tattrs = this.textAttributes.clone(); + tattrs.colorPalette = this.screen_.textAttributes.colorPalette; + tattrs.syncColors(); + + this.screen_.textAttributes = tattrs; + + vt.GL = this.GL; + vt.GR = this.GR; + + vt.G0 = this.G0; + vt.G1 = this.G1; + vt.G2 = this.G2; + vt.G3 = this.G3; +}; +// SOURCE FILE: hterm/js/hterm_scrollport.js +// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +lib.rtdep('lib.f', 'hterm.PubSub', 'hterm.Size'); + +/** + * A 'viewport' view of fixed-height rows with support for selection and + * copy-to-clipboard. + * + * 'Viewport' in this case means that only the visible rows are in the DOM. + * If the rowProvider has 100,000 rows, but the ScrollPort is only 25 rows + * tall, then only 25 dom nodes are created. The ScrollPort will ask the + * RowProvider to create new visible rows on demand as they are scrolled in + * to the visible area. + * + * This viewport is designed so that select and copy-to-clipboard still works, + * even when all or part of the selection is scrolled off screen. + * + * Note that the X11 mouse clipboard does not work properly when all or part + * of the selection is off screen. It would be difficult to fix this without + * adding significant overhead to pathologically large selection cases. + * + * The RowProvider should return rows rooted by the custom tag name 'x-row'. + * This ensures that we can quickly assign the correct display height + * to the rows with css. + * + * @param {RowProvider} rowProvider An object capable of providing rows as + * raw text or row nodes. + */ +hterm.ScrollPort = function(rowProvider) { + hterm.PubSub.addBehavior(this); + + this.rowProvider_ = rowProvider; + + // SWAG the character size until we can measure it. + this.characterSize = new hterm.Size(10, 10); + + // DOM node used for character measurement. + this.ruler_ = null; + + this.selection = new hterm.ScrollPort.Selection(this); + + // A map of rowIndex => rowNode for each row that is drawn as part of a + // pending redraw_() call. Null if there is no pending redraw_ call. + this.currentRowNodeCache_ = null; + + // A map of rowIndex => rowNode for each row that was drawn as part of the + // previous redraw_() call. + this.previousRowNodeCache_ = {}; + + // Used during scroll events to detect when the underlying cause is a resize. + this.lastScreenWidth_ = null; + this.lastScreenHeight_ = null; + + // True if the user should be allowed to select text in the terminal. + // This is disabled when the host requests mouse drag events so that we don't + // end up with two notions of selection. + this.selectionEnabled_ = true; + + // The last row count returned by the row provider, re-populated during + // syncScrollHeight(). + this.lastRowCount_ = 0; + + // The scroll wheel pixel delta multiplier to increase/decrease + // the scroll speed of mouse wheel events. See: https://goo.gl/sXelnq + this.scrollWheelMultiplier_ = 1; + + // The last touch events we saw to support touch based scrolling. Indexed + // by touch identifier since we can have more than one touch active. + this.lastTouch_ = {}; + + /** + * True if the last scroll caused the scrollport to show the final row. + */ + this.isScrolledEnd = true; + + /** + * A guess at the current scrollbar width, fixed in resize(). + */ + this.currentScrollbarWidthPx = 16; + + /** + * Whether the ctrl-v key on the screen should paste. + */ + this.ctrlVPaste = false; + + this.div_ = null; + this.document_ = null; + + // Collection of active timeout handles. + this.timeouts_ = {}; + + this.observers_ = {}; + + this.DEBUG_ = false; +}; + +/** + * Proxy for the native selection object which understands how to walk up the + * DOM to find the containing row node and sort out which comes first. + * + * @param {hterm.ScrollPort} scrollPort The parent hterm.ScrollPort instance. + */ +hterm.ScrollPort.Selection = function(scrollPort) { + this.scrollPort_ = scrollPort; + + /** + * The row containing the start of the selection. + * + * This may be partially or fully selected. It may be the selection anchor + * or the focus, but its rowIndex is guaranteed to be less-than-or-equal-to + * that of the endRow. + * + * If only one row is selected then startRow == endRow. If there is no + * selection or the selection is collapsed then startRow == null. + */ + this.startRow = null; + + /** + * The row containing the end of the selection. + * + * This may be partially or fully selected. It may be the selection anchor + * or the focus, but its rowIndex is guaranteed to be greater-than-or-equal-to + * that of the startRow. + * + * If only one row is selected then startRow == endRow. If there is no + * selection or the selection is collapsed then startRow == null. + */ + this.endRow = null; + + /** + * True if startRow != endRow. + */ + this.isMultiline = null; + + /** + * True if the selection is just a point rather than a range. + */ + this.isCollapsed = null; +}; + +/** + * Given a list of DOM nodes and a container, return the DOM node that + * is first according to a depth-first search. + * + * Returns null if none of the children are found. + */ +hterm.ScrollPort.Selection.prototype.findFirstChild = function( + parent, childAry) { + var node = parent.firstChild; + + while (node) { + if (childAry.indexOf(node) != -1) + return node; + + if (node.childNodes.length) { + var rv = this.findFirstChild(node, childAry); + if (rv) + return rv; + } + + node = node.nextSibling; + } + + return null; +}; + +/** + * Synchronize this object with the current DOM selection. + * + * This is a one-way synchronization, the DOM selection is copied to this + * object, not the other way around. + */ +hterm.ScrollPort.Selection.prototype.sync = function() { + var self = this; + + // The dom selection object has no way to tell which nodes come first in + // the document, so we have to figure that out. + // + // This function is used when we detect that the "anchor" node is first. + function anchorFirst() { + self.startRow = anchorRow; + self.startNode = selection.anchorNode; + self.startOffset = selection.anchorOffset; + self.endRow = focusRow; + self.endNode = selection.focusNode; + self.endOffset = selection.focusOffset; + } + + // This function is used when we detect that the "focus" node is first. + function focusFirst() { + self.startRow = focusRow; + self.startNode = selection.focusNode; + self.startOffset = selection.focusOffset; + self.endRow = anchorRow; + self.endNode = selection.anchorNode; + self.endOffset = selection.anchorOffset; + } + + var selection = this.scrollPort_.getDocument().getSelection(); + + this.startRow = null; + this.endRow = null; + this.isMultiline = null; + this.isCollapsed = !selection || selection.isCollapsed; + + if (!selection) { + return; + } + + // Usually collapsed selections wouldn't be interesting, however screen + // readers will set a collapsed selection as they navigate through the DOM. + // It is important to preserve these nodes in the DOM as scrolling happens + // so that screen reader navigation isn't cleared. + const accessibilityEnabled = this.scrollPort_.accessibilityReader_ && + this.scrollPort_.accessibilityReader_.accessibilityEnabled; + if (this.isCollapsed && !accessibilityEnabled) { + return; + } + + var anchorRow = selection.anchorNode; + while (anchorRow && anchorRow.nodeName != 'X-ROW') { + anchorRow = anchorRow.parentNode; + } + + if (!anchorRow) { + // Don't set a selection if it's not a row node that's selected. + return; + } + + var focusRow = selection.focusNode; + while (focusRow && focusRow.nodeName != 'X-ROW') { + focusRow = focusRow.parentNode; + } + + if (!focusRow) { + // Don't set a selection if it's not a row node that's selected. + return; + } + + if (anchorRow.rowIndex < focusRow.rowIndex) { + anchorFirst(); + + } else if (anchorRow.rowIndex > focusRow.rowIndex) { + focusFirst(); + + } else if (selection.focusNode == selection.anchorNode) { + if (selection.anchorOffset < selection.focusOffset) { + anchorFirst(); + } else { + focusFirst(); + } + + } else { + // The selection starts and ends in the same row, but isn't contained all + // in a single node. + var firstNode = this.findFirstChild( + anchorRow, [selection.anchorNode, selection.focusNode]); + + if (!firstNode) + throw new Error('Unexpected error syncing selection.'); + + if (firstNode == selection.anchorNode) { + anchorFirst(); + } else { + focusFirst(); + } + } + + this.isMultiline = anchorRow.rowIndex != focusRow.rowIndex; +}; + + +/** + * Turn a div into this hterm.ScrollPort. + */ +hterm.ScrollPort.prototype.decorate = function(div) { + this.div_ = div; + + this.iframe_ = div.ownerDocument.createElement('iframe'); + this.iframe_.style.cssText = ( + 'border: 0;' + + 'height: 100%;' + + 'position: absolute;' + + 'width: 100%'); + + // Set the iframe src to # in FF. Otherwise when the frame's + // load event fires in FF it clears out the content of the iframe. + if ('mozInnerScreenX' in window) // detect a FF only property + this.iframe_.src = '#'; + + div.appendChild(this.iframe_); + + this.iframe_.contentWindow.addEventListener('resize', + this.onResize_.bind(this)); + + var doc = this.document_ = this.iframe_.contentDocument; + doc.body.style.cssText = ( + 'margin: 0px;' + + 'padding: 0px;' + + 'height: 100%;' + + 'width: 100%;' + + 'overflow: hidden;' + + 'cursor: var(--hterm-mouse-cursor-style);' + + '-webkit-user-select: none;' + + '-moz-user-select: none;'); + + const metaCharset = doc.createElement('meta'); + metaCharset.setAttribute('charset', 'utf-8'); + doc.head.appendChild(metaCharset); + + if (this.DEBUG_) { + // When we're debugging we add padding to the body so that the offscreen + // elements are visible. + this.document_.body.style.paddingTop = + this.document_.body.style.paddingBottom = + 'calc(var(--hterm-charsize-height) * 3)'; + } + + var style = doc.createElement('style'); + + // Hide rows that are above or below the x-fold elements. This is necessary to + // ensure that these rows aren't visible to a screen reader. First hide all + // rows that are children of the . Then display the nodes that are + // after the top fold. Then rehide nodes that are after the bottom fold. + style.textContent = ` + x-row { + display: block; + height: var(--hterm-charsize-height); + line-height: var(--hterm-charsize-height); + } + + x-screen x-row { + visibility: hidden; + } + + #hterm\\:top-fold-for-row-selection ~ x-row { + visibility: visible; + } + + #hterm\\:bottom-fold-for-row-selection ~ x-row { + visibility: hidden; + }`; + doc.head.appendChild(style); + + this.userCssLink_ = doc.createElement('link'); + this.userCssLink_.setAttribute('rel', 'stylesheet'); + + this.userCssText_ = doc.createElement('style'); + doc.head.appendChild(this.userCssText_); + + // TODO(rginda): Sorry, this 'screen_' isn't the same thing as hterm.Screen + // from screen.js. I need to pick a better name for one of them to avoid + // the collision. + // We make this field editable even though we don't actually allow anything + // to be edited here so that Chrome will do the right thing with virtual + // keyboards and IMEs. But make sure we turn off all the input helper logic + // that doesn't make sense here, and might inadvertently mung or save input. + // Some of these attributes are standard while others are browser specific, + // but should be safely ignored by other browsers. + this.screen_ = doc.createElement('x-screen'); + this.screen_.setAttribute('contenteditable', 'true'); + this.screen_.setAttribute('spellcheck', 'false'); + this.screen_.setAttribute('autocomplete', 'off'); + this.screen_.setAttribute('autocorrect', 'off'); + this.screen_.setAttribute('autocapitalize', 'none'); + + // In some ways the terminal behaves like a text box but not in all ways. It + // is not editable in the same ways a text box is editable and the content we + // want to be read out by a screen reader does not always align with the edits + // (selection changes) that happen in the terminal window. Use the log role so + // that the screen reader doesn't treat it like a text box and announce all + // selection changes. The announcements that we want spoken are generated + // by a separate live region, which gives more control over what will be + // spoken. + this.screen_.setAttribute('role', 'log'); + this.screen_.setAttribute('aria-live', 'off'); + this.screen_.setAttribute('aria-roledescription', 'Terminal'); + + // Set aria-readonly to indicate to the screen reader that the text on the + // screen is not modifiable by the html cursor. It may be modifiable by + // sending input to the application running in the terminal, but this is + // orthogonal to the DOM's notion of modifiable. + this.screen_.setAttribute('aria-readonly', 'true'); + this.screen_.setAttribute('tabindex', '-1'); + this.screen_.style.cssText = ( + 'caret-color: transparent;' + + 'display: block;' + + 'font-family: monospace;' + + 'font-size: 15px;' + + 'font-variant-ligatures: none;' + + 'height: 100%;' + + 'overflow-y: scroll; overflow-x: hidden;' + + 'white-space: pre;' + + 'width: 100%;' + + 'outline: none !important'); + + doc.body.appendChild(this.screen_); + + this.screen_.addEventListener('scroll', this.onScroll_.bind(this)); + this.screen_.addEventListener('wheel', this.onScrollWheel_.bind(this)); + this.screen_.addEventListener('touchstart', this.onTouch_.bind(this)); + this.screen_.addEventListener('touchmove', this.onTouch_.bind(this)); + this.screen_.addEventListener('touchend', this.onTouch_.bind(this)); + this.screen_.addEventListener('touchcancel', this.onTouch_.bind(this)); + this.screen_.addEventListener('copy', this.onCopy_.bind(this)); + this.screen_.addEventListener('paste', this.onPaste_.bind(this)); + this.screen_.addEventListener('drop', this.onDragAndDrop_.bind(this)); + + doc.body.addEventListener('keydown', this.onBodyKeyDown_.bind(this)); + + // Add buttons to make accessible scrolling through terminal history work + // well. These are positioned off-screen until they are selected, at which + // point they are moved on-screen. + const scrollButtonHeight = 30; + const scrollButtonBorder = 1; + const scrollButtonTotalHeight = scrollButtonHeight + 2 * scrollButtonBorder; + const scrollButtonStyle = `right: 0px; + position:fixed; + z-index: 1; + text-align: center; + cursor: pointer; + height: ${scrollButtonHeight}px; + width: 110px; + line-height: ${scrollButtonHeight}px; + border-width: ${scrollButtonBorder}px; + border-style: solid; + font-weight: bold;`; + // Note: we use a
rather than a