[yt-svn] commit/yt: 16 new changesets
commits-noreply at bitbucket.org
commits-noreply at bitbucket.org
Thu Aug 27 09:16:23 PDT 2015
16 new commits in yt:
https://bitbucket.org/yt_analysis/yt/commits/8b7eea5eb8ab/
Changeset: 8b7eea5eb8ab
Branch: yt
User: ngoldbaum
Date: 2015-08-24 16:46:18+00:00
Summary: Removing PWViewerExtJS
Affected #: 1 file
diff -r 0d479d8c21a4557c8fc17329c0171ff6dec4e8e8 -r 8b7eea5eb8ab7de87e02ec2f76450e6fa44ecfe7 yt/visualization/plot_window.py
--- a/yt/visualization/plot_window.py
+++ b/yt/visualization/plot_window.py
@@ -1670,259 +1670,6 @@
def _recreate_frb(self):
super(OffAxisProjectionPlot, self)._recreate_frb()
-
-_metadata_template = """
-%(ds)s<br>
-<br>
-Field of View: %(x_width)0.3f %(axes_unit_names)s<br>
-Minimum Value: %(mi)0.3e %(colorbar_unit)s<br>
-Maximum Value: %(ma)0.3e %(colorbar_unit)s<br>
-Central Point: (data coords)<br>
- %(xc)0.14f<br>
- %(yc)0.14f<br>
- %(zc)0.14f
-"""
-
-class PWViewerExtJS(PlotWindow):
- """A viewer for the web interface.
-
- """
- _ext_widget_id = None
- _current_field = None
- _widget_name = "plot_window"
- _frb_generator = FixedResolutionBuffer
- _contour_info = None
- _vector_info = None
-
- def _setup_plots(self):
- from yt.gui.reason.bottle_mods import PayloadHandler
- ph = PayloadHandler()
- if self._current_field is not None \
- and self._ext_widget_id is not None:
- fields = [self._current_field]
- addl_keys = {'type': 'widget_payload',
- 'widget_id': self._ext_widget_id}
- else:
- fields = self.frb.data.keys()
- addl_keys = {}
- if self._colorbar_valid is False:
- addl_keys['colorbar_image'] = self._get_cbar_image()
- self._colorbar_valid = True
- min_zoom = 200*self.ds.index.get_smallest_dx() * self.ds['unitary']
- for field in fields:
- to_plot = apply_colormap(self.frb[field],
- func = self._field_transform[field],
- cmap_name = self._colormaps[field])
- pngs = self._apply_modifications(to_plot)
- img_data = base64.b64encode(pngs)
- # We scale the width between 200*min_dx and 1.0
- x_width = self.xlim[1] - self.xlim[0]
- zoom_fac = np.log10(x_width*self.ds['unitary'])/np.log10(min_zoom)
- zoom_fac = 100.0*max(0.0, zoom_fac)
- ticks = self.get_ticks(field)
- payload = {'type':'png_string',
- 'image_data':img_data,
- 'metadata_string': self.get_metadata(field),
- 'zoom': zoom_fac,
- 'ticks': ticks}
- payload.update(addl_keys)
- ph.add_payload(payload)
-
- def _apply_modifications(self, img):
- if self._contour_info is None and self._vector_info is None:
- return write_png_to_string(img)
- from matplotlib.figure import Figure
-
- vi, vj, vn = img.shape
-
- # Now we need to get our field values
- fig = Figure((vi/100.0, vj/100.0), dpi = 100)
- fig.figimage(img)
- # Add our contour
- ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False)
- ax.patch.set_alpha(0.0)
-
- # Now apply our modifications
- self._apply_contours(ax, vi, vj)
- self._apply_vectors(ax, vi, vj)
-
- canvas = FigureCanvasAgg(fig)
- f = StringIO()
- canvas.print_figure(f)
- f.seek(0)
- img = f.read()
- return img
-
- def _apply_contours(self, ax, vi, vj):
- if self._contour_info is None: return
- plot_args = {}
- field, number, colors, logit = self._contour_info
- if colors is not None: plot_args['colors'] = colors
-
- raw_data = self.frb.data_source
- b = self.frb.bounds
- xi, yi = np.mgrid[b[0]:b[1]:(vi / 8) * 1j,
- b[2]:b[3]:(vj / 8) * 1j]
- x = raw_data['px']
- y = raw_data['py']
- z = raw_data[field]
- if logit: z = np.log10(z)
- if LooseVersion(matplotlib.__version__) < LooseVersion("1.4.0"):
- from matplotlib.delaunay.triangulate import Triangulation as triang
- fvals = triang(x,y).nn_interpolator(z)(xi,yi).transpose()[::-1,:]
- else:
- from matplotlib.tri import Triangulation, LinearTriInterpolator
- t = Triangulation(x, y)
- fvals = LinearTriInterpolator(t, z)(xi, yi).transpose()[::-1,:]
-
- ax.contour(fvals, number, colors='w')
-
- def _apply_vectors(self, ax, vi, vj):
- if self._vector_info is None: return
- skip, scale = self._vector_info
-
- nx = self.frb.buff_size[0]/skip
- ny = self.frb.buff_size[1]/skip
- new_frb = FixedResolutionBuffer(self.frb.data_source,
- self.frb.bounds, (nx,ny))
-
- axis = self.frb.data_source.axis
- xax = self.frb.data_source.ds.coordinates.x_axis[axis]
- yax = self.frb.data_source.ds.coordinates.y_axis[axis]
- axis_names = self.frb.data_source.ds.coordinates.axis_name
- fx = "velocity_%s" % (axis_names[xax])
- fy = "velocity_%x" % (axis_names[yax])
- px = new_frb[fx][::-1,:]
- py = new_frb[fy][::-1,:]
- x = np.mgrid[0:vi-1:ny*1j]
- y = np.mgrid[0:vj-1:nx*1j]
- # Always normalize, then we scale
- nn = ((px**2.0 + py**2.0)**0.5).max()
- px /= nn
- py /= nn
- print(scale, px.min(), px.max(), py.min(), py.max())
- ax.quiver(x, y, px, py, scale=float(vi)/skip)
-
- def get_ticks(self, field, height = 400):
- # This will eventually change to work with non-logged fields
- ticks = []
- transform = self._field_transform[field]
- mi, ma = self.frb[field].min(), self.frb[field].max()
- tick_locs = transform.ticks(mi, ma)
- mi, ma = transform((mi, ma))
- for v1,v2 in zip(tick_locs, transform(tick_locs)):
- if v2 < mi or v2 > ma: continue
- p = height - height * (v2 - mi)/(ma - mi)
- ticks.append((p,v1,v2))
- return ticks
-
- def _get_cbar_image(self, height = 400, width = 40, field = None):
- if field is None: field = self._current_field
- cmap_name = self._colormaps[field]
- vals = np.mgrid[1:0:height * 1j] * np.ones(width)[:,None]
- vals = vals.transpose()
- to_plot = apply_colormap(vals, cmap_name = cmap_name)
- pngs = write_png_to_string(to_plot)
- img_data = base64.b64encode(pngs)
- return img_data
-
- # This calls an invalidation routine from within
- def scroll_zoom(self, value):
- # We accept value from 0..100, and assume it has been set from the
- # scroll bar. In that case, we undo the logic for calcualting
- # 'zoom_fac' from above.
- min_val = 200*self.ds.index.get_smallest_dx()
- unit = self.ds['unitary']
- width = (min_val**(value/100.0))/unit
- self.set_width(width)
-
- def image_recenter(self, img_x, img_y, img_size_x, img_size_y):
- dx = (self.xlim[1] - self.xlim[0]) / img_size_x
- dy = (self.ylim[1] - self.ylim[0]) / img_size_y
- new_x = img_x * dx + self.xlim[0]
- new_y = img_y * dy + self.ylim[0]
- print(img_x, img_y, dx, dy, new_x, new_y)
- self.set_center((new_x, new_y))
-
- def get_field_units(self, field, strip_mathml = True):
- source = self.data_source
- field = self._check_field(field)
- finfo = source.ds._get_field_info(*field)
- if source._type_name in ("slice", "cutting"):
- units = finfo.get_units()
- elif source._type_name == "proj":
- if source.weight_field is not None or source.method in ("mip", "sum"):
- units = finfo.get_units()
- else:
- units = finfo.get_projected_units()
- else:
- units = ""
- if strip_mathml:
- units = units.replace(r"\rm{", "").replace("}","")
- return units
-
- def get_metadata(self, field, strip_mathml = True, return_string = True):
- fval = self.frb[field]
- mi = fval.min()
- ma = fval.max()
- x_width = self.xlim[1] - self.xlim[0]
- y_width = self.ylim[1] - self.ylim[0]
- if self._axes_unit_names is None:
- unit = self.ds.get_smallest_appropriate_unit(x_width)
- unit = (unit, unit)
- else:
- unit = self._axes_unit_names
- units = self.get_field_units(field, strip_mathml)
- center = getattr(self.frb.data_source, "center", None)
- xax = self.ds.coordinates.x_axis[self.frb.axis]
- yax = self.ds.coordinates.y_axis[self.frb.axis]
- if center is None or self.frb.axis == 4:
- xc, yc, zc = -999, -999, -999
- else:
- center[xax] = 0.5 * (
- self.xlim[0] + self.xlim[1])
- center[yax] = 0.5 * (
- self.ylim[0] + self.ylim[1])
- xc, yc, zc = center
- if return_string:
- md = _metadata_template % dict(
- ds = self.ds,
- x_width = x_width*self.ds[unit[0]],
- y_width = y_width*self.ds[unit[1]],
- axes_unit_names = unit[0], colorbar_unit = units,
- mi = mi, ma = ma, xc = xc, yc = yc, zc = zc)
- else:
- md = dict(ds = self.ds,
- x_width = x_width*self.ds[unit[0]],
- y_width = y_width*self.ds[unit[1]],
- axes_unit_names = unit, colorbar_unit = units,
- mi = mi, ma = ma, xc = xc, yc = yc, zc = zc)
- return md
-
- @invalidate_plot
- def set_contour_info(self, field_name, n_cont = 8, colors = None,
- logit = True):
- if field_name == "None" or n_cont == 0:
- self._contour_info = None
- return
- self._contour_info = (field_name, n_cont, colors, logit)
-
- @invalidate_plot
- def set_vector_info(self, skip, scale = 1):
- self._vector_info = (skip, scale)
-
- @invalidate_data
- def set_current_field(self, field):
- field = self._check_field(field)
- self._current_field = field
- self.frb[field]
- finfo = self.data_source.ds._get_field_info(*field)
- if finfo.take_log:
- self._field_transform[field] = log_transform
- else:
- self._field_transform[field] = linear_transform
-
-
class WindowPlotMPL(ImagePlotMPL):
"""A container for a single PlotWindow matplotlib figure and axes"""
def __init__(self, data, cbname, cblinthresh, cmap, extent, zlim, figure_size,
https://bitbucket.org/yt_analysis/yt/commits/ccca8a7d48aa/
Changeset: ccca8a7d48aa
Branch: yt
User: ngoldbaum
Date: 2015-08-24 16:46:43+00:00
Summary: Remove reference to ExtProgressBar from yt.funcs
Affected #: 1 file
diff -r 8b7eea5eb8ab7de87e02ec2f76450e6fa44ecfe7 -r ccca8a7d48aac586758088a82c3c5e041995ccc6 yt/funcs.py
--- a/yt/funcs.py
+++ b/yt/funcs.py
@@ -367,9 +367,6 @@
"__IPYTHON__" in dir(builtins) or \
ytcfg.getboolean("yt", "__withintesting"):
return DummyProgressBar()
- elif ytcfg.getboolean("yt", "__withinreason"):
- from yt.gui.reason.extdirect_repl import ExtProgressBar
- return ExtProgressBar(title, maxval)
elif ytcfg.getboolean("yt", "__parallel"):
return ParallelProgressBar(title, maxval)
widgets = [ title,
https://bitbucket.org/yt_analysis/yt/commits/e0672a66cb31/
Changeset: e0672a66cb31
Branch: yt
User: ngoldbaum
Date: 2015-08-24 16:47:01+00:00
Summary: Remove __withinreason configuration parameter
Affected #: 1 file
diff -r ccca8a7d48aac586758088a82c3c5e041995ccc6 -r e0672a66cb3113520e5007ad8b5ed097c9debd1e yt/config.py
--- a/yt/config.py
+++ b/yt/config.py
@@ -30,7 +30,6 @@
loglevel = '20',
inline = 'False',
numthreads = '-1',
- __withinreason = 'False',
__withintesting = 'False',
__parallel = 'False',
__global_parallel_rank = '0',
https://bitbucket.org/yt_analysis/yt/commits/6f844749fdac/
Changeset: 6f844749fdac
Branch: yt
User: ngoldbaum
Date: 2015-08-24 16:47:10+00:00
Summary: Remove pyro_queue.py script
Affected #: 1 file
diff -r e0672a66cb3113520e5007ad8b5ed097c9debd1e -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e scripts/pyro_queue.py
--- a/scripts/pyro_queue.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from yt.config import ytcfg;ytcfg["yt","__withinreason"]="True"
-import os
-import Pyro4
-import uuid
-
-from yt.mods import *
-from yt.utilities.parallel_tools.parallel_analysis_interface import \
- _get_comm
-from yt.gui.reason.pyro_queue import \
- PyroQueueRoot, \
- PyroQueueNonRoot
-
-comm = _get_comm(())
-my_rank = comm.comm.rank
-
-if my_rank == 0:
- my_q = PyroQueueRoot(comm)
- Pyro4.config.HMAC_KEY = uuid.uuid4().hex
- key_file = 'reason.key'
- fd = os.open(key_file, os.O_CREAT, 0600)
- os.close(fd)
- out_file = file(key_file, 'w')
- out_file.write("HMAC KEY: %s\n" % Pyro4.config.HMAC_KEY)
- out_file.close()
- mylog.info('See %s for HMAC key.', key_file)
- Pyro4.Daemon.serveSimple(
- {my_q: "yt.executor"},
- ns=False, verbose=True)
-else:
- my_q = PyroQueueNonRoot(comm)
- my_q.run()
https://bitbucket.org/yt_analysis/yt/commits/105458124524/
Changeset: 105458124524
Branch: yt
User: ngoldbaum
Date: 2015-08-24 18:03:56+00:00
Summary: Move pannable map out of reason and into yt.visualization
Affected #: 208 files
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/bottle_mods.py
--- a/yt/gui/reason/bottle_mods.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""
-Modifications and extensions to Bottle, to make it slightly more useful for
-yt's purposes
-
-
-
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import uuid
-import json
-import logging, threading
-import sys
-from yt.extern.six.moves import urllib
-import numpy as np
-
-from yt.extern.bottle import \
- server_names, debug, route, run, request, ServerAdapter, response
-from .extdirect_router import DirectRouter, DirectProviderDefinition
-from yt.utilities.logger import ytLogger as mylog
-from yt.funcs import *
-
-route_functions = {}
-route_watchers = []
-payloads = []
-
-def preroute(future_route, *args, **kwargs):
- def router(func):
- route_functions[future_route] = (args, kwargs, func)
- return func
- return router
-
-def notify_route(watcher):
- route_watchers.append(watcher)
-
-class BinaryDelivery(object):
- delivered = False
- payload = ""
- def __init__(self, payload, name = ""):
- self.name = name
- self.payload = payload
- #sys.__stderr__.write("CREATING A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
-
- def get(self):
- # We set our
- #sys.__stderr__.write("REQUESTED A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
- p = self.payload
- if p == "":
- response.status = 404
- return
- self.payload = ""
- return p
-
-class PayloadHandler(object):
- _shared_state = {}
- payloads = None
- binary_payloads = None
- recorded_payloads = None
- multicast_ids = None
- multicast_payloads = None
- lock = None
- record = False
- event = None
- count = 0
- debug = False
- _prefix = ""
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.payloads is None: self.payloads = []
- if self.lock is None: self.lock = threading.Lock()
- if self.recorded_payloads is None: self.recorded_payloads = []
- if self.event is None: self.event = threading.Event()
- if self.multicast_payloads is None: self.multicast_payloads = {}
- if self.multicast_ids is None: self.multicast_ids = {}
- if self.binary_payloads is None: self.binary_payloads = []
-
- def deliver_payloads(self):
- with self.lock:
- payloads = self.payloads
- if self.record:
- self.recorded_payloads += self.payloads
- if self.debug:
- sys.__stderr__.write("**** Delivering %s payloads\n" % (len(payloads)))
- for p in payloads:
- sys.__stderr__.write("**** %s\n" % p['type'])
- self.payloads = []
- self.event.clear()
- try:
- self.deliver_multicast()
- except Exception as exc:
- sys.__stderr__.write("%s" % exc)
- return payloads
-
- def add_payload(self, to_add):
- with self.lock:
- if "binary" in to_add:
- self._add_binary_payload(to_add)
- self.payloads.append(to_add)
- # Does this next part need to be in the lock?
- if to_add.get("widget_id", None) in self.multicast_ids:
- self.multicast_payloads[to_add["widget_id"]] = to_add
- self.count += 1
- self.event.set()
- if self.debug:
- sys.__stderr__.write("**** Adding payload of type %s\n" % (to_add['type']))
-
- def _add_binary_payload(self, bp):
- # This shouldn't be called by anybody other than add_payload.
- bkeys = ensure_list(bp['binary'])
- bp['binary'] = []
- for bkey in bkeys:
- bdata = bp.pop(bkey) # Get the binary data
- if isinstance(bdata, np.ndarray):
- bdata = bdata.tostring()
- bpserver = BinaryDelivery(bdata, bkey)
- self.binary_payloads.append(bpserver)
- uu = uuid.uuid4().hex
- bp['binary'].append((bkey, uu))
- route("%s/%s" % (self._prefix, uu))(bpserver.get)
- if self.debug:
- sys.__stderr__.write(
- "**** Adding binary payload (%s) to %s\n" % (bkey, uu))
-
- def replay_payloads(self):
- return self.recorded_payloads
-
- def widget_payload(self, widget, data):
- data['type'] = 'widget_payload'
- data['widget_id'] = widget._ext_widget_id
- self.add_payload(data)
-
- def deliver_multicast(self):
- for widget_id in self.multicast_payloads:
- if widget_id not in self.multicast_payloads: continue
- server_id, session_token = self.multicast_ids[widget_id]
- # Now we execute a post to the correct location
- data = urllib.parse.urlencode({
- 'payload_session_id': server_id,
- 'payload_session_token': session_token,
- 'payload_data': self.multicast_payloads[widget_id],
- 'payload_metadata': {}
- })
- urllib.request.urlopen("http://localhost:8080/UpdatePayload", data = data)
-
-class YTRocketServer(ServerAdapter):
- server_info = {} # Hack to get back at instance vars
- def run(self, handler):
- from yt.extern.rocket import Rocket
- server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
- self.server_info[id(self)] = server
- server.start()
-
-class BottleDirectRouter(DirectRouter):
- # This class implements a mechanism for auto-routing an ExtDirect-callable
- # object through Bottle. It should be used as a base class of an object,
- # and the __init__ function will need to include the keyword argument
- # 'route' for it to work.
- _route_prefix = None
- def __init__(self, *args, **kwargs):
- future_route = self.api_url
- super(BottleDirectRouter, self).__init__(*args, **kwargs)
- self.__name__ = str(self.my_name)
- route_functions[future_route] = ((), {'method':("POST", "GET")}, self)
- preroute("/resources/ext-%s-api.js" % self.api_url, method="GET")(self._myapi)
- notify_route(self)
-
- def _myapi(self):
- dpd = DirectProviderDefinition(self, self.api_url, ns="yt_rpc")
- source = "Ext.Direct.addProvider(%s);" % json.dumps(dpd._config())
- response.headers['Content-Type'] = "text/javascript"
- return source
-
- def __call__(self):
- #print "Hi there, I just got this request:",
- val = request.body.read()
- #print val
- #import pdb;pdb.set_trace()
- rv = super(BottleDirectRouter, self).__call__(val)
- #print "With this response:", rv
- return rv
-
-def uuid_serve_functions(pre_routed = None, open_browser=False, port=9099,
- repl = None, token = None):
- if pre_routed == None: pre_routed = route_functions
- debug(mode=True)
- if token is None: token = uuid.uuid1()
- for r in pre_routed:
- args, kwargs, f = pre_routed[r]
- if r[0] == "/": r = r[1:]
- rp = "/%s/%s" % (token, r)
- func_name = getattr(f, 'func_name', str(f))
- print("Routing from %s => %s" % (rp, func_name))
- route(rp, *args, **kwargs)(f)
- for w in route_watchers:
- if not hasattr(w, "_route_prefix"):
- print("WARNING: %s has no _route_prefix attribute. Not notifying.")
- continue
- w._route_prefix = token
- repl._global_token = token
- repl.activate()
- repl.execution_thread.wait()
- print()
- print()
- print("=============================================================================")
- print("=============================================================================")
- print("Greetings, and welcome to Reason!")
- print("Your private token is %s ." % token)
- print("DO NOT SHARE THIS TOKEN.")
- print()
- print("Please direct your browser to:")
- print()
- print(" http://localhost:%s/%s/" % (port, token))
- print()
- print("=============================================================================")
- print()
- print("If you are currently ssh'd into a remote machine, you should be able")
- print("to create a new SSH tunnel by typing or copy/pasting this text")
- print("verbatim, while waiting to see the 'ssh>' prompt after the first line.")
- print()
- print("~C")
- print("-L%s:localhost:%s" % (port, port))
- print()
- print("and then pointing a web browser on your local machine to the above URL.")
- print()
- print("=============================================================================")
- print("=============================================================================")
- print()
- print()
- if open_browser:
- # We do some fancy footwork so that we can open the browser while the
- # server starts up. I got this from some recipe whose URL escapes me.
- # Thank you, to whoever wrote it!
- def local_browse():
- """Start a browser after waiting for half a second."""
- import webbrowser, threading
- def _local_browse():
- webbrowser.open('http://localhost:%s/%s/' % (port, token))
- thread = threading.Timer(0.5, _local_browse)
- thread.start()
- local_browse()
- try:
- import yt.extern.rocket as rocket
- server_type = YTRocketServer
- log = logging.getLogger('Rocket')
- log.setLevel(logging.WARNING)
- kwargs = {'timeout': 600, 'max_threads': 2}
- if repl is not None:
- repl.server = YTRocketServer.server_info
- except ImportError:
- server_type = server_names.get("wsgiref")
- kwargs = {}
- server = server_type(host='localhost', port=port, **kwargs)
- mylog.info("Starting up the server.")
- run(server=server)
-
-class MethodLock(object):
- _shared_state = {}
- locks = None
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.locks is None: self.locks = {}
-
- def __call__(self, func):
- if str(func) not in self.locks:
- self.locks[str(func)] = threading.Lock()
- @wraps(func)
- def locker(*args, **kwargs):
- print("Acquiring lock on %s" % (str(func)))
- with self.locks[str(func)]:
- rv = func(*args, **kwargs)
- print("Regained lock on %s" % (str(func)))
- return rv
- return locker
-
-lockit = MethodLock()
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/extdirect_router.py
--- a/yt/gui/reason/extdirect_router.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""
-This is code from the extdirect package:
-
-http://pypi.python.org/pypi/extdirect/0.3
-https://github.com/iancmcc/extdirect
-
-written by Ian McCracken
-
-This code was released under the BSD License.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-import inspect
-
-class DirectException(Exception):
- pass
-
-
-try:
- import json
-except ImportError:
- try:
- import simplejson as json
- except ImportError:
- raise DirectException("No JSON library available. Please install"
- " simplejson or upgrade to Python 2.6.")
-
-
-class DirectRouter(object):
- """
- Basic Ext.Direct router class.
-
- Ext.Direct allows one to create an API that communicates with a single URL,
- which then routes requests to the appropriate method. The client-side API
- object matches the server-side API object.
-
- This base class parses an Ext.Direct request, which contains the name of
- the method and any data that should be passed, and routes the data to the
- approriate method. It then receives the output of that call and puts it
- into the data structure expected by Ext.Direct.
-
- Call an instance of this class with the JSON from an Ext.Direct request.
- """
- exception_handler = None
- def __call__(self, body):
- """
- """
- # Decode the request data
- body = json.loads(body)
- self._body = body
-
- if isinstance(body, list):
- directRequests = body
- elif isinstance(body, dict):
- directRequests = [body]
- else:
- raise DirectException("Body is not a support type: %s" % body)
-
- responses = []
-
- for req in directRequests:
- responses.append(self._doRequest(req))
-
- if len(responses) == 1:
- responses = responses[0]
-
- return json.dumps(responses)
-
- def _doRequest(self, request):
-
- # Double-check that this request is meant for this class
- action = request.get('action')
- clsname = self.__class__.__name__
- if action != clsname:
- raise DirectException(("Action specified in request ('%s') is"
- " not named %s.") % (action, clsname))
-
- # Pull out the method name and make sure it exists on this class
- method = request.get('method')
- if not method:
- raise DirectException("No method specified. Is this a valid"
- " Ext.Direct request?")
- try:
- _targetfn = getattr(self, method)
- except AttributeError:
- raise DirectException("'%s' is not the name of a method on %s" % (
- method, clsname
- ))
-
- # Pull out any arguments. Sent as an array containing a hash map, so
- # get the first member.
- data = request.get('data')
- if not data:
- data = {}
- else:
- data = data[0]
-
- # Cast all keys as strings, in case of encoding or other wrinkles
- data = dict((str(k), v) for k,v in data.iteritems())
- self._data = data
-
- # Finally, call the target method, passing in the data
- try:
- result = _targetfn(**data)
- except Exception as e:
- if self.exception_handler is not None:
- result = self.exception_handler(e)
- else:
- raise e
-
- return {
- 'type':'rpc',
- 'tid': request['tid'],
- 'action': action,
- 'method': method,
- 'result': result
- }
-
-
-class DirectProviderDefinition(object):
- """
- Turns a L{DirectRouter} subclass into JavaScript object representing the
- config of the client-side API.
-
- Inspects the given subclass and retrieves the names of all public methods,
- then defines those as actions on the Ext.Direct provider, and creates the
- JS that adds the provider.
-
- See http://extjs.com/products/extjs/direct.php for a full explanation of
- protocols and features of Ext.Direct.
- """
- def __init__(self, routercls, url, ns=None, timeout=None):
- """
- @param routercls: A L{DirectRouter} subclass
- @type routercls: class
- @param url: The url at which C{routercls} is available
- @type url: str
- @param ns: The client-side namespace in which the provider should live.
- The provider will be available at [ns].[routercls.__name__].
- For example, if ns is 'Zenoss.remote' and routercls is named
- 'EventConsole', client-side code would call
- C{Zenoss.remote.EventConsole.my_method(params, callback)}.
- """
- self.routercls = routercls
- self.url = url
- self.ns = ns
- self.timeout = timeout
-
- def _config(self):
- actions = []
- for name, value in inspect.getmembers(self.routercls):
- if name.startswith("_"):
- continue
- if inspect.ismethod(value):
-
- ## Update this when extdirect doesn't freak out when you specify
- ## actual lens (we're passing them all in as a single dict, so
- ## from the perspective of Ext.Direct they are all len 1)
- #args = inspect.getargspec(value)[0]
- #args.remove('self')
- #arglen = len(args)
- arglen = 1
-
- actions.append({'name':name, 'len':arglen})
- config = {
- 'id': self.routercls.__name__,
- 'type': 'remoting',
- 'url': self.url,
- 'actions': {
- self.routercls.__name__: actions
- }
- }
- if self.timeout:
- config['timeout'] = self.timeout
- if self.ns:
- config['namespace'] = self.ns
- return config
-
- def render(self):
- """
- Generate and return an Ext.Direct provider definition, wrapped in a
- <script> tag and ready for inclusion in an HTML document.
- """
- config = self._config()
- source = "Ext.Direct.addProvider(%s);" % json.dumps(config)
- return '<script type="text/javascript"> %s </script>' % source.strip()
-
-
-
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app.js
--- a/yt/gui/reason/html/app.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/**********************************************************************
-The main GUI facility for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.Loader.setConfig({enabled:true});
-
-var reason, rdebug, examine;
-
-Ext.application({
- requires: ['Ext.container.Viewport',
- 'Reason.view.LoggingGrid',
- 'Reason.view.DataObjectTree',
- 'Reason.controller.widgets.SampleWidget',
- ],
- name: 'Reason',
-
- appFolder: 'reason/app',
-
- launch: function() {
- reason = this;
- this.numberOfRequests = 0;
- rdebug = this.getController("Debugger");
- this.server = this.getController("ServerCommunication");
- Ext.create('Ext.container.Viewport', {
- layout: 'border',
- items: [
- {
- xtype: 'logginggrid',
- autofill: true,
- region: 'south',
- id: "status-region",
- cls: "status-logger",
- split: true,
- height: 100,
- maxSize: 200,
- collapsible: true,
- title: 'Status',
- margins: '0 0 0 0',
- }, {
- id: 'west-panel',
- region: 'west',
- split: true,
- width: 200,
- minSize: 175,
- maxSize: 400,
- collapsible: true,
- layout: {
- type: 'vbox',
- pack: 'start',
- align: 'stretch',
- },
- items: [
- { xtype: 'dataobjecttree',
- flex: 1.0},
- { xtype: 'panel',
- tpl: 'Pending Requests: {0}',
- data: [0],
- height: 30,
- id: 'pending',
- }
- ],
- }, {
- xtype: 'tabpanel',
- region: 'center',
- id: 'center-panel',
- activeTab: 0,
- dockedItems: [ {
- dock: 'top',
- xtype: 'mainmenu',
- } ],
- items: [
- { xtype: 'panel',
- title: 'Welcome!',
- closeable: true,
- autoLoad: 'help.html',
- },
- { xtype: 'ytnotebook' },
- ]
- }
- ]
- });
- this.pending = Ext.getCmp("pending");
- this.fireEvent("allowinput");
- },
- controllers : [
- 'Logging',
- 'DataObjects',
- 'Notebook',
- 'ServerCommunication',
- 'WidgetDirector',
- 'MenuActions',
- 'Debugger',
- 'FileOpen',
- ],
-
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/DataObjects.js
--- a/yt/gui/reason/html/app/controller/DataObjects.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/**********************************************************************
-Data object controller for Reason
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-***********************************************************************/
-
-Ext.define('Reason.controller.DataObjects', {
- extend: 'Ext.app.Controller',
- stores: [ 'DataObjects' ],
- models: ['DataObject'],
- view: ['DataObjectTree'],
- refs: [
- { ref: 'dataObjectTree',
- selector: 'dataobjecttree#dataobjects',
- xtype: 'dataobjecttree',
- itemId: 'dataobjects',
- autoCreate: true,
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloaddataobjects : {fn: this.refreshDataObjects, scope: this},
- });
- this.control({
- "#dataobjects": { itemcontextmenu:
- function(view, rec, node, index, e) {
- e.preventDefault();
- this.application.fireEvent("showwidgets", rec, e);
- }
- }});
- this.callParent(arguments);
- },
-
- refreshDataObjects: function(payload) {
- /*console.log("Refreshing data objects");*/
- var objs = payload['objs'];
- var root = this.getDataObjectsStore().getRootNode();
- root.removeAll();
- var pf;
- Ext.each(objs, function(o, i, os) {
- /*console.log("Appending " + o['name']);*/
- pf = root.appendChild({
- name: o.name,
- type: o.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: o.varname,
- leaf: false,
- expanded: true,
- iconCls: 'pf_icon'
- });
- Ext.each(o['children'], function(c, ci, cs) {
- /*console.log(" Appending " + c['name']);*/
- pf.appendChild({name: c.name,
- type: c.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: c.varname,
- leaf: true,
- iconcls: 'data_obj'});
-
- });
- });
- },
-});
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/Debugger.js
--- a/yt/gui/reason/html/app/controller/Debugger.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**********************************************************************
-Debug helper for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Debugger', {
- extend: 'Ext.app.Controller',
- stores: ['WidgetTypes', 'WidgetInstances', 'Requests'],
-
- getWidget: function(widgetId) {
- this.getWidgetInstancesStore().find(
- {'widgetid': widgetId});
- var widgetInfo = this.getWidgetInstancesStore().getAt(resultId).data;
- return widgetInfo.widget;
- },
-
- getAllWidgetsByType: function(typeName) {
- var arr = []
- this.getWidgetInstancesStore().each(function(r) {
- if (r.data['widgettype'] == typeName) {
- arr.push(r.data);
- }
- });
- return arr;
- },
-
-});
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/FileOpen.js
--- a/yt/gui/reason/html/app/controller/FileOpen.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/**********************************************************************
-File Open Dialog for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.FileOpen', {
- extend: 'Ext.app.Controller',
- stores: ['FileListing'],
- requires: ["Reason.view.FileOpen"],
-
- init: function() {
-
- },
-
- openDialog: function() {
- this.currentDirectory = '',
- this.getFileListingStore().removeAll();
- reason.server.method("file_listing",
- {base_dir:"", sub_dir:""}, this.fillStore);
- this.win = Ext.widget("fileopenwindow");
- this.win.query("#file_listing")[0].bindStore(this.getFileListingStore());
- /* Set up our handlers */
- this.control({
- '#current_file': { specialkey: this.specialKeyPressed, },
- '#file_listing': { celldblclick: this.doubleClicked, },
- '#load': { click: this.loadFile, },
- '#cancel': { click: this.cancelWindow, }
- });
- this.win.show();
- },
-
- specialKeyPressed: function(f, e) {
- if (e.getKey() != e.ENTER) { return; }
- reason.server.method("file_listing",
- {base_dir:f.getValue(), sub_dir:""}, this.fillStore);
- },
-
- doubleClicked: function(view, td, cellIndex, record) {
- conf = {'base_dir': this.currentDirectory};
- if (record.data.type == 'directory') {
- conf['sub_dir'] = record.data.filename;
- reason.server.method('file_listing', conf, this.fillStore);
- } else {
- conf['filename'] = record.data.filename;
- reason.server.method('load', conf);
- this.win.destroy();
- }
- },
-
- loadFile: function(b, e) {
- var conf = {filename: '', base_dir: this.currentDirectory};
- var fl = this.win.query("#file_listing")[0];
- var idx = fl.getSelectionModel().getSelection();
- if (idx == 1) {
- conf['filename'] = this.getFileListingStore().getAt(idx).data.filename;
- }
- reason.server.method('load', conf);
- },
-
- cancelWindow: function(b, e) {
- this.win.destroy();
- },
-
- fillStore: function(f, a) {
- var con = reason.getController("FileOpen");
- if(a.status == false){
- Ext.Msg.alert("Error", "Something has gone wrong.");
- con.window.destroy();
- }
- if(a.result['change'] == false) {
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- return;
- }
- con.getFileListingStore().removeAll();
- var rec = [];
- con.getFileListingStore().loadData(a.result['objs']);
- con.currentDirectory = a.result['cur_dir'];
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- },
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/Logging.js
--- a/yt/gui/reason/html/app/controller/Logging.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**********************************************************************
-Logging entry controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Logging', {
- extend: 'Ext.app.Controller',
- stores: [ 'LogEntries' ],
- view: ['LoggingGrid'],
-
- refs: [
- { ref: 'logEntries',
- selector: '#logentries'
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadlogentry: {fn: this.addLogPayload, scope: this},
- logentry: {fn: this.addLogEntry, scope: this},
- });
- },
-
- addLogPayload: function(payload) {
- this.addLogEntry(payload['log_entry']);
- },
-
- addLogEntry: function(text) {
- this.getLogEntriesStore().add({record: text});
- var i = this.getLogEntriesStore().getCount();
- this.getLogEntries().getView().focusRow(i - 1);
- },
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/MenuActions.js
--- a/yt/gui/reason/html/app/controller/MenuActions.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**********************************************************************
-Menu actions in Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-
-Ext.define('Reason.controller.MenuActions', {
- extend: 'Ext.app.Controller',
- views: ['MainMenu'],
-
- init: function() {
- this.control({
- '#openfile': { click: this.openFile },
- '#savescript': { click: this.saveScript},
- '#downloadscript': { click: this.downloadScript },
- '#pastebinscript': { click: this.pastebinScript },
- '#ytchat': {click: this.openIRCChannel },
- '#quit': {click: this.quitReason },
- '#enabledebug': {click: this.enableDebug },
- });
- this.callParent(arguments);
- },
-
- saveScript: function (b,e) {
- /* This function gets called on success */
- var controller = this;
- function handleResponse(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Saved session to ' + a.result['filename'];
- Ext.Msg.alert('Success!', alert_text);
- controller.application.fireEvent("logentry", alert_text);
- } else {
- Ext.Msg.alert('Always naysaying!',
- 'Failed to save to ' + a.result['filename'] + '<br>Error: ' +
- a.result['error']);
- }
- };
- /* Now we prompt */
- Ext.Msg.prompt("We have important work to do.", "Enter filename.",
- function(btn, text) {
- if (btn == 'ok') {
- reason.server.method('save_session',
- {filename:text}, handleResponse);
- }
- }
- );
- },
-
- openFile: function(b, e) {
- this.application.getController("FileOpen").openDialog();
- },
-
- downloadScript: function(b, e) {
- window.open("session.py", "_top");
- this.application.fireEvent("logentry", 'Saved session locally.')
- },
-
- pastebinScript: function(b, e) {
- reason.server.method('paste_session', {}, function(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Pasted session to:<br>' +
- a.result['site']
- var alert_text_rec = 'Pasted session to: ' +
- a.result['site']
- Ext.Msg.alert('Pastebin', alert_text);
- this.application.fireEvent("logentry", alert_text_rec);
- }
- });
- },
-
- openIRCChannel: function(b, e) {
- window.open("http://yt-project.org/irc.html", "_new");
- },
-
- quitReason: function(b, e) {
- this.application.fireEvent("stopheartbeat");
- reason.server.method('shutdown', {}, function(f, a) {
- Ext.Msg.alert("Goodbye!", "Goodbye from Reason!", function() {
- window.open("http://www.google.com/", "_top");});});
- },
-
- enableDebug: function() {
- this.application.fireEvent("enabledebug");
- },
-});
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/Notebook.js
--- a/yt/gui/reason/html/app/controller/Notebook.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/**********************************************************************
-Notebook controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Notebook', {
- extend: 'Ext.app.Controller',
- stores: [ 'CellValues' , 'Requests'],
- views: ['Notebook', 'CellView'],
- refs: [
- { ref: 'inputLine',
- selector: '#inputline'
- },
- { ref: 'cellDisplay',
- selector: 'notebookcells#cells',
- xtype: 'notebookcells',
- autoCreate: true,
- itemId: 'cells',
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadcell: {fn: this.addCell, scope: this},
- payloadscript: {fn: this.loadScript, scope: this},
- executecell: {fn: this.executeCell, scope: this},
- wipeinput: {fn: this.wipeInputLine, scope: this},
- blockinput: {fn: this.blockInput, scope: this},
- allowinput: {fn: this.allowInput, scope: this},
- scrolltobottom: {fn: this.scrollToBottom, scope: this},
- })
- this.control({
- '#executecellbutton': {
- click: function(f, e) {
- this.executeCell(this.getInputLine().getValue());
- }
- },
- '#inputline': {
- specialkey: function(field, e, opts){
- if (e.shiftKey && e.getKey() == e.ENTER) {
- this.executeCell(field.getValue());
- }
- },
- },
- });
- this.callParent(arguments);
- },
-
- addRequest: function(request_id, command) {
- /*console.log("Adding request " + request_id);*/
- this.getRequestsStore().add({
- request_id: request_id, command: command,
- });
- reason.pending.update([this.getRequestsStore().count()]);
- },
-
- addCell: function(cell) {
- this.application.fireEvent("wipeinput");
- this.application.fireEvent("allowinput");
- if (cell['result_id'] != null) {
- var ind = this.getRequestsStore().find(
- 'request_id', cell['result_id']);
- if (ind != -1) {
- /*console.log("Removing request " + cell['result_id']);*/
- var rec = this.getRequestsStore().removeAt(ind);
- }
- reason.pending.update([this.getRequestsStore().count()]);
- }
- if (cell['hide'] == true) { return; }
- this.getCellValuesStore().add({
- input: cell['input'],
- output: cell['output'],
- raw_input: cell['raw_input'],
- image_data: cell['image_data'],
- executiontime: cell['executiontime'],
- result_id: cell['result_id'],
- });
- this.application.fireEvent("scrolltobottom");
- },
-
- loadScript: function(payload) {
- this.getInputLine().setValue(payload['value']);
- this.getInputLine()._lock = true;
- },
-
- executeCell: function(line) {
- this.application.fireEvent("blockinput");
- reason.server.execute(line, false);
- },
-
- scrollToBottom: function() {
- var i = this.getCellValuesStore().getCount();
- this.getCellDisplay().getView().focusRow(i-1);
- },
-
- wipeInputLine: function() {
- if(this.getInputLine()._lock == true) {
- this.getInputLine()._lock = false;
- } else {
- this.getInputLine().setValue("");
- }
- },
-
- blockInput: function() {
- this.getInputLine().addClass("cell_waiting");
- this.getInputLine().setReadOnly(true);
- },
-
- allowInput: function() {
- this.getInputLine().removeCls("cell_waiting");
- this.getInputLine().setReadOnly(false);
- var application = this.application;
- },
-
-});
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/ServerCommunication.js
--- a/yt/gui/reason/html/app/controller/ServerCommunication.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/**********************************************************************
-The Payload handling facility for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-var heartbeatRequest = false;
-
-Ext.define('Reason.controller.ServerCommunication', {
- extend: 'Ext.app.Controller',
- stores: ['Payloads'],
- views: ['PayloadGrid'],
- requires: ['Reason.view.MulticastSetup', 'Reason.view.RequestsGrid'],
-
- init: function() {
- this.application.addListener({
- payloadreceived: {fn: this.handlePayload, scope: this},
- stopheartbeat: {fn: this.stopHeartbeat, scope: this},
- enabledebug: {fn: this.enableDebug, scope: this},
- })
- /* We also use this as our heartbeat */
- this.taskRunner = new Ext.util.TaskRunner();
- heartbeatRequest = false;
- this.heartbeat = this.taskRunner.start(
- {run: this.heartbeatCall,
- interval: 250});
- this.callParent(arguments);
- },
-
- handlePayload: function(payload) {
- if ((this.payloadGrid) && (payload['type'] != 'logentry')) {
- var wv = payload['varname'];
- if (payload['type'] == 'widget_payload') {
- wv = payload['widget_id'];
- }
- this.getPayloadsStore().add({
- payloadtype: payload['type'],
- widgettype: payload['widget_type'],
- varname: wv,
- });
- }
- this.application.fireEvent('payload' + payload['type'], payload);
- },
-
- heartbeatCall: function() {
- if (heartbeatRequest == true) return;
- heartbeatRequest = true;
- yt_rpc.ExtDirectREPL.heartbeat(
- {}, function(f, a) {
- heartbeatRequest = false;
- if (f != null) {
- Ext.each(f, function(payload, index) {
- reason.fireEvent("payloadreceived", payload);
- });
- }
- /*else if (!a.status) {
- reason.fireEvent("stopheartbeat");
- Ext.Msg.alert("Error", "Error talking to server. Shutting down.");
- }*/
- return true;
- }
- );
- },
-
- stopHeartbeat: function() {
- this.taskRunner.stopAll();
- },
-
- enableDebug: function() {
- this.payloadGrid = Ext.widget("payloadgrid");
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.payloadGrid);
- this.requestsGrid = Ext.widget('requestsgrid');
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.requestsGrid);
- },
-
- execute: function(code, hide, callback) {
- var fn;
- if (callback) { fn = callback; }
- else { fn = this.returnFromRPC; }
- if (hide == null) { hide = false; }
- reason.fireEvent("disableinput");
- result_id = reason.numberOfRequests + 1;
- reason.numberOfRequests += 1;
- reason.getController("Notebook").addRequest(result_id, code);
- yt_rpc.ExtDirectREPL.execute({
- code: code,
- hide:hide,
- result_id: result_id
- }, fn);
- },
-
- returnFromRPC: function(result, e) {
- if(!e.status) {
- var tpl = new Ext.XTemplate(
- 'RPC Error: {message}; {action}, {method}');
- var trans = e.getTransaction();
- tpl = tpl.apply({message: e.message,
- action: trans.action,
- method: trans.method});
- Ext.Msg.alert("Error", tpl);
- Ext.Error.raise(tpl);
- }
- reason.fireEvent("allowinput");
- },
-
- method: function(methodName, args, callback) {
- var m = yt_rpc.ExtDirectREPL[methodName];
- if (!m) {
- var t = "Could not identify method " + methodName;
- Ext.Msg.alert("Error", t);
- Ext.Error.raise(t);
- }
- var fn;
- if (callback) { fn = callback; }
- else {
- this.application.fireEvent("disableinput");
- fn = this.returnFromRPC;
- }
- m(args, fn);
- },
-
- m: function() { return this.method(arguments); },
-
- multicast: function(widget_var) {
- /*
- This will be two step. The first will be to create a window that
- allows the user to set up the MultiCast session, which will be an
- iframe loading the GAE instance. Then we tell our local server that
- we want to multicast.
- */
- var win = Ext.widget('multicastsetup');
- setupMulticast = function() {
- var cmd = Ext.String.format(
- 'widget_store.activate_multicast("{0}", "{1}", "{2}")',
- widget_var,
- win.query("#session_id")[0].getValue(),
- win.query("#session_token")[0].getValue());
- reason.server.execute(cmd);
- win.destroy();
- }
- win.query('#multicast')[0].on('click', setupMulticast);
- win.query('#cancel')[0].on('click', function(){win.destroy();});
- win.show();
- },
-
-});
-
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/WidgetDirector.js
--- a/yt/gui/reason/html/app/controller/WidgetDirector.js
+++ /dev/null
@@ -1,172 +0,0 @@
-/**********************************************************************
-Widget controller class
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.WidgetDirector', {
- extend: 'Ext.app.Controller',
- requires: ["Reason.controller.widgets.SampleWidget",
- "Reason.controller.widgets.PlotWindow",
- "Reason.controller.widgets.ProgressBar",
- "Reason.controller.widgets.GridDataViewer",
- "Reason.controller.widgets.ParameterFile",
- "Reason.controller.widgets.PannableMap",
- "Reason.controller.widgets.PhasePlot",
- "Reason.controller.widgets.Scene",
- ],
- stores: ['WidgetTypes', 'WidgetInstances'],
- views: ['WidgetTypesGrid', 'WidgetInstancesGrid'],
-
- init: function() {
- Ext.iterate(Reason.controller.widgets, function(i, w, ws) {
- Ext.require(w.getName());
- this.registerWidget(w);
- }, this);
- this.application.addListener({
- createwidget: {fn: this.createWidget, scope: this},
- showwidgets: {fn: this.showWidgetMenu, scope: this},
- payloadwidget: {fn: this.newWidgetCreated, scope: this},
- payloadwidget_payload: {fn: this.sendPayload, scope: this},
- enabledebug: {fn: this.enableDebug, scope: this},
- });
- this.callParent(arguments);
- },
-
- registerWidget: function(w) {
- if (w.widgetName == null) {return;}
- console.log("Registering " + w.widgetName);
- this.getWidgetTypesStore().add({
- widgetname: w.widgetName,
- widgetclass: w,
- displayname: w.displayName,
- pfs: w.supportsParameterFiles,
- objs: w.supportsDataObjects,
- });
- },
-
- createWidget: function(b, e) {
- var w = b.widget;
- console.log("Asked to create " + b.widget.widgetName);
- b.widget.preCreation(b.dataObj);
- },
-
- showWidgetMenu: function(treerecord, e) {
- var contextMenu = Ext.create('Ext.menu.Menu', {plain: true,});
- var data = treerecord.data;
- var w;
- this.getWidgetTypesStore().each(function(record, idx) {
- w = record.data;
- if (((data.type == 'parameter_file') && (w.pfs == false))
- || ((data.type != 'parameter_file') && (w.objs == false))) {
- return;
- }
- contextMenu.add({xtype:'menuitem',
- text: w.displayname,
- listeners: {
- click: {
- fn : this.createWidget,
- scope: this
- },
- },
- widget: w.widgetclass,
- dataObj: data
- });
- }, this);
- contextMenu.showAt(e.getXY());
- },
-
- newWidgetCreated: function(payload) {
- /* We have the following fields:
- type ('widget')
- widget_type
- varname
- data (has subfields)
-
- We now obtain our class, create that with the factory, and we add
- the resultant class to our store.
- */
- var resultId = this.getWidgetTypesStore().find(
- 'widgetname', payload['widget_type']);
- if (resultId == -1) {
- Ext.Error.raise('Did not recognize widget type "' +
- payload['widget_type'] + '".');
- }
- var widgetInfo = this.getWidgetTypesStore().getAt(resultId).data;
- /* The widget adds its view to the viewport. */
- var newWidget = Ext.create(widgetInfo['widgetclass'].getName(),
- {payload: payload});
- console.log("Adding widget payload with varname " + payload['varname']);
- this.getWidgetInstancesStore().add({
- widgetid: payload['varname'],
- widgettype: widgetInfo.widgetname,
- widget: newWidget
- });
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- newWidget.createView());
- },
-
- sendPayload: function(payload) {
- var resultId = this.getWidgetInstancesStore().find(
- 'widgetid', payload['widget_id']);
- if (resultId == -1) {
- Ext.Error.raise('Could not find widget "' +
- payload['widget_id'] + '".');
- }
- /*console.log("Directing payload for " + payload['widget_id'] +
- " to resultId " + resultId);*/
- if (payload['binary'] != null) {
- this.loadBinaryData(payload);
- return;
- }
- var widgetInfo = this.getWidgetInstancesStore().getAt(resultId).data;
- widgetInfo['widget'].applyPayload(payload);
- },
-
- loadBinaryData: function(payload1) {
- /* https://developer.mozilla.org/en/using_xmlhttprequest
- including progress */
- function loadBinaryPayload(payload) {
- var req = new XMLHttpRequest();
- var bkeys = payload['binary'];
- var nLeft = bkeys.length;
- var bkey = bkeys[nLeft - 1];
- var director = this;
- payload['binary'] = null;
- req.open("GET", bkey[1], true);
- req.responseType = "arraybuffer";
- onLoad = function(e) {
- payload[bkey[0]] = req.response;
- nLeft = nLeft - 1;
- if (nLeft == 0) {
- director.sendPayload(payload);
- } else {
- bkey = bkeys[nLeft - 1];
- req.open("GET", bkey[1], true);
- req.responseType = "arraybuffer";
- req.onload = onLoad;
- req.send();
- exaine = payload;
- }
- }
- req.onload = onLoad;
- req.send();
- }
- loadBinaryPayload.call(this, payload1);
- },
-
- enableDebug: function() {
- if(this.instanceView) {return;}
- this.instanceView = Ext.widget('widgetinstancesgrid');
- this.typeView = Ext.widget('widgettypesgrid');
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.instanceView);
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.typeView);
- },
-
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/widgets/BaseWidget.js
--- a/yt/gui/reason/html/app/controller/widgets/BaseWidget.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/**********************************************************************
-Base widget class
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.require("Reason.templates.TemplateContainer");
-
-Ext.define('Reason.controller.widgets.BaseWidget', {
- extend: 'Ext.app.Controller',
- supportsParameterFiles: false,
- supportsDataObjects: false,
- templateManager: null,
- templates: {},
- executionTriggers: [],
- widgetTriggers: [],
- keyTriggers: [],
-
- constructor: function() {
- this.templateManager = Ext.create(
- "Reason.templates.TemplateContainer",
- { templates: this.templates }
- );
- this.callParent(arguments);
- },
-
- getExecuteFunction: function(ww, templateName, isValidFn) {
- var tpl = new Ext.XTemplate(
- this.templateManager.getTemplates()[templateName]);
- var args = {};
- var control = this;
- function ev() {
- var myArgs = arguments;
- Ext.each(arguments, function(v, i) {
- args["a" + i] = myArgs[i];
- });
- args['control'] = control;
- args['widget'] = ww;
- if((isValidFn != null) && (isValidFn(arguments) == false)) {return;}
- reason.server.execute(tpl.apply(args), true);
- };
- return ev;
- },
-
- applyExecuteHandlers: function(ww) {
- var conf;
- function ef(id, ename, tpl, isValidFn) {
- conf = {}
- conf[ename] = this.getExecuteFunction(ww, tpl);
- ww.query(id)[0].on(conf);
- };
- Ext.each(this.executionTriggers, function(trigger) {
- ef.call(this, trigger[0], trigger[1], trigger[2], trigger[3]);
- }, this);
- Ext.each(this.widgetTriggers, function(trigger) {
- conf = {scope:this}
- conf[trigger[1]] = this[trigger[2]];
- ww.query(trigger[0])[0].on(conf);
- }, this);
-
- this.keyMap = new Ext.util.KeyMap({target: document});
- this.keyMap.disable();
- Ext.each(this.keyTriggers, function(trigger) {
- trigger['fn'] = this.getExecuteFunction(ww, trigger['tpl']);
- this.keyMap.addBinding(trigger);
- }, this);
- ww.on("activate", this.activateKeyMap, this);
- ww.on("deactivate", this.deactivateKeyMap, this);
- },
-
- activateKeyMap: function() {
- this.keyMap.enable();
- },
-
- deactivateKeyMap: function() {
- this.keyMap.disable();
- },
-
- createMyRefs: function(varname) {
- var refs = Array(this.viewRefs.length);
- var tpl = new Ext.XTemplate("#{varname} {selector}");
- Ext.each(this.viewRefs, function(v, i, a) {
- refs[i] = {ref: v['ref'],
- selector: tpl.apply({varname:varname,
- selector: v['selector']})
- };
- });
- this.ref(refs);
- return refs;
- },
-
- multicast: function() {
- reason.server.multicast(this.payload['varname']);
- }
-
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/widgets/GridDataViewer.js
--- a/yt/gui/reason/html/app/controller/widgets/GridDataViewer.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**********************************************************************
-The Plot Window Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-Ext.define("Reason.controller.widgets.GridDataViewer", {
- extend: 'Reason.controller.widgets.BaseWidget',
- requires: ['Reason.view.widgets.GridDataViewer'],
-
- templates: {
- title: "Grid Data for {widget.varname}",
- createGridViewer: 'widget_store.create_grid_dataview({varname})',
- },
-
- widgetTriggers: [
-
- ],
-
- executionTriggers: [
-
- ],
-
- viewRefs: [
- ],
-
- applyPayload: function(payload) {
- return;
- },
-
- createView: function() {
- var wd = this.payload['data'];
- this.dataStore = Ext.create("Reason.store.widgets.GridData");
- this.dataStore.loadData(wd['gridvals']);
- this.gridDataView = Ext.widget("griddataviewer", {
- store: this.dataStore,
- title: 'Grid Data for ' + this.payload['varname'],
- });
-
- this.createMyRefs(this.gridDataView.id);
- return this.gridDataView;
- },
-
- statics: {
- widgetName: "grid_data",
- displayName: "Grid Data Viewer",
- supportsDataObjects: false,
- supportsParameterFiles: true,
- preCreation: function(obj) {
- var widget = Ext.create(this.getName());
- var cmd = widget.templateManager.applyObject(
- obj, 'createGridViewer');
- reason.server.execute(cmd);
- },
- },
-});
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/widgets/GridViewer.js
--- a/yt/gui/reason/html/app/controller/widgets/GridViewer.js
+++ /dev/null
@@ -1,194 +0,0 @@
-/**********************************************************************
-The Plot Window Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-window.requestAnimFrame = (function(){
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(/* function */ callback, /* DOMElement */ element){
- window.setTimeout(callback, 1000 / 60);
- };
-})();
-
-var WidgetGridViewer = function(python_varname, widget_data) {
- this.id = python_varname;
- this.widget_data = widget_data;
- examine = "canvas_" + python_varname;
- var draw;
- var GridViewerStart = function() {
- this.curX = 0;
- this.curY = 0;
- this.dist = 0;
- function updateBasedOnOffset(camera, offset){
- camera.position.x = camera.target.x + offset.x;
- camera.position.y = camera.target.y + offset.y;
- camera.position.z = camera.target.z + offset.z;
- draw();
- }
- function camGetOffset(camera){
- return PhiloGL.Vec3.sub(camera.position, camera.target)
- }
- PhiloGL('canvas_' + python_varname, {
- camera: {
- position: {
- x: 0.5, y: 0.5, z: 5
- },
- target: {
- x: 0.5, y: 0.5, z: 0.5
- },
- },
- events: {
- onDragStart: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- this.curX = e.x;
- this.curY = e.y;
- this.dist = camGetOffset(this.camera).norm();
- },
- onDragEnd: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- },
- onDragMove: function(e) {
- var c = this.camera;
- var off = camGetOffset(c);
-
- // Get Horizontal vector
- var horiz = PhiloGL.Vec3.cross(c.up,
- camGetOffset(c))
- horiz.$scale(1./horiz.norm());
-
- if (e.event.button == 0){ // Rotation
- // Do vertical rotation about horizontal vector
- var vert_rot = new PhiloGL.Mat4();
- vert_rot.id();
- vert_rot.$rotateAxis((e.y-this.curY)/100., horiz);
- PhiloGL.Mat4.$mulVec3(vert_rot, off);
- PhiloGL.Mat4.$mulVec3(vert_rot, c.up);
- c.up.$scale(1./c.up.norm());
-
- // Do horizontal rotation about up vector
- var side_rot = new PhiloGL.Mat4();
- side_rot.id();
- side_rot.$rotateAxis(-(e.x-this.curX)/100., c.up);
- side_rot.$mulVec3(off);
-
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- updateBasedOnOffset(c, off);
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- } else if (e.event.button = 2){ // Right click - transpose
- var tscale = 1.0*off.norm()/512.;
- var move_up = c.up.scale(-(e.y-this.curY)*tscale);
- var move_over = horiz.scale(-(e.x-this.curX)*tscale);
- c.position.$add(move_up);
- c.position.$add(move_over);
- c.target.$add(move_up);
- c.target.$add(move_over);
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- }
- draw();
- },
- onMouseWheel: function(e){
- e.stop();
- var offset = PhiloGL.Vec3.scale(camGetOffset(this.camera),
- 1.0 - e.wheel/10.);
- updateBasedOnOffset(this.camera, offset);
- var dist = offset.norm()
- this.camera.near = offset.norm()/100000.0;
- this.camera.far = offset.norm()*2.0;
- this.camera.update();
- draw();
- }
- },
- onError: function() {
- alert("An error ocurred while loading the application");
- },
- onLoad: function(app) {
- var gl = app.gl,
- canvas = app.canvas,
- program = app.program,
- scene = app.scene,
- camera = app.camera;
- var grids = new PhiloGL.O3D.Model({
- vertices : widget_data['vertex_positions'],
- drawType : "LINES",
- colors : widget_data['vertex_colors'],
- });
- scene.add(grids);
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.clearColor(0, 0, 0, 1);
-
- //examine = camera;
- camera.view.id();
- camera.update();
-
- //Draw the scene
- draw = function() {
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- scene.render();
- }
-
- draw();
-
- }
- });
- }
-
- viewport.get("center-panel").add(
- {
- xtype: 'panel',
- id: "gv_" + python_varname,
- title: "WebGL Grid Viewer",
- iconCls: 'graph',
- autoScroll: true,
- layout:'absolute',
- closable: true,
- items: [
- { xtype:'panel',
- autoEl: {
- tag: 'canvas',
- id: 'canvas_' + python_varname,
- style: 'border: none;',
- width: 512, height:512
- },
- width: 512,
- height: 512
- }],
- listeners: { afterlayout: GridViewerStart },
- }
- );
-
- viewport.get("center-panel").activate("gv_" + this.id);
- viewport.doLayout();
- this.panel = viewport.get("center-panel").get("gv_" + python_varname);
- this.panel.doLayout();
-
- this.accept_results = function(payload) { }
-}
-
-widget_types['grid_viewer'] = WidgetGridViewer;
diff -r 6f844749fdac5ed63441a64c806fc1e94b3ef91e -r 105458124524bb225bc5e47720993d1b72d03796 yt/gui/reason/html/app/controller/widgets/IsocontourViewer.js
--- a/yt/gui/reason/html/app/controller/widgets/IsocontourViewer.js
+++ /dev/null
@@ -1,196 +0,0 @@
-/**********************************************************************
-The isocontour viewer widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-window.requestAnimFrame = (function(){
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(/* function */ callback, /* DOMElement */ element){
- window.setTimeout(callback, 1000 / 60);
- };
-})();
-
-var exagain;
-var WidgetIsocontourViewer = function(python_varname, widget_data) {
- this.id = python_varname;
- this.widget_data = widget_data;
- examine = "canvas_" + python_varname;
- var draw;
- var GridViewerStart = function() {
- this.curX = 0;
- this.curY = 0;
- this.dist = 0;
- function updateBasedOnOffset(camera, offset){
- camera.position.x = camera.target.x + offset.x;
- camera.position.y = camera.target.y + offset.y;
- camera.position.z = camera.target.z + offset.z;
- draw();
- }
- function camGetOffset(camera){
- return PhiloGL.Vec3.sub(camera.position, camera.target)
- }
- PhiloGL('canvas_' + python_varname, {
- camera: {
- position: {
- x: 0.5, y: 0.5, z: 5
- },
- target: {
- x: 0.5, y: 0.5, z: 0.5
- },
- },
- events: {
- onDragStart: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- this.curX = e.x;
- this.curY = e.y;
- this.dist = camGetOffset(this.camera).norm();
- },
- onDragEnd: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- },
- onDragMove: function(e) {
- var c = this.camera;
- var off = camGetOffset(c);
-
- // Get Horizontal vector
- var horiz = PhiloGL.Vec3.cross(c.up,
- camGetOffset(c))
- horiz.$scale(1./horiz.norm());
-
- if (e.event.button == 0){ // Rotation
- // Do vertical rotation about horizontal vector
- var vert_rot = new PhiloGL.Mat4();
- vert_rot.id();
- vert_rot.$rotateAxis((e.y-this.curY)/100., horiz);
- PhiloGL.Mat4.$mulVec3(vert_rot, off);
- PhiloGL.Mat4.$mulVec3(vert_rot, c.up);
- c.up.$scale(1./c.up.norm());
-
- // Do horizontal rotation about up vector
- var side_rot = new PhiloGL.Mat4();
- side_rot.id();
- side_rot.$rotateAxis(-(e.x-this.curX)/100., c.up);
- side_rot.$mulVec3(off);
-
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- updateBasedOnOffset(c, off);
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- } else if (e.event.button = 2){ // Right click - transpose
- var tscale = 1.0*off.norm()/512.;
- var move_up = c.up.scale(-(e.y-this.curY)*tscale);
- var move_over = horiz.scale(-(e.x-this.curX)*tscale);
- c.position.$add(move_up);
- c.position.$add(move_over);
- c.target.$add(move_up);
- c.target.$add(move_over);
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- }
- draw();
- },
- onMouseWheel: function(e){
- e.stop();
- var offset = PhiloGL.Vec3.scale(camGetOffset(this.camera),
- 1.0 - e.wheel/10.);
- updateBasedOnOffset(this.camera, offset);
- var dist = offset.norm()
- this.camera.near = offset.norm()/100000.0;
- this.camera.far = offset.norm()*2.0;
- this.camera.update();
- draw();
- }
- },
- onError: function() {
- alert("An error ocurred while loading the application");
- },
- onLoad: function(app) {
- var gl = app.gl,
- canvas = app.canvas,
- program = app.program,
- scene = app.scene,
- camera = app.camera;
- var grids = new PhiloGL.O3D.Model({
- vertices : widget_data['vertex_positions'],
- drawType : "TRIANGLES",
- colors : widget_data['vertex_colors'],
- });
- exagain = grids;
- scene.add(grids);
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.clearColor(0, 0, 0, 1);
-
- //examine = camera;
- camera.view.id();
- camera.update();
-
- //Draw the scene
- draw = function() {
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- scene.render();
- }
-
- draw();
-
- }
- });
- }
-
- viewport.get("center-panel").add(
- {
- xtype: 'panel',
- id: "iv_" + python_varname,
- title: "WebGL Isocontour Viewer",
- iconCls: 'graph',
- autoScroll: true,
- layout:'absolute',
- closable: true,
- items: [
- { xtype:'panel',
- autoEl: {
- tag: 'canvas',
- id: 'canvas_' + python_varname,
- style: 'border: none;',
- width: 512, height:512
- },
- width: 512,
- height: 512
- }],
- listeners: { afterlayout: GridViewerStart },
- }
- );
-
- viewport.get("center-panel").activate("iv_" + this.id);
- viewport.doLayout();
- this.panel = viewport.get("center-panel").get("iv_" + python_varname);
- this.panel.doLayout();
-
- this.accept_results = function(payload) { }
-}
-
-widget_types['isocontour_viewer'] = WidgetIsocontourViewer;
This diff is so big that we needed to truncate the remainder.
https://bitbucket.org/yt_analysis/yt/commits/8b9ce73b435c/
Changeset: 8b9ce73b435c
Branch: yt
User: ngoldbaum
Date: 2015-08-24 18:06:32+00:00
Summary: Removing last remnants of yt.gui submodule
Affected #: 10 files
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/basic_repl.py
--- a/yt/gui/reason/basic_repl.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""
-A read-eval-print-loop. This code was released in the CherryPy project
-initially, but has been heavily modified and again re-released in compliance
-with the terms of its original license.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import codeop
-import inspect
-import re
-import json
-import sys
-import traceback
-from yt.extern.six.moves import StringIO
-
-class ProgrammaticREPL(object):
- stopped = False
- debug = False
- def __init__(self, locals=None):
- self.executed_cell_texts = []
- self.locals = {}
- if locals:
- self.locals.update(locals)
- self.buffer = []
- # Nominally at this point we could populate our namespace with widgets
- # or other useful functions. We aren't really ready for that just yet.
-
- def evaluate_cell(self, input):
- result = []
- for line in input.split("\n"):
- r = self.push(line)
- if r is not None: result.append(r)
- # To catch if people leave a little bit at the end for us
- if r is None:
- r = self.push("\n")
- if r is not None: result.append(r)
- # Usually they have \n already
- return "".join(result)
-
- def push(self, line):
- """Push 'line' and return exec results (None if more input needed)."""
- if line == "help":
- return "Type help(object) for help about object."
- if line == "help()":
- return "You cannot call help() without an argument."
-
- self.buffer.append(line)
- source = "\n".join(self.buffer)
-
- try:
- code = codeop.compile_command(source, "<HTTP input>", 'single')
- except (OverflowError, SyntaxError, ValueError):
- self.buffer = []
- return traceback.format_exc()
-
- if code is None:
- # More lines needed.
- return None
-
- self.buffer = []
- return self.execute(code)
-
- def execute(self, code):
- """Execute the given code in self.locals and return any stdout/sterr."""
- out = StringIO()
- oldout = sys.stdout
- olderr = sys.stderr
- sys.stdout = sys.stderr = out
- try:
- try:
- exec code in self.locals
- except:
- result = traceback.format_exc()
- else:
- result = out.getvalue()
- finally:
- sys.stdout = oldout
- sys.stderr = olderr
- out.close()
- return result
-
- def dir(self, line):
- """Examine a partial line and provide attr list of final expr."""
- line = re.split(r"\s", line)[-1].strip()
- # Support lines like "thing.attr" as "thing.", because the browser
- # may not finish calculating the partial line until after the user
- # has clicked on a few more keys.
- line = ".".join(line.split(".")[:-1])
- try:
- result = eval("dir(%s)" % line, {}, self.locals)
- except:
- return []
- return result
-
- def doc(self, line):
- """Examine a partial line and provide sig+doc of final expr."""
- line = re.split(r"\s", line)[-1].strip()
- # Support lines like "func(text" as "func(", because the browser
- # may not finish calculating the partial line until after the user
- # has clicked on a few more keys.
- line = "(".join(line.split("(")[:-1])
- try:
- result = eval(line, {}, self.locals)
- try:
- if isinstance(result, type):
- func = result.__init__
- else:
- func = result
- args, varargs, varkw, defaults = inspect.getargspec(func)
- except TypeError:
- if callable(result):
- doc = getattr(result, "__doc__", "") or ""
- return "%s\n\n%s" % (line, doc)
- return None
- except:
- return None
-
- if args and args[0] == 'self':
- args.pop(0)
- missing = object()
- defaults = defaults or []
- defaults = ([missing] * (len(args) - len(defaults))) + list(defaults)
- arglist = []
- for a, d in zip(args, defaults):
- if d is missing:
- arglist.append(a)
- else:
- arglist.append("%s=%s" % (a, d))
- if varargs:
- arglist.append("*%s" % varargs)
- if varkw:
- arglist.append("**%s" % varkw)
- doc = getattr(result, "__doc__", "") or ""
- return "%s(%s)\n%s" % (line, ", ".join(arglist), doc)
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/extdirect_repl.py
--- a/yt/gui/reason/extdirect_repl.py
+++ /dev/null
@@ -1,499 +0,0 @@
-"""
-A read-eval-print-loop that is served up through Bottle and accepts its
-commands through ExtDirect calls
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from yt.extern.six.moves import urllib
-import json
-import os
-import stat
-from cStringIO import StringIO
-import logging
-import uuid
-import numpy as np
-import time
-import pprint
-import traceback
-import tempfile
-import base64
-import imp
-import threading
-import Queue
-import zipfile
-try:
- import Pyro4
-except ImportError:
- pass
-
-from yt.funcs import *
-from yt.utilities.logger import ytLogger, ufstring
-from yt.visualization.image_writer import apply_colormap
-from yt.visualization.api import Streamlines
-from .widget_store import WidgetStore
-
-from .bottle_mods import preroute, BottleDirectRouter, notify_route, \
- PayloadHandler, lockit
-from yt.extern.bottle import response, request, route, static_file
-from .utils import get_list_of_datasets
-from .basic_repl import ProgrammaticREPL
-
-try:
- import pygments
- import pygments.lexers
- import pygments.formatters
- def _highlighter():
- pl = pygments.lexers.PythonLexer()
- hf = pygments.formatters.HtmlFormatter(
- linenos='table', linenospecial=2)
- def __highlighter(a):
- return pygments.highlight(a, pl, hf)
- return __highlighter, hf.get_style_defs()
- # We could add an additional '.highlight_pyg' in the call
- highlighter, highlighter_css = _highlighter()
-except ImportError:
- highlighter = lambda a: a
- highlight_css = ''
-
-local_dir = os.path.dirname(__file__)
-
-class ExecutionThread(threading.Thread):
- def __init__(self, repl):
- self.repl = repl
- self.payload_handler = PayloadHandler()
- self.queue = Queue.Queue()
- threading.Thread.__init__(self)
- self.daemon = True
-
- def heartbeat(self):
- return
-
- def run(self):
- while 1:
- #print "Checking for a queue ..."
- try:
- task = self.queue.get(True, 1)
- except Queue.Empty:
- if self.repl.stopped: return
- continue
- print("Received the task", task)
- if task['type'] != 'code':
- raise NotImplementedError
- print(task)
- self.execute_one(task['code'], task['hide'], task['result_id'])
- self.queue.task_done()
-
- def wait(self):
- self.queue.join()
-
- def execute_one(self, code, hide, result_id):
- self.repl.executed_cell_texts.append(code)
- result = ProgrammaticREPL.execute(self.repl, code)
- if self.repl.debug:
- print("==================== Cell Execution ====================")
- print(code)
- print("==================== ====================")
- print(result)
- print("========================================================")
- self.payload_handler.add_payload(
- {'type': 'cell',
- 'output': result,
- 'input': highlighter(code),
- 'image_data': '',
- 'result_id': result_id,
- 'hide': hide,
- 'raw_input': code},
- )
- objs = get_list_of_datasets()
- self.payload_handler.add_payload(
- {'type': 'dataobjects',
- 'objs': objs})
-
-class PyroExecutionThread(ExecutionThread):
- def __init__(self, repl):
- ExecutionThread.__init__(self, repl)
- hmac_key = raw_input("HMAC_KEY? ").strip()
- uri = raw_input("URI? ").strip()
- Pyro4.config.HMAC_KEY = hmac_key
- self.executor = Pyro4.Proxy(uri)
-
- def execute_one(self, code, hide, result_id):
- self.repl.executed_cell_texts.append(code)
- print(code)
- result = self.executor.execute(code)
- if not hide:
- self.repl.payload_handler.add_payload(
- {'type': 'cell',
- 'output': result,
- 'input': highlighter(code),
- 'result_id': result_id,
- 'raw_input': code},
- )
- ph = self.executor.deliver()
- for p in ph:
- self.repl.payload_handler.add_payload(p)
-
- def heartbeat(self):
- ph = self.executor.deliver()
- for p in ph:
- self.repl.payload_handler.add_payload(p)
-
-def reason_pylab():
- from .utils import deliver_image
- def _canvas_deliver(canvas):
- tf = tempfile.TemporaryFile()
- canvas.print_png(tf)
- tf.seek(0)
- img_data = base64.b64encode(tf.read())
- tf.close()
- deliver_image(img_data)
- def reason_draw_if_interactive():
- if matplotlib.is_interactive():
- figManager = Gcf.get_active()
- if figManager is not None:
- _canvas_deliver(figManager.canvas)
- def reason_show(mainloop = True):
- # We ignore mainloop here
- for manager in Gcf.get_all_fig_managers():
- _canvas_deliver(manager.canvas)
- # Matplotlib has very nice backend overriding.
- # We should really use that. This is just a hack.
- import matplotlib
- matplotlib.use("agg") # Hotfix for when we import pylab below
- new_agg = imp.new_module("reason_agg")
- import matplotlib.backends.backend_agg as bagg
- new_agg.__dict__.update(bagg.__dict__)
- new_agg.__dict__.update(
- {'show': reason_show,
- 'draw_if_interactive': reason_draw_if_interactive})
- sys.modules["reason_agg"] = new_agg
- bagg.draw_if_interactive = reason_draw_if_interactive
- from matplotlib._pylab_helpers import Gcf
- matplotlib.rcParams["backend"] = "module://reason_agg"
- import pylab
- pylab.switch_backend("module://reason_agg")
-
-_startup_template = r"""\
-import pylab
-from yt.mods import *
-from yt.gui.reason.utils import load_script, deliver_image
-from yt.gui.reason.widget_store import WidgetStore
-from yt.data_objects.static_output import _cached_datasets
-
-pylab.ion()
-data_objects = []
-widget_store = WidgetStore()
-"""
-
-class ExtDirectREPL(ProgrammaticREPL, BottleDirectRouter):
- _skip_expose = ('index')
- my_name = "ExtDirectREPL"
- timeout = 660 # a minute longer than the rocket server timeout
- server = None
- _heartbeat_timer = None
-
- def __init__(self, reasonjs_path, locals=None,
- use_pyro=False):
- # First we do the standard initialization
- self.reasonjs_file = zipfile.ZipFile(reasonjs_path, 'r')
- ProgrammaticREPL.__init__(self, locals)
- # Now, since we want to only preroute functions we know about, and
- # since they have different arguments, and most of all because we only
- # want to add them to the routing tables (which are a singleton for the
- # entire interpreter state) we apply all the pre-routing now, rather
- # than through metaclasses or other fancy decorating.
- preroute_table = dict(index = ("/", "GET"),
- _help_html = ("/help.html", "GET"),
- _myapi = ("/ext-repl-api.js", "GET"),
- _session_py = ("/session.py", "GET"),
- _highlighter_css = ("/highlighter.css", "GET"),
- _reasonjs = ("/reason-js/:path#.+#", "GET"),
- _app = ("/reason/:path#.+#", "GET"),
- )
- for v, args in preroute_table.items():
- preroute(args[0], method=args[1])(getattr(self, v))
- # This has to be routed to the root directory
- self.api_url = "repl"
- BottleDirectRouter.__init__(self)
- self.payload_handler = PayloadHandler()
- if use_pyro:
- self.execution_thread = PyroExecutionThread(self)
- else:
- self.execution_thread = ExecutionThread(self)
- # We pass in a reference to ourself
- self.execute(_startup_template)
- self.widget_store = WidgetStore(self)
- # Now we load up all the yt.mods stuff, but only after we've finished
- # setting up.
- reason_pylab()
-
- def activate(self):
- self.payload_handler._prefix = self._global_token
- self._setup_logging_handlers()
- # Setup our heartbeat
- self.last_heartbeat = time.time()
- self._check_heartbeat()
- self.execute("widget_store._global_token = '%s'" % self._global_token)
- self.execution_thread.start()
-
- def exception_handler(self, exc):
- result = {'type': 'cell',
- 'input': 'ERROR HANDLING IN REASON',
- 'result_id': None,
- 'output': traceback.format_exc()}
- return result
-
- def _setup_logging_handlers(self):
- handler = PayloadLoggingHandler()
- formatter = logging.Formatter(ufstring)
- handler.setFormatter(formatter)
- ytLogger.addHandler(handler)
-
- def index(self):
- root = os.path.join(local_dir, "html")
- return static_file("index.html", root)
-
- def heartbeat(self):
- self.last_heartbeat = time.time()
- if self.debug: print("### Heartbeat ... started: %s" % (time.ctime()))
- for i in range(30):
- # Check for stop
- if self.debug: print(" ###")
- if self.stopped: return {'type':'shutdown'} # No race condition
- if self.payload_handler.event.wait(1): # One second timeout
- if self.debug: print(" ### Delivering payloads")
- rv = self.payload_handler.deliver_payloads()
- if self.debug: print(" ### Got back, returning")
- return rv
- self.execution_thread.heartbeat()
- if self.debug: print("### Heartbeat ... finished: %s" % (time.ctime()))
- return []
-
- def _check_heartbeat(self):
- if self.server is not None:
- if not all((s._monitor.is_alive() for s in self.server.values())):
- self.shutdown()
- return
- if time.time() - self.last_heartbeat > self.timeout:
- print("Shutting down after a timeout of %s" % (self.timeout))
- #sys.exit(0)
- # Still can't shut down yet, because bottle doesn't return the
- # server instance by default.
- self.shutdown()
- return
- if self._heartbeat_timer is not None: return
- self._heartbeat_timer = threading.Timer(10, self._check_heartbeat)
- self._heartbeat_timer.start()
-
- def shutdown(self):
- if self.server is None:
- return
- self._heartbeat_timer.cancel()
- self.stopped = True
- self.payload_handler.event.set()
- for v in self.server.values():
- v.stop()
- for t in threading.enumerate():
- print("Found a living thread:", t)
-
- def _help_html(self):
- root = os.path.join(local_dir, "html")
- return static_file("help.html", root)
-
- def _reasonjs(self, path):
- pp = os.path.join("reason-js", path)
- try:
- f = self.reasonjs_file.open(pp)
- except KeyError:
- response.status = 404
- return
- if path[-4:].lower() in (".png", ".gif", ".jpg"):
- response.headers['Content-Type'] = "image/%s" % (path[-3:].lower())
- elif path[-4:].lower() == ".css":
- response.headers['Content-Type'] = "text/css"
- elif path[-3:].lower() == ".js":
- response.headers['Content-Type'] = "text/javascript"
- return f.read()
-
- def _app(self, path):
- root = os.path.join(local_dir, "html")
- return static_file(path, root)
-
- def _highlighter_css(self):
- response.headers['Content-Type'] = "text/css"
- return highlighter_css
-
- def execute(self, code, hide = False, result_id = None):
- task = {'type': 'code',
- 'code': code,
- 'hide': hide,
- 'result_id': result_id,
- }
- self.execution_thread.queue.put(task)
- return dict(status = True)
-
- def get_history(self):
- return self.executed_cell_texts[:]
-
- @lockit
- def save_session(self, filename):
- if filename.startswith('~'):
- filename = os.path.expanduser(filename)
- elif not filename.startswith('/'):
- filename = os.path.join(os.getcwd(), filename)
- if os.path.exists(filename):
- return {'status': 'FAIL', 'filename': filename,
- 'error': 'File exists!'}
- try:
- f = open(filename, 'w')
- f.write("\n######\n".join(self.executed_cell_texts))
- f.close()
- except IOError as xxx_todo_changeme:
- (errno, strerror) = xxx_todo_changeme.args
- return {'status': 'FAIL', 'filename': filename,
- 'error': strerror}
- except:
- return {'status': 'FAIL', 'filename': filename,
- 'error': 'Unexpected error.'}
- return {'status': 'SUCCESS', 'filename': filename}
-
- @lockit
- def paste_session(self):
- import xmlrpclib
- p = xmlrpclib.ServerProxy(
- "http://paste.yt-project.org/xmlrpc/",
- allow_none=True)
- cs = StringIO()
- cs.write("\n######\n".join(self.executed_cell_texts))
- cs = cs.getvalue()
- ret = p.pastes.newPaste('python', cs, None, '', '', True)
- site = "http://paste.yt-project.org/show/%s" % ret
- return {'status': 'SUCCESS', 'site': site}
-
- @lockit
- def paste_text(self, to_paste):
- import xmlrpclib
- p = xmlrpclib.ServerProxy(
- "http://paste.yt-project.org/xmlrpc/",
- allow_none=True)
- ret = p.pastes.newPaste('python', to_paste, None, '', '', True)
- site = "http://paste.yt-project.org/show/%s" % ret
- return {'status': 'SUCCESS', 'site': site}
-
- _api_key = 'f62d550859558f28c4c214136bc797c7'
- def upload_image(self, image_data, caption):
- if not image_data.startswith("data:"): return {'uploaded':False}
- prefix = "data:image/png;base64,"
- image_data = image_data[len(prefix):]
- parameters = {'key':self._api_key, 'image':image_data, type:'base64',
- 'caption': caption, 'title': "Uploaded Image from reason"}
- data = urllib.parse.urlencode(parameters)
- req = urllib.request.Request('http://api.imgur.com/2/upload.json', data)
- try:
- response = urllib.request.urlopen(req).read()
- except urllib.error.HTTPError as e:
- print("ERROR", e)
- return {'uploaded':False}
- rv = json.loads(response)
- rv['uploaded'] = True
- pprint.pprint(rv)
- return rv
-
- @lockit
- def _session_py(self):
- cs = StringIO()
- cs.write("\n######\n".join(self.executed_cell_texts))
- cs.seek(0)
- response.headers["content-disposition"] = "attachment;"
- return cs
-
- @lockit
- def load(self, base_dir, filename):
- pp = os.path.join(base_dir, filename)
- funccall = "datasets.append(load('%s'))" % pp
- self.execute(funccall)
- return []
-
- def file_listing(self, base_dir, sub_dir):
- if base_dir == "":
- cur_dir = os.getcwd()
- elif sub_dir == "":
- cur_dir = base_dir
- else:
- cur_dir = os.path.join(base_dir, sub_dir)
- cur_dir = os.path.abspath(cur_dir)
- if not os.path.isdir(cur_dir):
- return {'change':False}
- fns = os.listdir(cur_dir)
- results = [("..", 0, "directory")]
- for fn in sorted((os.path.join(cur_dir, f) for f in fns)):
- if not os.access(fn, os.R_OK): continue
- if os.path.isfile(fn):
- size = os.path.getsize(fn)
- t = "file"
- else:
- size = 0
- t = "directory"
- results.append((os.path.basename(fn), size, t))
- return dict(objs = results, cur_dir=cur_dir)
-
-class PayloadLoggingHandler(logging.StreamHandler):
- def __init__(self, *args, **kwargs):
- logging.StreamHandler.__init__(self, *args, **kwargs)
- self.payload_handler = PayloadHandler()
-
- def emit(self, record):
- msg = self.format(record)
- self.payload_handler.add_payload(
- {'type':'logentry',
- 'log_entry':msg})
-
-if os.path.exists(os.path.expanduser("~/.yt/favicon.ico")):
- ico = os.path.expanduser("~/.yt/")
-else:
- ico = os.path.join(local_dir, "html", "resources", "images")
- at route("/favicon.ico", method="GET")
-def _favicon_ico():
- print(ico)
- return static_file("favicon.ico", ico)
-
-class ExtProgressBar(object):
- def __init__(self, title, maxval):
- self.title = title
- self.maxval = maxval
- self.last = 0
- # Now we add a payload for the progress bar
- self.payload_handler = PayloadHandler()
- self.payload_handler.add_payload(
- {'type': 'widget',
- 'widget_type': 'progressbar',
- 'varname': 'pbar_top',
- 'data': {'title':title}
- })
-
- def update(self, val):
- # An update is only meaningful if it's on the order of 1/100 or greater
-
- if (val - self.last) > (self.maxval / 100.0):
- self.last = val
- self.payload_handler.add_payload(
- {'type': 'widget_payload',
- 'widget_id': 'pbar_top',
- 'value': float(val) / self.maxval})
-
- def finish(self):
- self.payload_handler.add_payload(
- {'type': 'widget_payload',
- 'widget_id': 'pbar_top',
- 'value': -1})
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/http_repl.py
--- a/yt/gui/reason/http_repl.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""
-A read-eval-print-loop that is served up through Bottle and accepts its
-commands through HTTP
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import json
-import os
-
-from .bottle_mods import preroute
-from .basic_repl import ProgrammaticREPL
-
-local_dir = os.path.dirname(__file__)
-
-class HTTPREPL(ProgrammaticREPL):
-
- def __init__(self, locals=None):
- # First we do the standard initialization
- ProgrammaticREPL.__init__(self, locals)
- # Now, since we want to only preroute functions we know about, and
- # since they have different arguments, and most of all because we only
- # want to add them to the routing tables (which are a singleton for the
- # entire interpreter state) we apply all the pre-routing now, rather
- # than through metaclasses or other fancy decorating.
- preroute_table = dict(index = ("/", "GET"),
- push = ("/push", "POST"),
- dir = ("/dir", "GET"),
- doc = ("/doc", "GET"),
- resources = ("/resources/:val", "GET"))
- for v, args in preroute_table.items():
- preroute(args[0], method=args[1])(getattr(self, v))
-
- def index(self):
- """Return an HTTP-based Read-Eval-Print-Loop terminal."""
- # For now this doesn't work! We will need to move to a better method
- # for this.
- vals = open(os.path.join(local_dir, "httprepl.html")).read()
- return vals
-
- def push(self):
- """Push 'line' and return exec results as a bare response."""
- line = request.POST['line']
- result = ProgrammaticREPL.push(self, line)
- new_values = self.locals.pop("new_values", "")
- if result is None:
- # More input lines needed.
- response.status = 204
- return json.dumps( dict(text = result, new_values = new_values ))
-
- def dir(self):
- """Push 'line' and return result of eval on the final expr."""
- line = request.GET['line']
- result = ProgrammaticREPL.dir(self, line)
- if not result:
- response.status = 204
- return
- return repr(result)
-
- def doc(self):
- """Push 'line' and return result of getargspec on the final expr."""
- line = request.GET['line']
- result = ProgrammaticREPL.doc(self, line)
- if not result:
- response.status = 204
- return result
-
- def resources(self, val):
- pp = os.path.join(local_dir, "resources", val)
- if not os.path.exists(pp):
- response.status = 404
- return
- return open(pp).read()
-
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/pyro_queue.py
--- a/yt/gui/reason/pyro_queue.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-Task queue for reason.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import numpy as np
-
-from yt.funcs import *
-
-from yt.gui.reason.basic_repl import ProgrammaticREPL
-from yt.gui.reason.extdirect_repl import ExecutionThread
-from yt.gui.reason.bottle_mods import PayloadHandler
-from .utils import get_list_of_datasets
-
-class PyroQueueRoot(object):
- def __init__(self, comm):
- self.comm = comm
- self.repl = ProgrammaticREPL()
- self.execution_thread = ExecutionThread(self.repl)
- self.payload_handler = PayloadHandler()
- self.execution_thread.start()
-
- def execute(self, code, hide = False):
- mylog.info('Root sending out code.')
- code = self.comm.comm.bcast(code, root=0)
- task = {'type': 'code',
- 'code': code,
- 'hide': hide}
- self.execution_thread.queue.put(task)
-
- def deliver(self):
- return self.payload_handler.deliver_payloads()
-
-class PyroQueueNonRoot(object):
- def __init__(self, comm):
- self.comm = comm
- self.repl = ProgrammaticREPL()
-
- def run(self):
- while 1:
- code = None
- code = self.comm.comm.bcast(code, root=0)
- mylog.info('Received commands from subcomm root.')
- value = self.repl.execute(code)
-
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/setup.py
--- a/yt/gui/reason/setup.py
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/usr/bin/env python
-import setuptools
-import os
-import sys
-import os.path
-import glob
-
-
-def configuration(parent_package='', top_path=None):
- from numpy.distutils.misc_util import Configuration
- config = Configuration('reason', parent_package, top_path)
- config.make_config_py() # installs __config__.py
- #config.make_svn_version_py()
- return config
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/widget_builders.py
--- a/yt/gui/reason/widget_builders.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""
-These widget objects provide the interaction to yt tasks.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-from yt.mods import *
-import weakref
-
-class RenderingScene(object):
- _camera = None
- _tf = None
-
- def __init__(self, ds, camera=None, tf=None):
- self.ds = weakref.proxy(ds)
- self._camera = camera
- self._tf = tf
-
- self.center = self.ds.domain_center
- self.normal_vector = np.array([0.7,1.0,0.3])
- self.north_vector = [0.,0.,1.]
- self.steady_north = True
- self.fields = ['Density']
- self.log_fields = [True]
- self.l_max = 0
- self.mi = None
- self.ma = None
- if self._tf is None:
- self._new_tf(self.ds)
-
- if self._camera is None:
- self._new_camera(self.ds)
-
- def _new_tf(self, ds, mi=None, ma=None, nbins=1024):
- if mi is None or ma is None:
- roi = self.ds.region(self.center, self.center-self.width, self.center+self.width)
- self.mi, self.ma = roi.quantities['Extrema'](self.fields[0])[0]
- if self.log_fields[0]:
- self.mi, self.ma = np.log10(self.mi), np.log10(self.ma)
-
- self._tf = ColorTransferFunction((self.mi-2, self.ma+2), nbins=nbins)
-
- def add_contours(self, n_contours=7, contour_width=0.05, colormap='kamae'):
- self._tf.add_layers(n_contours=n_contours ,w=contour_width,
- col_bounds = (self.mi,self.ma),
- colormap=colormap)
-
- def _new_camera(self, ds):
- del self._camera
- self._camera = self.ds.camera(self.center, self.normal_vector,
- self.width, self.resolution, self._tf,
- north_vector=self.north_vector,
- steady_north=self.steady_north,
- fields=self.fields, log_fields=self.log_fields,
- l_max=self.l_max)
- def snapshot(self):
- return self._camera.snapshot()
-
-
-def get_corners(ds, max_level=None):
- DL = ds.domain_left_edge[None,:,None]
- DW = ds.domain_width[None,:,None]/100.0
- corners = ((ds.grid_corners-DL)/DW)
- levels = ds.grid_levels
- return corners, levels
-
-def get_isocontour(ds, field, value=None, rel_val = False):
-
- dd = ds.h.all_data()
- if value is None or rel_val:
- if value is None: value = 0.5
- mi, ma = np.log10(dd.quantities["Extrema"]("Density")[0])
- value = 10.0**(value*(ma - mi) + mi)
- vert = dd.extract_isocontours("Density", value)
- np.multiply(vert, 100, vert)
- return vert
-
-def get_streamlines(ds):
- from yt.visualization.api import Streamlines
- streamlines = Streamlines(ds, ds.domain_center)
- streamlines.integrate_through_volume()
- stream = streamlines.path(0)
- matplotlib.pylab.semilogy(stream['t'], stream['Density'], '-x')
-
-
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/reason/widget_store.py
--- a/yt/gui/reason/widget_store.py
+++ /dev/null
@@ -1,299 +0,0 @@
-"""
-This is a place to store widgets, and to create them.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from yt.mods import *
-import weakref
-from .bottle_mods import PayloadHandler, lockit
-from .widget_builders import RenderingScene, get_corners, get_isocontour
-from yt.visualization.plot_window import PWViewerExtJS
-from yt.visualization.volume_rendering.create_spline import create_spline
-import uuid
-
-_phase_plot_mds = """<pre>
-Field X: %s
-Field Y: %s
-Field Z: %s
-Weight : %s
-</pre>
-"""
-
-class WidgetStore(dict):
- def __init__(self, global_token = ""):
- self._global_token = global_token
- self.payload_handler = PayloadHandler()
- super(WidgetStore, self).__init__()
-
- def _add_widget(self, widget, widget_data = None):
- # We need to make sure that we aren't running in advance of a new
- # object being added.
- #uu = str(uuid.uuid1()).replace("-","_")
- #varname = "%s_%s" % (widget._widget_name, uu)
- varname = "%s_%s" % (widget._widget_name, len(self))
- widget._ext_widget_id = varname
- payload = {'type': 'widget',
- 'widget_type': widget._widget_name,
- 'varname': varname}
- widget._ext_widget_id = varname
- payload['data'] = widget_data
- self[varname] = widget
- self.payload_handler.add_payload(payload)
-
- def activate_multicast(self, widget_id, multicast_session, multicast_token):
- # Here we have to conduct the handshake between us and the GAE
- self.payload_handler.multicast_ids[widget_id] = (
- multicast_session, multicast_token)
- mylog.info("Multicasting %s to %s", widget_id, multicast_session)
-
- def create_slice(self, ds, center, axis, field, onmax):
- if onmax:
- center = ds.h.find_max('Density')[1]
- else:
- center = np.array(center)
- axis = ds.coordinates.axis_id[axis.lower()]
- coord = center[axis]
- sl = ds.slice(axis, coord, center = center)
- xax = ds.coordinates.x_axis[axis]
- yax = ds.coordinates.y_axis[axis]
- DLE, DRE = ds.domain_left_edge, ds.domain_right_edge
- pw = PWViewerExtJS(sl, (DLE[xax], DRE[xax], DLE[yax], DRE[yax]),
- setup = False, plot_type='SlicePlot')
- pw.set_current_field(field)
- field_list = list(set(ds.field_list + ds.derived_field_list))
- field_list = [dict(text = f) for f in sorted(field_list)]
- cb = pw._get_cbar_image()
- trans = pw._field_transform[pw._current_field].name
- widget_data = {'fields': field_list,
- 'initial_field': field,
- 'title': "%s Slice" % (ds),
- 'colorbar': cb,
- 'initial_transform' : trans}
- self._add_widget(pw, widget_data)
-
- def create_proj(self, ds, axis, field, weight):
- if weight == "None": weight = None
- axis = ds.coordinates.axis_id[axis.lower()]
- proj = ds.proj(field, axis, weight_field=weight)
- xax = ds.coordinates.x_axis[axis]
- yax = ds.coordinates.y_axis[axis]
- DLE, DRE = ds.domain_left_edge, ds.domain_right_edge
- pw = PWViewerExtJS(proj, (DLE[xax], DRE[xax], DLE[yax], DRE[yax]),
- setup = False, plot_type='ProjectionPlot')
- pw.set_current_field(field)
- field_list = list(set(ds.field_list + ds.derived_field_list))
- field_list = [dict(text = f) for f in sorted(field_list)]
- cb = pw._get_cbar_image()
- widget_data = {'fields': field_list,
- 'initial_field': field,
- 'title': "%s Projection" % (ds),
- 'colorbar': cb}
- self._add_widget(pw, widget_data)
-
- def create_grid_dataview(self, ds):
- levels = ds.grid_levels
- left_edge = ds.grid_left_edge
- right_edge = ds.grid_right_edge
- dimensions = ds.grid_dimensions
- cell_counts = ds.grid_dimensions.prod(axis=1)
- # This is annoying, and not ... that happy for memory.
- i = ds.index.grids[0]._id_offset
- vals = []
- for i, (L, LE, RE, dim, cell) in enumerate(zip(
- levels, left_edge, right_edge, dimensions, cell_counts)):
- vals.append([ int(i), int(L[0]),
- float(LE[0]), float(LE[1]), float(LE[2]),
- float(RE[0]), float(RE[1]), float(RE[2]),
- int(dim[0]), int(dim[1]), int(dim[2]),
- int(cell)] )
- varname = "gg_%s" % (len(self))
- self[varname] = None
- payload = {'type': 'widget',
- 'widget_type': 'grid_data',
- 'varname': varname, # Is just "None"
- 'data': dict(gridvals = vals),
- }
- self.payload_handler.add_payload(payload)
-
- def create_ds_display(self, ds):
- widget = ParameterFileWidget(ds)
- widget_data = {'fields': widget._field_list(),
- 'level_stats': widget._level_stats(),
- 'ds_info': widget._ds_info(),
- }
- self._add_widget(widget, widget_data)
-
- def create_mapview(self, widget_name):
- widget = self[widget_name]
- # We want multiple maps simultaneously
- uu = "/%s/%s" % (self._global_token,
- str(uuid.uuid1()).replace("-","_"))
- from .pannable_map import PannableMapServer
- data = widget.data_source
- field_name = widget._current_field
- pm = PannableMapServer(data, field_name, route_prefix = uu)
- widget_data = {'prefix': uu, 'field':field_name}
- self._add_widget(pm, widget_data)
-
- def create_phase(self, obj, field_x, field_y, field_z, weight):
- from yt.visualization.profile_plotter import PhasePlotterExtWidget
- pp = PhasePlotterExtWidget(obj, field_x, field_y, field_z, weight)
- mds = _phase_plot_mds % (field_x, field_y, field_z,
- pp._initial_weight)
- widget_data = {'title': "%s Phase Plot" % (obj),
- 'metadata_string': mds}
- self._add_widget(pp, widget_data)
-
- def create_scene(self, ds):
- '''Creates 3D XTK-based scene'''
- widget = SceneWidget(ds)
- field_list = list(set(ds.field_list
- + ds.derived_field_list))
- field_list.sort()
- widget_data = {'title':'Scene for %s' % ds,
- 'fields': field_list}
- self._add_widget(widget, widget_data)
-
-
-class ParameterFileWidget(object):
- _ext_widget_id = None
- _widget_name = "parameterfile"
-
- def __init__(self, ds):
- self.ds = weakref.proxy(ds)
-
- def _field_list(self):
- field_list = list(set(self.ds.field_list
- + self.ds.derived_field_list))
- field_list.sort()
- return [dict(text = field) for field in field_list]
-
- def _level_stats(self):
- level_data = []
- level_stats = self.ds.h.level_stats
- ngrids = float(level_stats['numgrids'].sum())
- ncells = float(level_stats['numcells'].sum())
- for level in range(self.ds.h.max_level + 1):
- cell_count = level_stats['numcells'][level]
- grid_count = level_stats['numgrids'][level]
- level_data.append({'level' : level,
- 'cell_count': int(cell_count),
- 'grid_count': int(grid_count),
- 'cell_rel': int(100*cell_count/ncells),
- 'grid_rel': int(100*grid_count/ngrids)})
- return level_data
-
- def _ds_info(self):
- tr = {}
- for k, v in self.ds._mrep._attrs.items():
- if isinstance(v, np.ndarray):
- tr[k] = v.tolist()
- else:
- tr[k] = v
- return tr
-
- def deliver_field(self, field):
- ph = PayloadHandler()
- ph.widget_payload(self,
- {'ptype':'field_info',
- 'field_source': self.ds.field_info[field].get_source() })
- return
-
-class SceneWidget(object):
- _ext_widget_id = None
- _widget_name = "scene"
- _rendering_scene = None
-
- def __init__(self, ds):
- self.ds = weakref.proxy(ds)
-
- def add_volume_rendering(self):
- return None
- self._rendering_scene = RenderingScene(self.ds, None, None)
-
- def deliver_rendering(self, scene_config):
- ph = PayloadHandler()
- ph.widget_payload(self, {'ptype':'rendering',
- 'image':self._rendering_scene.snapshot()})
- return
-
- def deliver_isocontour(self, field, value, rel_val = False):
- ph = PayloadHandler()
- vert = get_isocontour(self.ds, field, value, rel_val)
- normals = np.empty(vert.shape)
- for i in range(vert.shape[0]/3):
- n = np.cross(vert[i*3,:], vert[i*3+1,:])
- normals[i*3:i*3+3,:] = n[None,:]
- ph.widget_payload(self, {'ptype':'isocontour',
- 'binary': ['vert', 'normals'],
- 'vert':vert,
- 'normals':normals})
-
- def deliver_gridlines(self):
- ph = PayloadHandler()
- corners, levels = get_corners(self.ds)
- ph.widget_payload(self, {'ptype':'grid_lines',
- 'binary': ['corners', 'levels'],
- 'corners': corners,
- 'levels': levels,
- 'max_level': int(self.ds.h.max_level)})
- return
-
- def render_path(self, views, times, N):
- # Assume that path comes in as a list of matrice
- # Assume original vector is (0., 0., 1.), up is (0., 1., 0.)
-
- views = [np.array(view).transpose() for view in views]
-
- times = np.linspace(0.0,1.0,len(times))
-
- # This is wrong.
- reflect = np.array([[1,0,0],[0,1,0],[0,0,-1]])
-
- rots = np.array([R[0:3,0:3] for R in views])
-
- rots = np.array([np.dot(reflect,rot) for rot in rots])
-
- centers = np.array([np.dot(rot,R[0:3,3]) for R,rot in zip(views,rots)])
-
- ups = np.array([np.dot(rot,R[0:3,1]) for R,rot in zip(views,rots)])
-
- #print 'views'
- #for view in views: print view
- #print 'rots'
- #for rot in rots: print rot
- #print 'centers'
- #for center in centers: print center
- #print 'ups'
- #for up in ups: print up
-
- pos = np.empty((N,3), dtype="float64")
- uv = np.empty((N,3), dtype="float64")
- f = np.zeros((N,3), dtype="float64")
- for i in range(3):
- pos[:,i] = create_spline(times, centers[:,i], np.linspace(0.0,1.0,N))
- uv[:,i] = create_spline(times, ups[:,i], np.linspace(0.0,1.0,N))
-
- path = [pos.tolist(), f.tolist(), uv.tolist()]
-
- ph = PayloadHandler()
- ph.widget_payload(self, {'ptype':'camerapath',
- 'data':path,})
-
- return
-
-
- def deliver_streamlines(self):
- ds = PayloadHandler()
- pass
-
diff -r 105458124524bb225bc5e47720993d1b72d03796 -r 8b9ce73b435cc1889aeaa933b87c143bc507beba yt/gui/setup.py
--- a/yt/gui/setup.py
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/usr/bin/env python
-import setuptools
-import os
-import sys
-import os.path
-
-
-def configuration(parent_package='', top_path=None):
- from numpy.distutils.misc_util import Configuration
- config = Configuration('gui', parent_package, top_path)
- config.add_subpackage('reason')
- config.make_config_py() # installs __config__.py
- #config.make_svn_version_py()
- return config
https://bitbucket.org/yt_analysis/yt/commits/920743b09e59/
Changeset: 920743b09e59
Branch: yt
User: ngoldbaum
Date: 2015-08-24 18:11:53+00:00
Summary: Removing the image_panner
This is not used elsewhere in yt and is not exposed in the public API
Affected #: 5 files
diff -r 8b9ce73b435cc1889aeaa933b87c143bc507beba -r 920743b09e591e126e18a2986cff0f7125cfc635 yt/visualization/image_panner/__init__.py
--- a/yt/visualization/image_panner/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
diff -r 8b9ce73b435cc1889aeaa933b87c143bc507beba -r 920743b09e591e126e18a2986cff0f7125cfc635 yt/visualization/image_panner/api.py
--- a/yt/visualization/image_panner/api.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-API for yt.visualization.image_panner
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from .vm_panner import VariableMeshPanner, WindowedVariableMeshPanner, \
- MultipleWindowVariableMeshPanner, ImageSaver, \
- PanningCeleritasStreamer, NonLocalDataImagePanner
diff -r 8b9ce73b435cc1889aeaa933b87c143bc507beba -r 920743b09e591e126e18a2986cff0f7125cfc635 yt/visualization/image_panner/setup.py
--- a/yt/visualization/image_panner/setup.py
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env python
-
-
-def configuration(parent_package='', top_path=None):
- from numpy.distutils.misc_util import Configuration
- config = Configuration('image_panner', parent_package, top_path)
- config.make_config_py() # installs __config__.py
- #config.make_svn_version_py()
- return config
diff -r 8b9ce73b435cc1889aeaa933b87c143bc507beba -r 920743b09e591e126e18a2986cff0f7125cfc635 yt/visualization/image_panner/vm_panner.py
--- a/yt/visualization/image_panner/vm_panner.py
+++ /dev/null
@@ -1,303 +0,0 @@
-"""
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import base64
-
-import numpy as np
-from yt.visualization.fixed_resolution import \
- FixedResolutionBuffer
-from yt.data_objects.data_containers import \
- data_object_registry
-from yt.funcs import iterable
-
-class VariableMeshPanner(object):
- _buffer = None
- _hold = False
-
- def __init__(self, source, size, field, callback = None,
- viewport_callback = None):
- """
- This class describes a meta-view onto a 2D data interface. You provide
- it with a slice or a projection (*source*), a tuple of the x and y
- resolution of the final image you want (*size) and a *field* to
- display, and then it will generate a new buffer each time you call its
- methods for moving the window around and changing its size. *callback*
- is a routine called with the new buffer each time the buffer changes
- and *viewport_callback* is called with the new *xlim* and *ylim* values
- each time the viewport changes.
- """
- #if not isinstance(source, (YTOverlapProjBase, YTSliceBase)):
- # raise RuntimeError
- if callback is None:
- callback = lambda a: None
- self.callback = callback
- if viewport_callback is None:
- viewport_callback = lambda a, b: None
- self.viewport_callback = viewport_callback
- self.size = size
- self.source = source
- self.field = field
- self.xlim, self.ylim = self.bounds
-
- def _run_callbacks(self):
- if self._hold: return
- self.callback(self.buffer)
- self.viewport_callback(self.xlim, self.ylim)
-
- @property
- def bounds(self):
- if not hasattr(self, 'ds'): self.ds = self.source.ds
- DLE, DRE = self.ds.domain_left_edge, self.ds.domain_right_edge
- ax = self.source.axis
- xax = self.ds.coordinates.x_axis[ax]
- yax = self.ds.coordinates.y_axis[ax]
- xbounds = DLE[xax], DRE[xax]
- ybounds = DLE[yax], DRE[yax]
- return (xbounds, ybounds)
-
- @property
- def width(self):
- Wx = self.xlim[1] - self.xlim[0]
- Wy = self.ylim[1] - self.ylim[0]
- return (Wx, Wy)
-
- def zoom(self, factor):
- """
- This zooms the window by *factor*.
- """
- Wx, Wy = self.width
- centerx = self.xlim[0] + Wx*0.5
- centery = self.ylim[0] + Wy*0.5
- nWx, nWy = Wx/factor, Wy/factor
- self.xlim = (centerx - nWx*0.5, centerx + nWx*0.5)
- self.ylim = (centery - nWy*0.5, centery + nWy*0.5)
- self._run_callbacks()
-
- def pan(self, deltas):
- """
- This accepts a tuple of *deltas*, composed of (delta_x, delta_y) that
- will pan the window by those values in absolute coordinates.
- """
- self.xlim = (self.xlim[0] + deltas[0], self.xlim[1] + deltas[0])
- self.ylim = (self.ylim[0] + deltas[1], self.ylim[1] + deltas[1])
- self._run_callbacks()
-
- def pan_x(self, delta):
- """
- This pans the window by *delta* in the x direction.
- """
- self.pan( (delta, 0.0) )
-
- def pan_y(self, delta):
- """
- This pans the window by *delta* in the y direction.
- """
- self.pan( (0.0, delta) )
-
- def pan_rel(self, deltas):
- """
- This accepts a tuple of *deltas*, composed of (delta_x, delta_y) that
- will pan the window by those values in relative values, relative to the
- current window view.
- """
- Wx, Wy = self.width
- px = deltas[0] * Wx
- py = deltas[1] * Wy
- self.pan( (px, py) )
-
- def pan_rel_x(self, delta):
- """
- This pans the window by *delta* in the x direction, where *delta* is
- relative to the current window view.
- """
- self.pan_rel( (delta, 0.0) )
-
- def pan_rel_y(self, delta):
- """
- This pans the window by *delta* in the y direction, where *delta* is
- relative to the current window view.
- """
- self.pan_rel( (0.0, delta) )
-
- @property
- def buffer(self):
- my_bounds = self.xlim + self.ylim # Tuples concatenate
- # If the buffer is None, we just kill it regardless.
- if self._buffer is None:
- self._regenerate_buffer()
- elif self._buffer.bounds != my_bounds:
- self._regenerate_buffer()
- return self._buffer[self.field]
-
- def _regenerate_buffer(self):
- new_buffer = FixedResolutionBuffer(
- self.source, self.xlim + self.ylim,
- self.size)
- self._buffer = new_buffer
-
- def set_low_high(self, low, high):
- """
- This accepts *low* in the format (x_min, y_min) and *high* in the
- format (x_max, y_max) and changes the viewport appropriately. In
- breaking from tradition, it also returns the buffer.
- """
- self.xlim = (low[0], high[0])
- self.ylim = (low[1], high[1])
- return np.log10(self.buffer)
-
- def set_width(self, width):
- """
- This sets the width based on the current center.
- """
- if not iterable(width): width = (width, width)
- Wx, Wy = self.width
- centerx = self.xlim[0] + Wx*0.5
- centery = self.ylim[0] + Wy*0.5
- self.xlim = (centerx - width[0]/2.0,
- centerx + width[0]/2.0)
- self.ylim = (centery - width[1]/2.0,
- centery + width[1]/2.0)
- self._run_callbacks()
-
- def set_limits(self, xlim, ylim):
- """
- This accepts a new *xlim* and *ylim*.
- """
- self.xlim = xlim
- self.ylim = ylim
- self._run_callbacks()
-
- def set_center(self, center):
- if len(center) == 2:
- centerx, centery = center
- elif len(center) == 3:
- xax = self.ds.coordinates.x_axis[self.source.axis]
- yax = self.ds.coordinates.y_axis[self.source.axis]
- centerx = center[xax]
- centery = center[yax]
- else:
- raise RuntimeError
- Wx, Wy = self.width
- self.xlim = (centerx - Wx*0.5, centerx + Wx*0.5)
- self.ylim = (centery - Wy*0.5, centery + Wy*0.5)
- self._run_callbacks()
-
-data_object_registry["image_panner"] = VariableMeshPanner
-
-class WindowedVariableMeshPanner(VariableMeshPanner):
-
- def __init__(self, source, full_size, my_size, start_indices,
- field, callback = None):
- """
- This image panner accepts a *full_size*, which describes the full size
- of the image which it will be displaying a portion of. *my_size* is
- the size that this window will be responsible for, and *start_indices*
- is a tuple of indices that this window begins at. *field* and
- *callback* function as in the vanilla image panner.
- """
- self.my_size = my_size
- self.start_indices = start_indices
- VariableMeshPanner.__init__(self, source, full_size, field, callback)
-
- def _regenerate_buffer(self):
- dx = (self.xlim[1] - self.xlim[0])/self.size[0]
- dy = (self.ylim[1] - self.ylim[0])/self.size[1]
- my_lim = (self.xlim[0] + dx*self.start_indices[0],
- self.xlim[0] + dx*(self.start_indices[0] + self.my_size[0]),
- self.ylim[0] + dy*self.start_indices[1],
- self.ylim[0] + dy*(self.start_indices[1] + self.my_size[1]))
- new_buffer = FixedResolutionBuffer(self.source, my_lim, self.my_size)
- self._buffer = new_buffer
-
-data_object_registry["windowed_image_panner"] = WindowedVariableMeshPanner
-
-class MultipleWindowVariableMeshPanner(object):
- def __init__(self, windows):
- """
- This panner is exclusively a controller. It accepts a list of
- *windows*, to which it will issue commands. It knows nothing other
- than their interfaces.
- """
- self.windows = windows
-
- def zoom(self, factor):
- for w in self.windows: w.zoom(factor)
-
- def pan(self, deltas):
- for w in self.windows: w.pan(deltas)
-
- def pan_x(self, delta):
- for w in self.windows: w.pan_x(delta)
-
- def pan_y(self, delta):
- for w in self.windows: w.pan_y(delta)
-
- def pan_rel(self, deltas):
- for w in self.windows: w.pan_rel(deltas)
-
- def pan_rel_x(self, delta):
- for w in self.windows: w.pan_rel_x(delta)
-
- def pan_rel_y(self, delta):
- for w in self.windows: w.pan_rel_y(delta)
-
- def set_limits(self, xlim, ylim):
- for w in self.windows: w.set_limits(xlim, ylim)
-
-class ImageSaver(object):
- def __init__(self, tile_id):
- """
- This is a sample callback for an image panner that will save to a file
- named ``wimage_%03i.png`` where the final variable is specified here as
- *tile_id*.
- """
- self.tile_id = tile_id
-
- import matplotlib
- matplotlib.use("Agg")
- import pylab
- self.pylab = pylab
- self.pylab.clf()
- fig = pylab.gcf()
- fig.subplots_adjust(left=0.0, bottom=0.0,
- right=1.0, top=1.0,
- wspace=0.0, hspace=0.0)
- fig.set_dpi(100.0)
- fig.set_size_inches((5.12, 5.12))
-
- def __call__(self, val):
- self.pylab.clf()
- self.pylab.imshow(np.log10(val), interpolation='nearest')
- self.pylab.savefig("wimage_%03i.png" % self.tile_id)
-
-class TransportAppender(object):
- def __init__(self, transport):
- """
- This is a simple callback that appends the latest buffer to the
- supplied *transport* object.
- """
- self.transport = transport
-
- def __call__(self, val):
- from yt.utilities.png_writer import write_png_to_string
- from yt.visualization.image_writer import map_to_colors
- image = np.log10(val)
- mi = np.nanmin(image[~np.isinf(image)])
- ma = np.nanmax(image[~np.isinf(image)])
- color_bounds = mi, ma
- image = (image - color_bounds[0])/(color_bounds[1] - color_bounds[0])
- to_plot = map_to_colors(image, "algae")
- to_plot = np.clip(to_plot, 0, 255)
- s = write_png_to_string(to_plot)
- response_body = "data:image/png;base64," + base64.encodestring(s)
- self.transport.append(response_body)
diff -r 8b9ce73b435cc1889aeaa933b87c143bc507beba -r 920743b09e591e126e18a2986cff0f7125cfc635 yt/visualization/setup.py
--- a/yt/visualization/setup.py
+++ b/yt/visualization/setup.py
@@ -4,7 +4,6 @@
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('visualization', parent_package, top_path)
- config.add_subpackage("image_panner")
config.add_subpackage("volume_rendering")
config.add_subpackage("tests")
config.make_config_py() # installs __config__.py
https://bitbucket.org/yt_analysis/yt/commits/a59bffb6db85/
Changeset: a59bffb6db85
Branch: yt
User: ngoldbaum
Date: 2015-08-24 18:13:11+00:00
Summary: Ensure mapserver package gets deployed in source installs
Affected #: 1 file
diff -r 920743b09e591e126e18a2986cff0f7125cfc635 -r a59bffb6db85cf362376b5d9beee09adcd59fccb yt/visualization/setup.py
--- a/yt/visualization/setup.py
+++ b/yt/visualization/setup.py
@@ -4,6 +4,7 @@
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('visualization', parent_package, top_path)
+ config.add_subpackage("mapserver")
config.add_subpackage("volume_rendering")
config.add_subpackage("tests")
config.make_config_py() # installs __config__.py
https://bitbucket.org/yt_analysis/yt/commits/33dadd43445d/
Changeset: 33dadd43445d
Branch: yt
User: ngoldbaum
Date: 2015-08-24 18:19:52+00:00
Summary: Remove most reason files
Affected #: 98 files
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app.js
--- a/yt/visualization/mapserver/html/app.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/**********************************************************************
-The main GUI facility for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.Loader.setConfig({enabled:true});
-
-var reason, rdebug, examine;
-
-Ext.application({
- requires: ['Ext.container.Viewport',
- 'Reason.view.LoggingGrid',
- 'Reason.view.DataObjectTree',
- 'Reason.controller.widgets.SampleWidget',
- ],
- name: 'Reason',
-
- appFolder: 'reason/app',
-
- launch: function() {
- reason = this;
- this.numberOfRequests = 0;
- rdebug = this.getController("Debugger");
- this.server = this.getController("ServerCommunication");
- Ext.create('Ext.container.Viewport', {
- layout: 'border',
- items: [
- {
- xtype: 'logginggrid',
- autofill: true,
- region: 'south',
- id: "status-region",
- cls: "status-logger",
- split: true,
- height: 100,
- maxSize: 200,
- collapsible: true,
- title: 'Status',
- margins: '0 0 0 0',
- }, {
- id: 'west-panel',
- region: 'west',
- split: true,
- width: 200,
- minSize: 175,
- maxSize: 400,
- collapsible: true,
- layout: {
- type: 'vbox',
- pack: 'start',
- align: 'stretch',
- },
- items: [
- { xtype: 'dataobjecttree',
- flex: 1.0},
- { xtype: 'panel',
- tpl: 'Pending Requests: {0}',
- data: [0],
- height: 30,
- id: 'pending',
- }
- ],
- }, {
- xtype: 'tabpanel',
- region: 'center',
- id: 'center-panel',
- activeTab: 0,
- dockedItems: [ {
- dock: 'top',
- xtype: 'mainmenu',
- } ],
- items: [
- { xtype: 'panel',
- title: 'Welcome!',
- closeable: true,
- autoLoad: 'help.html',
- },
- { xtype: 'ytnotebook' },
- ]
- }
- ]
- });
- this.pending = Ext.getCmp("pending");
- this.fireEvent("allowinput");
- },
- controllers : [
- 'Logging',
- 'DataObjects',
- 'Notebook',
- 'ServerCommunication',
- 'WidgetDirector',
- 'MenuActions',
- 'Debugger',
- 'FileOpen',
- ],
-
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/DataObjects.js
--- a/yt/visualization/mapserver/html/app/controller/DataObjects.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/**********************************************************************
-Data object controller for Reason
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-***********************************************************************/
-
-Ext.define('Reason.controller.DataObjects', {
- extend: 'Ext.app.Controller',
- stores: [ 'DataObjects' ],
- models: ['DataObject'],
- view: ['DataObjectTree'],
- refs: [
- { ref: 'dataObjectTree',
- selector: 'dataobjecttree#dataobjects',
- xtype: 'dataobjecttree',
- itemId: 'dataobjects',
- autoCreate: true,
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloaddataobjects : {fn: this.refreshDataObjects, scope: this},
- });
- this.control({
- "#dataobjects": { itemcontextmenu:
- function(view, rec, node, index, e) {
- e.preventDefault();
- this.application.fireEvent("showwidgets", rec, e);
- }
- }});
- this.callParent(arguments);
- },
-
- refreshDataObjects: function(payload) {
- /*console.log("Refreshing data objects");*/
- var objs = payload['objs'];
- var root = this.getDataObjectsStore().getRootNode();
- root.removeAll();
- var pf;
- Ext.each(objs, function(o, i, os) {
- /*console.log("Appending " + o['name']);*/
- pf = root.appendChild({
- name: o.name,
- type: o.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: o.varname,
- leaf: false,
- expanded: true,
- iconCls: 'pf_icon'
- });
- Ext.each(o['children'], function(c, ci, cs) {
- /*console.log(" Appending " + c['name']);*/
- pf.appendChild({name: c.name,
- type: c.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: c.varname,
- leaf: true,
- iconcls: 'data_obj'});
-
- });
- });
- },
-});
-
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/Debugger.js
--- a/yt/visualization/mapserver/html/app/controller/Debugger.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**********************************************************************
-Debug helper for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Debugger', {
- extend: 'Ext.app.Controller',
- stores: ['WidgetTypes', 'WidgetInstances', 'Requests'],
-
- getWidget: function(widgetId) {
- this.getWidgetInstancesStore().find(
- {'widgetid': widgetId});
- var widgetInfo = this.getWidgetInstancesStore().getAt(resultId).data;
- return widgetInfo.widget;
- },
-
- getAllWidgetsByType: function(typeName) {
- var arr = []
- this.getWidgetInstancesStore().each(function(r) {
- if (r.data['widgettype'] == typeName) {
- arr.push(r.data);
- }
- });
- return arr;
- },
-
-});
-
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/FileOpen.js
--- a/yt/visualization/mapserver/html/app/controller/FileOpen.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/**********************************************************************
-File Open Dialog for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.FileOpen', {
- extend: 'Ext.app.Controller',
- stores: ['FileListing'],
- requires: ["Reason.view.FileOpen"],
-
- init: function() {
-
- },
-
- openDialog: function() {
- this.currentDirectory = '',
- this.getFileListingStore().removeAll();
- reason.server.method("file_listing",
- {base_dir:"", sub_dir:""}, this.fillStore);
- this.win = Ext.widget("fileopenwindow");
- this.win.query("#file_listing")[0].bindStore(this.getFileListingStore());
- /* Set up our handlers */
- this.control({
- '#current_file': { specialkey: this.specialKeyPressed, },
- '#file_listing': { celldblclick: this.doubleClicked, },
- '#load': { click: this.loadFile, },
- '#cancel': { click: this.cancelWindow, }
- });
- this.win.show();
- },
-
- specialKeyPressed: function(f, e) {
- if (e.getKey() != e.ENTER) { return; }
- reason.server.method("file_listing",
- {base_dir:f.getValue(), sub_dir:""}, this.fillStore);
- },
-
- doubleClicked: function(view, td, cellIndex, record) {
- conf = {'base_dir': this.currentDirectory};
- if (record.data.type == 'directory') {
- conf['sub_dir'] = record.data.filename;
- reason.server.method('file_listing', conf, this.fillStore);
- } else {
- conf['filename'] = record.data.filename;
- reason.server.method('load', conf);
- this.win.destroy();
- }
- },
-
- loadFile: function(b, e) {
- var conf = {filename: '', base_dir: this.currentDirectory};
- var fl = this.win.query("#file_listing")[0];
- var idx = fl.getSelectionModel().getSelection();
- if (idx == 1) {
- conf['filename'] = this.getFileListingStore().getAt(idx).data.filename;
- }
- reason.server.method('load', conf);
- },
-
- cancelWindow: function(b, e) {
- this.win.destroy();
- },
-
- fillStore: function(f, a) {
- var con = reason.getController("FileOpen");
- if(a.status == false){
- Ext.Msg.alert("Error", "Something has gone wrong.");
- con.window.destroy();
- }
- if(a.result['change'] == false) {
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- return;
- }
- con.getFileListingStore().removeAll();
- var rec = [];
- con.getFileListingStore().loadData(a.result['objs']);
- con.currentDirectory = a.result['cur_dir'];
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- },
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/Logging.js
--- a/yt/visualization/mapserver/html/app/controller/Logging.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**********************************************************************
-Logging entry controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Logging', {
- extend: 'Ext.app.Controller',
- stores: [ 'LogEntries' ],
- view: ['LoggingGrid'],
-
- refs: [
- { ref: 'logEntries',
- selector: '#logentries'
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadlogentry: {fn: this.addLogPayload, scope: this},
- logentry: {fn: this.addLogEntry, scope: this},
- });
- },
-
- addLogPayload: function(payload) {
- this.addLogEntry(payload['log_entry']);
- },
-
- addLogEntry: function(text) {
- this.getLogEntriesStore().add({record: text});
- var i = this.getLogEntriesStore().getCount();
- this.getLogEntries().getView().focusRow(i - 1);
- },
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/MenuActions.js
--- a/yt/visualization/mapserver/html/app/controller/MenuActions.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**********************************************************************
-Menu actions in Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-
-Ext.define('Reason.controller.MenuActions', {
- extend: 'Ext.app.Controller',
- views: ['MainMenu'],
-
- init: function() {
- this.control({
- '#openfile': { click: this.openFile },
- '#savescript': { click: this.saveScript},
- '#downloadscript': { click: this.downloadScript },
- '#pastebinscript': { click: this.pastebinScript },
- '#ytchat': {click: this.openIRCChannel },
- '#quit': {click: this.quitReason },
- '#enabledebug': {click: this.enableDebug },
- });
- this.callParent(arguments);
- },
-
- saveScript: function (b,e) {
- /* This function gets called on success */
- var controller = this;
- function handleResponse(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Saved session to ' + a.result['filename'];
- Ext.Msg.alert('Success!', alert_text);
- controller.application.fireEvent("logentry", alert_text);
- } else {
- Ext.Msg.alert('Always naysaying!',
- 'Failed to save to ' + a.result['filename'] + '<br>Error: ' +
- a.result['error']);
- }
- };
- /* Now we prompt */
- Ext.Msg.prompt("We have important work to do.", "Enter filename.",
- function(btn, text) {
- if (btn == 'ok') {
- reason.server.method('save_session',
- {filename:text}, handleResponse);
- }
- }
- );
- },
-
- openFile: function(b, e) {
- this.application.getController("FileOpen").openDialog();
- },
-
- downloadScript: function(b, e) {
- window.open("session.py", "_top");
- this.application.fireEvent("logentry", 'Saved session locally.')
- },
-
- pastebinScript: function(b, e) {
- reason.server.method('paste_session', {}, function(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Pasted session to:<br>' +
- a.result['site']
- var alert_text_rec = 'Pasted session to: ' +
- a.result['site']
- Ext.Msg.alert('Pastebin', alert_text);
- this.application.fireEvent("logentry", alert_text_rec);
- }
- });
- },
-
- openIRCChannel: function(b, e) {
- window.open("http://yt-project.org/irc.html", "_new");
- },
-
- quitReason: function(b, e) {
- this.application.fireEvent("stopheartbeat");
- reason.server.method('shutdown', {}, function(f, a) {
- Ext.Msg.alert("Goodbye!", "Goodbye from Reason!", function() {
- window.open("http://www.google.com/", "_top");});});
- },
-
- enableDebug: function() {
- this.application.fireEvent("enabledebug");
- },
-});
-
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/Notebook.js
--- a/yt/visualization/mapserver/html/app/controller/Notebook.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/**********************************************************************
-Notebook controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Notebook', {
- extend: 'Ext.app.Controller',
- stores: [ 'CellValues' , 'Requests'],
- views: ['Notebook', 'CellView'],
- refs: [
- { ref: 'inputLine',
- selector: '#inputline'
- },
- { ref: 'cellDisplay',
- selector: 'notebookcells#cells',
- xtype: 'notebookcells',
- autoCreate: true,
- itemId: 'cells',
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadcell: {fn: this.addCell, scope: this},
- payloadscript: {fn: this.loadScript, scope: this},
- executecell: {fn: this.executeCell, scope: this},
- wipeinput: {fn: this.wipeInputLine, scope: this},
- blockinput: {fn: this.blockInput, scope: this},
- allowinput: {fn: this.allowInput, scope: this},
- scrolltobottom: {fn: this.scrollToBottom, scope: this},
- })
- this.control({
- '#executecellbutton': {
- click: function(f, e) {
- this.executeCell(this.getInputLine().getValue());
- }
- },
- '#inputline': {
- specialkey: function(field, e, opts){
- if (e.shiftKey && e.getKey() == e.ENTER) {
- this.executeCell(field.getValue());
- }
- },
- },
- });
- this.callParent(arguments);
- },
-
- addRequest: function(request_id, command) {
- /*console.log("Adding request " + request_id);*/
- this.getRequestsStore().add({
- request_id: request_id, command: command,
- });
- reason.pending.update([this.getRequestsStore().count()]);
- },
-
- addCell: function(cell) {
- this.application.fireEvent("wipeinput");
- this.application.fireEvent("allowinput");
- if (cell['result_id'] != null) {
- var ind = this.getRequestsStore().find(
- 'request_id', cell['result_id']);
- if (ind != -1) {
- /*console.log("Removing request " + cell['result_id']);*/
- var rec = this.getRequestsStore().removeAt(ind);
- }
- reason.pending.update([this.getRequestsStore().count()]);
- }
- if (cell['hide'] == true) { return; }
- this.getCellValuesStore().add({
- input: cell['input'],
- output: cell['output'],
- raw_input: cell['raw_input'],
- image_data: cell['image_data'],
- executiontime: cell['executiontime'],
- result_id: cell['result_id'],
- });
- this.application.fireEvent("scrolltobottom");
- },
-
- loadScript: function(payload) {
- this.getInputLine().setValue(payload['value']);
- this.getInputLine()._lock = true;
- },
-
- executeCell: function(line) {
- this.application.fireEvent("blockinput");
- reason.server.execute(line, false);
- },
-
- scrollToBottom: function() {
- var i = this.getCellValuesStore().getCount();
- this.getCellDisplay().getView().focusRow(i-1);
- },
-
- wipeInputLine: function() {
- if(this.getInputLine()._lock == true) {
- this.getInputLine()._lock = false;
- } else {
- this.getInputLine().setValue("");
- }
- },
-
- blockInput: function() {
- this.getInputLine().addClass("cell_waiting");
- this.getInputLine().setReadOnly(true);
- },
-
- allowInput: function() {
- this.getInputLine().removeCls("cell_waiting");
- this.getInputLine().setReadOnly(false);
- var application = this.application;
- },
-
-});
-
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/ServerCommunication.js
--- a/yt/visualization/mapserver/html/app/controller/ServerCommunication.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/**********************************************************************
-The Payload handling facility for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-var heartbeatRequest = false;
-
-Ext.define('Reason.controller.ServerCommunication', {
- extend: 'Ext.app.Controller',
- stores: ['Payloads'],
- views: ['PayloadGrid'],
- requires: ['Reason.view.MulticastSetup', 'Reason.view.RequestsGrid'],
-
- init: function() {
- this.application.addListener({
- payloadreceived: {fn: this.handlePayload, scope: this},
- stopheartbeat: {fn: this.stopHeartbeat, scope: this},
- enabledebug: {fn: this.enableDebug, scope: this},
- })
- /* We also use this as our heartbeat */
- this.taskRunner = new Ext.util.TaskRunner();
- heartbeatRequest = false;
- this.heartbeat = this.taskRunner.start(
- {run: this.heartbeatCall,
- interval: 250});
- this.callParent(arguments);
- },
-
- handlePayload: function(payload) {
- if ((this.payloadGrid) && (payload['type'] != 'logentry')) {
- var wv = payload['varname'];
- if (payload['type'] == 'widget_payload') {
- wv = payload['widget_id'];
- }
- this.getPayloadsStore().add({
- payloadtype: payload['type'],
- widgettype: payload['widget_type'],
- varname: wv,
- });
- }
- this.application.fireEvent('payload' + payload['type'], payload);
- },
-
- heartbeatCall: function() {
- if (heartbeatRequest == true) return;
- heartbeatRequest = true;
- yt_rpc.ExtDirectREPL.heartbeat(
- {}, function(f, a) {
- heartbeatRequest = false;
- if (f != null) {
- Ext.each(f, function(payload, index) {
- reason.fireEvent("payloadreceived", payload);
- });
- }
- /*else if (!a.status) {
- reason.fireEvent("stopheartbeat");
- Ext.Msg.alert("Error", "Error talking to server. Shutting down.");
- }*/
- return true;
- }
- );
- },
-
- stopHeartbeat: function() {
- this.taskRunner.stopAll();
- },
-
- enableDebug: function() {
- this.payloadGrid = Ext.widget("payloadgrid");
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.payloadGrid);
- this.requestsGrid = Ext.widget('requestsgrid');
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.requestsGrid);
- },
-
- execute: function(code, hide, callback) {
- var fn;
- if (callback) { fn = callback; }
- else { fn = this.returnFromRPC; }
- if (hide == null) { hide = false; }
- reason.fireEvent("disableinput");
- result_id = reason.numberOfRequests + 1;
- reason.numberOfRequests += 1;
- reason.getController("Notebook").addRequest(result_id, code);
- yt_rpc.ExtDirectREPL.execute({
- code: code,
- hide:hide,
- result_id: result_id
- }, fn);
- },
-
- returnFromRPC: function(result, e) {
- if(!e.status) {
- var tpl = new Ext.XTemplate(
- 'RPC Error: {message}; {action}, {method}');
- var trans = e.getTransaction();
- tpl = tpl.apply({message: e.message,
- action: trans.action,
- method: trans.method});
- Ext.Msg.alert("Error", tpl);
- Ext.Error.raise(tpl);
- }
- reason.fireEvent("allowinput");
- },
-
- method: function(methodName, args, callback) {
- var m = yt_rpc.ExtDirectREPL[methodName];
- if (!m) {
- var t = "Could not identify method " + methodName;
- Ext.Msg.alert("Error", t);
- Ext.Error.raise(t);
- }
- var fn;
- if (callback) { fn = callback; }
- else {
- this.application.fireEvent("disableinput");
- fn = this.returnFromRPC;
- }
- m(args, fn);
- },
-
- m: function() { return this.method(arguments); },
-
- multicast: function(widget_var) {
- /*
- This will be two step. The first will be to create a window that
- allows the user to set up the MultiCast session, which will be an
- iframe loading the GAE instance. Then we tell our local server that
- we want to multicast.
- */
- var win = Ext.widget('multicastsetup');
- setupMulticast = function() {
- var cmd = Ext.String.format(
- 'widget_store.activate_multicast("{0}", "{1}", "{2}")',
- widget_var,
- win.query("#session_id")[0].getValue(),
- win.query("#session_token")[0].getValue());
- reason.server.execute(cmd);
- win.destroy();
- }
- win.query('#multicast')[0].on('click', setupMulticast);
- win.query('#cancel')[0].on('click', function(){win.destroy();});
- win.show();
- },
-
-});
-
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/WidgetDirector.js
--- a/yt/visualization/mapserver/html/app/controller/WidgetDirector.js
+++ /dev/null
@@ -1,172 +0,0 @@
-/**********************************************************************
-Widget controller class
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.WidgetDirector', {
- extend: 'Ext.app.Controller',
- requires: ["Reason.controller.widgets.SampleWidget",
- "Reason.controller.widgets.PlotWindow",
- "Reason.controller.widgets.ProgressBar",
- "Reason.controller.widgets.GridDataViewer",
- "Reason.controller.widgets.ParameterFile",
- "Reason.controller.widgets.PannableMap",
- "Reason.controller.widgets.PhasePlot",
- "Reason.controller.widgets.Scene",
- ],
- stores: ['WidgetTypes', 'WidgetInstances'],
- views: ['WidgetTypesGrid', 'WidgetInstancesGrid'],
-
- init: function() {
- Ext.iterate(Reason.controller.widgets, function(i, w, ws) {
- Ext.require(w.getName());
- this.registerWidget(w);
- }, this);
- this.application.addListener({
- createwidget: {fn: this.createWidget, scope: this},
- showwidgets: {fn: this.showWidgetMenu, scope: this},
- payloadwidget: {fn: this.newWidgetCreated, scope: this},
- payloadwidget_payload: {fn: this.sendPayload, scope: this},
- enabledebug: {fn: this.enableDebug, scope: this},
- });
- this.callParent(arguments);
- },
-
- registerWidget: function(w) {
- if (w.widgetName == null) {return;}
- console.log("Registering " + w.widgetName);
- this.getWidgetTypesStore().add({
- widgetname: w.widgetName,
- widgetclass: w,
- displayname: w.displayName,
- pfs: w.supportsParameterFiles,
- objs: w.supportsDataObjects,
- });
- },
-
- createWidget: function(b, e) {
- var w = b.widget;
- console.log("Asked to create " + b.widget.widgetName);
- b.widget.preCreation(b.dataObj);
- },
-
- showWidgetMenu: function(treerecord, e) {
- var contextMenu = Ext.create('Ext.menu.Menu', {plain: true,});
- var data = treerecord.data;
- var w;
- this.getWidgetTypesStore().each(function(record, idx) {
- w = record.data;
- if (((data.type == 'parameter_file') && (w.pfs == false))
- || ((data.type != 'parameter_file') && (w.objs == false))) {
- return;
- }
- contextMenu.add({xtype:'menuitem',
- text: w.displayname,
- listeners: {
- click: {
- fn : this.createWidget,
- scope: this
- },
- },
- widget: w.widgetclass,
- dataObj: data
- });
- }, this);
- contextMenu.showAt(e.getXY());
- },
-
- newWidgetCreated: function(payload) {
- /* We have the following fields:
- type ('widget')
- widget_type
- varname
- data (has subfields)
-
- We now obtain our class, create that with the factory, and we add
- the resultant class to our store.
- */
- var resultId = this.getWidgetTypesStore().find(
- 'widgetname', payload['widget_type']);
- if (resultId == -1) {
- Ext.Error.raise('Did not recognize widget type "' +
- payload['widget_type'] + '".');
- }
- var widgetInfo = this.getWidgetTypesStore().getAt(resultId).data;
- /* The widget adds its view to the viewport. */
- var newWidget = Ext.create(widgetInfo['widgetclass'].getName(),
- {payload: payload});
- console.log("Adding widget payload with varname " + payload['varname']);
- this.getWidgetInstancesStore().add({
- widgetid: payload['varname'],
- widgettype: widgetInfo.widgetname,
- widget: newWidget
- });
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- newWidget.createView());
- },
-
- sendPayload: function(payload) {
- var resultId = this.getWidgetInstancesStore().find(
- 'widgetid', payload['widget_id']);
- if (resultId == -1) {
- Ext.Error.raise('Could not find widget "' +
- payload['widget_id'] + '".');
- }
- /*console.log("Directing payload for " + payload['widget_id'] +
- " to resultId " + resultId);*/
- if (payload['binary'] != null) {
- this.loadBinaryData(payload);
- return;
- }
- var widgetInfo = this.getWidgetInstancesStore().getAt(resultId).data;
- widgetInfo['widget'].applyPayload(payload);
- },
-
- loadBinaryData: function(payload1) {
- /* https://developer.mozilla.org/en/using_xmlhttprequest
- including progress */
- function loadBinaryPayload(payload) {
- var req = new XMLHttpRequest();
- var bkeys = payload['binary'];
- var nLeft = bkeys.length;
- var bkey = bkeys[nLeft - 1];
- var director = this;
- payload['binary'] = null;
- req.open("GET", bkey[1], true);
- req.responseType = "arraybuffer";
- onLoad = function(e) {
- payload[bkey[0]] = req.response;
- nLeft = nLeft - 1;
- if (nLeft == 0) {
- director.sendPayload(payload);
- } else {
- bkey = bkeys[nLeft - 1];
- req.open("GET", bkey[1], true);
- req.responseType = "arraybuffer";
- req.onload = onLoad;
- req.send();
- exaine = payload;
- }
- }
- req.onload = onLoad;
- req.send();
- }
- loadBinaryPayload.call(this, payload1);
- },
-
- enableDebug: function() {
- if(this.instanceView) {return;}
- this.instanceView = Ext.widget('widgetinstancesgrid');
- this.typeView = Ext.widget('widgettypesgrid');
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.instanceView);
- Ext.ComponentQuery.query("viewport > #center-panel")[0].add(
- this.typeView);
- },
-
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/BaseWidget.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/BaseWidget.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/**********************************************************************
-Base widget class
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.require("Reason.templates.TemplateContainer");
-
-Ext.define('Reason.controller.widgets.BaseWidget', {
- extend: 'Ext.app.Controller',
- supportsParameterFiles: false,
- supportsDataObjects: false,
- templateManager: null,
- templates: {},
- executionTriggers: [],
- widgetTriggers: [],
- keyTriggers: [],
-
- constructor: function() {
- this.templateManager = Ext.create(
- "Reason.templates.TemplateContainer",
- { templates: this.templates }
- );
- this.callParent(arguments);
- },
-
- getExecuteFunction: function(ww, templateName, isValidFn) {
- var tpl = new Ext.XTemplate(
- this.templateManager.getTemplates()[templateName]);
- var args = {};
- var control = this;
- function ev() {
- var myArgs = arguments;
- Ext.each(arguments, function(v, i) {
- args["a" + i] = myArgs[i];
- });
- args['control'] = control;
- args['widget'] = ww;
- if((isValidFn != null) && (isValidFn(arguments) == false)) {return;}
- reason.server.execute(tpl.apply(args), true);
- };
- return ev;
- },
-
- applyExecuteHandlers: function(ww) {
- var conf;
- function ef(id, ename, tpl, isValidFn) {
- conf = {}
- conf[ename] = this.getExecuteFunction(ww, tpl);
- ww.query(id)[0].on(conf);
- };
- Ext.each(this.executionTriggers, function(trigger) {
- ef.call(this, trigger[0], trigger[1], trigger[2], trigger[3]);
- }, this);
- Ext.each(this.widgetTriggers, function(trigger) {
- conf = {scope:this}
- conf[trigger[1]] = this[trigger[2]];
- ww.query(trigger[0])[0].on(conf);
- }, this);
-
- this.keyMap = new Ext.util.KeyMap({target: document});
- this.keyMap.disable();
- Ext.each(this.keyTriggers, function(trigger) {
- trigger['fn'] = this.getExecuteFunction(ww, trigger['tpl']);
- this.keyMap.addBinding(trigger);
- }, this);
- ww.on("activate", this.activateKeyMap, this);
- ww.on("deactivate", this.deactivateKeyMap, this);
- },
-
- activateKeyMap: function() {
- this.keyMap.enable();
- },
-
- deactivateKeyMap: function() {
- this.keyMap.disable();
- },
-
- createMyRefs: function(varname) {
- var refs = Array(this.viewRefs.length);
- var tpl = new Ext.XTemplate("#{varname} {selector}");
- Ext.each(this.viewRefs, function(v, i, a) {
- refs[i] = {ref: v['ref'],
- selector: tpl.apply({varname:varname,
- selector: v['selector']})
- };
- });
- this.ref(refs);
- return refs;
- },
-
- multicast: function() {
- reason.server.multicast(this.payload['varname']);
- }
-
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/GridDataViewer.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/GridDataViewer.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**********************************************************************
-The Plot Window Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-Ext.define("Reason.controller.widgets.GridDataViewer", {
- extend: 'Reason.controller.widgets.BaseWidget',
- requires: ['Reason.view.widgets.GridDataViewer'],
-
- templates: {
- title: "Grid Data for {widget.varname}",
- createGridViewer: 'widget_store.create_grid_dataview({varname})',
- },
-
- widgetTriggers: [
-
- ],
-
- executionTriggers: [
-
- ],
-
- viewRefs: [
- ],
-
- applyPayload: function(payload) {
- return;
- },
-
- createView: function() {
- var wd = this.payload['data'];
- this.dataStore = Ext.create("Reason.store.widgets.GridData");
- this.dataStore.loadData(wd['gridvals']);
- this.gridDataView = Ext.widget("griddataviewer", {
- store: this.dataStore,
- title: 'Grid Data for ' + this.payload['varname'],
- });
-
- this.createMyRefs(this.gridDataView.id);
- return this.gridDataView;
- },
-
- statics: {
- widgetName: "grid_data",
- displayName: "Grid Data Viewer",
- supportsDataObjects: false,
- supportsParameterFiles: true,
- preCreation: function(obj) {
- var widget = Ext.create(this.getName());
- var cmd = widget.templateManager.applyObject(
- obj, 'createGridViewer');
- reason.server.execute(cmd);
- },
- },
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/GridViewer.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/GridViewer.js
+++ /dev/null
@@ -1,194 +0,0 @@
-/**********************************************************************
-The Plot Window Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-window.requestAnimFrame = (function(){
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(/* function */ callback, /* DOMElement */ element){
- window.setTimeout(callback, 1000 / 60);
- };
-})();
-
-var WidgetGridViewer = function(python_varname, widget_data) {
- this.id = python_varname;
- this.widget_data = widget_data;
- examine = "canvas_" + python_varname;
- var draw;
- var GridViewerStart = function() {
- this.curX = 0;
- this.curY = 0;
- this.dist = 0;
- function updateBasedOnOffset(camera, offset){
- camera.position.x = camera.target.x + offset.x;
- camera.position.y = camera.target.y + offset.y;
- camera.position.z = camera.target.z + offset.z;
- draw();
- }
- function camGetOffset(camera){
- return PhiloGL.Vec3.sub(camera.position, camera.target)
- }
- PhiloGL('canvas_' + python_varname, {
- camera: {
- position: {
- x: 0.5, y: 0.5, z: 5
- },
- target: {
- x: 0.5, y: 0.5, z: 0.5
- },
- },
- events: {
- onDragStart: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- this.curX = e.x;
- this.curY = e.y;
- this.dist = camGetOffset(this.camera).norm();
- },
- onDragEnd: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- },
- onDragMove: function(e) {
- var c = this.camera;
- var off = camGetOffset(c);
-
- // Get Horizontal vector
- var horiz = PhiloGL.Vec3.cross(c.up,
- camGetOffset(c))
- horiz.$scale(1./horiz.norm());
-
- if (e.event.button == 0){ // Rotation
- // Do vertical rotation about horizontal vector
- var vert_rot = new PhiloGL.Mat4();
- vert_rot.id();
- vert_rot.$rotateAxis((e.y-this.curY)/100., horiz);
- PhiloGL.Mat4.$mulVec3(vert_rot, off);
- PhiloGL.Mat4.$mulVec3(vert_rot, c.up);
- c.up.$scale(1./c.up.norm());
-
- // Do horizontal rotation about up vector
- var side_rot = new PhiloGL.Mat4();
- side_rot.id();
- side_rot.$rotateAxis(-(e.x-this.curX)/100., c.up);
- side_rot.$mulVec3(off);
-
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- updateBasedOnOffset(c, off);
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- } else if (e.event.button = 2){ // Right click - transpose
- var tscale = 1.0*off.norm()/512.;
- var move_up = c.up.scale(-(e.y-this.curY)*tscale);
- var move_over = horiz.scale(-(e.x-this.curX)*tscale);
- c.position.$add(move_up);
- c.position.$add(move_over);
- c.target.$add(move_up);
- c.target.$add(move_over);
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- }
- draw();
- },
- onMouseWheel: function(e){
- e.stop();
- var offset = PhiloGL.Vec3.scale(camGetOffset(this.camera),
- 1.0 - e.wheel/10.);
- updateBasedOnOffset(this.camera, offset);
- var dist = offset.norm()
- this.camera.near = offset.norm()/100000.0;
- this.camera.far = offset.norm()*2.0;
- this.camera.update();
- draw();
- }
- },
- onError: function() {
- alert("An error ocurred while loading the application");
- },
- onLoad: function(app) {
- var gl = app.gl,
- canvas = app.canvas,
- program = app.program,
- scene = app.scene,
- camera = app.camera;
- var grids = new PhiloGL.O3D.Model({
- vertices : widget_data['vertex_positions'],
- drawType : "LINES",
- colors : widget_data['vertex_colors'],
- });
- scene.add(grids);
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.clearColor(0, 0, 0, 1);
-
- //examine = camera;
- camera.view.id();
- camera.update();
-
- //Draw the scene
- draw = function() {
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- scene.render();
- }
-
- draw();
-
- }
- });
- }
-
- viewport.get("center-panel").add(
- {
- xtype: 'panel',
- id: "gv_" + python_varname,
- title: "WebGL Grid Viewer",
- iconCls: 'graph',
- autoScroll: true,
- layout:'absolute',
- closable: true,
- items: [
- { xtype:'panel',
- autoEl: {
- tag: 'canvas',
- id: 'canvas_' + python_varname,
- style: 'border: none;',
- width: 512, height:512
- },
- width: 512,
- height: 512
- }],
- listeners: { afterlayout: GridViewerStart },
- }
- );
-
- viewport.get("center-panel").activate("gv_" + this.id);
- viewport.doLayout();
- this.panel = viewport.get("center-panel").get("gv_" + python_varname);
- this.panel.doLayout();
-
- this.accept_results = function(payload) { }
-}
-
-widget_types['grid_viewer'] = WidgetGridViewer;
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/IsocontourViewer.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/IsocontourViewer.js
+++ /dev/null
@@ -1,196 +0,0 @@
-/**********************************************************************
-The isocontour viewer widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-// shim layer with setTimeout fallback
-window.requestAnimFrame = (function(){
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(/* function */ callback, /* DOMElement */ element){
- window.setTimeout(callback, 1000 / 60);
- };
-})();
-
-var exagain;
-var WidgetIsocontourViewer = function(python_varname, widget_data) {
- this.id = python_varname;
- this.widget_data = widget_data;
- examine = "canvas_" + python_varname;
- var draw;
- var GridViewerStart = function() {
- this.curX = 0;
- this.curY = 0;
- this.dist = 0;
- function updateBasedOnOffset(camera, offset){
- camera.position.x = camera.target.x + offset.x;
- camera.position.y = camera.target.y + offset.y;
- camera.position.z = camera.target.z + offset.z;
- draw();
- }
- function camGetOffset(camera){
- return PhiloGL.Vec3.sub(camera.position, camera.target)
- }
- PhiloGL('canvas_' + python_varname, {
- camera: {
- position: {
- x: 0.5, y: 0.5, z: 5
- },
- target: {
- x: 0.5, y: 0.5, z: 0.5
- },
- },
- events: {
- onDragStart: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- this.curX = e.x;
- this.curY = e.y;
- this.dist = camGetOffset(this.camera).norm();
- },
- onDragEnd: function(e) {
- pos = {
- x: e.x,
- y: e.y
- };
- },
- onDragMove: function(e) {
- var c = this.camera;
- var off = camGetOffset(c);
-
- // Get Horizontal vector
- var horiz = PhiloGL.Vec3.cross(c.up,
- camGetOffset(c))
- horiz.$scale(1./horiz.norm());
-
- if (e.event.button == 0){ // Rotation
- // Do vertical rotation about horizontal vector
- var vert_rot = new PhiloGL.Mat4();
- vert_rot.id();
- vert_rot.$rotateAxis((e.y-this.curY)/100., horiz);
- PhiloGL.Mat4.$mulVec3(vert_rot, off);
- PhiloGL.Mat4.$mulVec3(vert_rot, c.up);
- c.up.$scale(1./c.up.norm());
-
- // Do horizontal rotation about up vector
- var side_rot = new PhiloGL.Mat4();
- side_rot.id();
- side_rot.$rotateAxis(-(e.x-this.curX)/100., c.up);
- side_rot.$mulVec3(off);
-
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- updateBasedOnOffset(c, off);
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- } else if (e.event.button = 2){ // Right click - transpose
- var tscale = 1.0*off.norm()/512.;
- var move_up = c.up.scale(-(e.y-this.curY)*tscale);
- var move_over = horiz.scale(-(e.x-this.curX)*tscale);
- c.position.$add(move_up);
- c.position.$add(move_over);
- c.target.$add(move_up);
- c.target.$add(move_over);
- // Update current positions
- this.curX = e.x;
- this.curY = e.y;
- this.dist = off.norm();
- this.camera.near = this.dist/100000.0;
- this.camera.far = this.dist*2.0;
- c.update();
- }
- draw();
- },
- onMouseWheel: function(e){
- e.stop();
- var offset = PhiloGL.Vec3.scale(camGetOffset(this.camera),
- 1.0 - e.wheel/10.);
- updateBasedOnOffset(this.camera, offset);
- var dist = offset.norm()
- this.camera.near = offset.norm()/100000.0;
- this.camera.far = offset.norm()*2.0;
- this.camera.update();
- draw();
- }
- },
- onError: function() {
- alert("An error ocurred while loading the application");
- },
- onLoad: function(app) {
- var gl = app.gl,
- canvas = app.canvas,
- program = app.program,
- scene = app.scene,
- camera = app.camera;
- var grids = new PhiloGL.O3D.Model({
- vertices : widget_data['vertex_positions'],
- drawType : "TRIANGLES",
- colors : widget_data['vertex_colors'],
- });
- exagain = grids;
- scene.add(grids);
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.clearColor(0, 0, 0, 1);
-
- //examine = camera;
- camera.view.id();
- camera.update();
-
- //Draw the scene
- draw = function() {
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- scene.render();
- }
-
- draw();
-
- }
- });
- }
-
- viewport.get("center-panel").add(
- {
- xtype: 'panel',
- id: "iv_" + python_varname,
- title: "WebGL Isocontour Viewer",
- iconCls: 'graph',
- autoScroll: true,
- layout:'absolute',
- closable: true,
- items: [
- { xtype:'panel',
- autoEl: {
- tag: 'canvas',
- id: 'canvas_' + python_varname,
- style: 'border: none;',
- width: 512, height:512
- },
- width: 512,
- height: 512
- }],
- listeners: { afterlayout: GridViewerStart },
- }
- );
-
- viewport.get("center-panel").activate("iv_" + this.id);
- viewport.doLayout();
- this.panel = viewport.get("center-panel").get("iv_" + python_varname);
- this.panel.doLayout();
-
- this.accept_results = function(payload) { }
-}
-
-widget_types['isocontour_viewer'] = WidgetIsocontourViewer;
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/PannableMap.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/PannableMap.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/**********************************************************************
-The Pannable Map Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define("Reason.controller.widgets.PannableMap", {
- extend: 'Reason.controller.widgets.BaseWidget',
- requires: ['Reason.view.widgets.PannableMapView'],
-
- templates: {
- title: "Map View for {widget.varname}",
- },
-
- widgetTriggers: [
- ['#mapbox', 'afterlayout', 'setupLeaflet'],
- ],
-
- executionTriggers: [
- ],
-
- viewRefs: [
- { ref: 'mapBox', selector: '#mapbox' },
- ],
-
- applyPayload: function(payload) {
- return;
- },
-
- setupLeaflet: function() {
- var toRender = this.getMapBox().getEl().dom.childNodes[0].id;
- this.leafletMap = new L.Map(toRender,
- {
- center: new L.LatLng(0, 0),
- zoom: 1,
- });
- var ytMapURL = this.payload.data['prefix'] + '/map/{z}/{x}/{y}.png';
- this.tileLayer = new L.TileLayer(ytMapURL, {maxZoom: 18});
- this.leafletMap.addLayer(this.tileLayer)
- },
-
- createView: function() {
- this.dataView = Ext.widget("mapview", {
- title: 'Pannable Map of ' + this.payload['field'],
- });
- this.createMyRefs(this.dataView.id);
- this.applyExecuteHandlers(this.dataView);
- return this.dataView;
- },
-
- statics: {
- widgetName: "pannable_map",
- displayName: "Pannable Map",
- supportsDataObjects: false,
- supportsParameterFiles: false,
- preCreation: function(obj) { },
- },
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/ParameterFile.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/ParameterFile.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/**********************************************************************
-The Parameter File widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define("Reason.controller.widgets.ParameterFile", {
- extend: 'Reason.controller.widgets.BaseWidget',
- requires: ['Reason.view.widgets.ParameterFileDisplay',
- 'Reason.view.widgets.LevelStats',
- 'Reason.view.widgets.FieldPanel',
- 'Reason.store.widgets.LevelInformation'],
- templates: {
- title: "Dataset: {widget.varname}",
- createDisplay: 'widget_store.create_pf_display({varname})',
- retrieveField: 'widget_store["{widget.varname}"].deliver_field("{a1}")',
- fieldSource: '<pre>{field_source}</pre>',
- pfParams: '<table class="pftable">' +
- '<tr><th>Parameter</th><th>Value</th></tr>' +
- '<tr><td>Output Hash</td>' +
- '<td>{output_hash}</td></tr>' +
- '<tr><td>Dimensionality</td>' +
- '<td>{dimensionality}</td></tr>' +
- '<tr><td>Refine by</td>' +
- '<td>{refine_by}</td></tr>' +
- '<tr><td>Domain Dimensions</td>' +
- '<td>{domain_dimensions}</td></tr>' +
- '<tr><td>Cosmological Simulation</td>' +
- '<td>{cosmological_simulation}</td></tr>' +
- '<tr><td>Current Redshift</td>' +
- '<td>{current_redshift}</td></tr>' +
- '<tr><td>Omega Matter</td>' +
- '<td>{omega_matter}</td></tr>' +
- '<tr><td>Omega Lambda</td>' +
- '<td>{omega_lambda}</td></tr>' +
- '<tr><td>Hubble Constant</td>' +
- '<td>{hubble_constant}</td></tr>' +
- '<tr><td>Current (sim) Time</td>' +
- '<td>{current_time}</td></tr>' +
- '<tr><td>Domain Left Edge</td>' +
- '<td>{domain_left_edge}</td></tr>' +
- '<tr><td>Domain Right Edge</td>' +
- '<td>{domain_right_edge}</td></tr>' +
- '</table>',
- },
-
- widgetTriggers: [
- ],
-
- executionTriggers: [
- ['#fieldSelector', 'change', 'retrieveField'],
- ],
-
- viewRefs: [
- { ref:'levelStats', selector: '#levelStats'},
- { ref:'statsPanel', selector: '#statsPanel'},
- { ref:'parametersPanel', selector: '#pfParams'},
- { ref:'fieldPanel', selector: '#fieldPanel'},
- { ref:'fieldSourcePanel', selector: '#fieldSourcePanel'},
- { ref:'widgetPanel', selector: '#widgetpanel'},
- ],
-
- applyPayload: function(payload) {
- if (payload['ptype'] == 'field_info') {
- var source = this.templateManager.applyObject(
- payload, 'fieldSource')
- this.getFieldSourcePanel().update(source);
- }
- },
-
- createView: function() {
- var wd = this.payload['data'];
- this.levelDataStore = Ext.create("Reason.store.widgets.LevelInformation");
- this.levelDataStore.loadData(wd['level_stats']);
- this.levelStatsDisplay = Ext.widget("levelstats", {
- store: this.levelDataStore,
- });
- this.dataView = Ext.widget("pfdisplay", {
- title: 'Data for ' + this.payload['varname'],
- varname: this.payload['varname'],
- });
- this.fieldDisplay = Ext.widget("fieldpanel");
- fieldSelector = this.fieldDisplay.query("#fieldSelector")[0]
- this.fieldStore = Ext.create("Reason.store.Fields")
- this.fieldStore.loadData(wd['fields']);
- fieldSelector.bindStore(this.fieldStore);
-
- this.dataView.query("#fieldPanel")[0].add(this.fieldDisplay);
- this.dataView.query("#statsPanel")[0].add(this.levelStatsDisplay);
- this.createMyRefs(this.dataView.id);
-
- var pfString = this.templateManager.applyObject(
- wd['pf_info'], 'pfParams');
- this.getParametersPanel().update(pfString);
- this.applyExecuteHandlers(this.dataView);
- return this.dataView;
- },
-
- statics: {
- widgetName: 'parameterfile',
- supportsDataObjects: false,
- supportsParameterFiles: true,
- displayName: 'Dataset Information',
- preCreation: function(obj) {
- var widget = Ext.create(this.getName());
- var cmd = widget.templateManager.applyObject(
- obj, 'createDisplay');
- reason.server.execute(cmd);
- },
-
- },
-
-});
diff -r a59bffb6db85cf362376b5d9beee09adcd59fccb -r 33dadd43445dafcebb5ceb688577c628e2918667 yt/visualization/mapserver/html/app/controller/widgets/PhasePlot.js
--- a/yt/visualization/mapserver/html/app/controller/widgets/PhasePlot.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/**********************************************************************
-The Plot Window Widget
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-
-Ext.define("Reason.controller.widgets.PhasePlot", {
- extend: 'Reason.controller.widgets.BaseWidget',
- requires: ['Reason.view.widgets.PhasePlotCreator',
- 'Reason.view.widgets.PhasePlot'],
- templates: {
- createPhasePlot: 'widget_store.create_phase({objname}, ' +
- '"{xField}", "{yField}", "{zField}", {weight})',
- setupPlot: 'widget_store["{widget.varname}"]._setup_plot()',
- },
-
- executionTriggers: [
- ['#imagepanel', 'afterrender', 'setupPlot'],
- ],
-
- viewRefs: [
- { ref: 'yTicks', selector: '#y_ticks'},
- { ref: 'xTicks', selector: '#x_ticks'},
- { ref: 'colorTicks', selector: '#cb_ticks'},
- { ref: 'colorbar', selector: '#colorbar'},
- { ref: 'image', selector: '#imagepanel'},
- { ref: 'metadataString', selector: '#metadataString'},
- ],
-
- applyPayload: function(payload) {
- this.getImage().getEl().dom.src =
- "data:image/png;base64," + payload['image_data'];
- this.getColorbar().getEl().dom.src=
- "data:image/png;base64," + payload['cbar']['cmap_image'];
- var YTicks = this.getYTicks();
- YTicks.removeAll();
- Ext.each(payload['yax']['ticks'], function(tick, index) {
- YTicks.add({xtype:'panel',
- width: 20, height:15,
- border: false,
- style: 'font-family: "Inconsolata", monospace;' +
- 'font-size: 12px; text-align: right;' +
- 'padding-right: 5px;',
- html: ' ' + tick[2] + ' ',
- x:0, y: tick[0]-6});
- YTicks.add({xtype:'panel',
- width: 20, height:1,
- style: 'background-color: #000000;',
- html:' ',
- x:20, y: tick[0]});
- });
- YTicks.doLayout();
- var XTicks = this.getXTicks();
- XTicks.removeAll();
- Ext.each(payload['xax']['ticks'], function(tick, index) {
- XTicks.add({xtype:'panel',
- width: 1, height:20,
- style: 'background-color: #000000;',
- html:' ',
- x:(400 - tick[0]) + 10, y: 0});
- XTicks.add({xtype:'panel',
- width: 20, height:20,
- border: false,
- style: 'font-family: "Inconsolata", monospace;' +
- 'font-size: 12px; text-align: center;',
- html: ' ' + tick[2] + ' ',
- x: (400 - tick[0]), y: 20});
- });
- XTicks.doLayout();
- var colorTicks = this.getColorTicks();
- colorTicks.removeAll();
- Ext.each(payload['cbar']['ticks'], function(tick, index) {
- colorTicks.add({xtype:'panel',
- width: 10, height:1,
- style: 'background-color: #000000;',
- html:' ',
- x:0, y: tick[0]});
- colorTicks.add({xtype:'panel',
- width: 30, height:15,
- border: false,
- style: 'font-family: "Inconsolata", monospace;' +
- 'font-size: 12px;',
- html: ' ' + tick[2] + ' ',
- x:18, y: tick[0]-6});
- });
- colorTicks.doLayout();
- },
-
- createView: function() {
- var wd = this.payload['data'];
- this.dataView = Ext.widget("phaseplotwindow",{
- varname : this.payload['varname'],
- title: wd['title'],
- });
- this.createMyRefs(this.dataView.id);
- this.applyExecuteHandlers(this.dataView);
- this.getMetadataString().update(this.payload['data']['metadata_string']);
- this.getMetadataString().mds = this.payload['data']['metadata_string'];
- return this.dataView;
- },
-
- statics: {
- widgetName: 'phase_plot',
- supportsDataObjects: true,
- supportsParameterFiles: false,
- displayName: 'Phase Plot',
- preCreation: function(obj) {
- var widget = Ext.create(this.getName());
- function makePlot(b, e) {
- var conf = {
- objname: obj.varname,
- xField: win.query("#x_field")[0].getValue(),
- yField: win.query("#y_field")[0].getValue(),
- zField: win.query("#z_field")[0].getValue(),
- };
- var weight = win.query("#weight")[0].getValue();
- if (weight == 'Mass') {
- weightField = '"CellMassMsun"';
- } else if (weight == 'Volume') {
- weightField = '"CellVolume"';
- } else if (weight == 'Just Sum') {
- weightField = 'None';
- }
- conf['weight'] = weightField;
- var cmd = widget.templateManager.applyObject(
- conf, 'createPhasePlot');
- reason.server.execute(cmd);
- win.destroy();
- }
- win = Ext.widget("phaseplotcreator", {obj:obj});
- var xFieldObj = win.query("#x_field")[0];
- var yFieldObj = win.query("#y_field")[0];
- var zFieldObj = win.query("#z_field")[0];
- this.fieldStore = Ext.create("Reason.store.Fields");
- this.fieldStore.loadData(obj.field_list);
- xFieldObj.bindStore(this.fieldStore);
- yFieldObj.bindStore(this.fieldStore);
- zFieldObj.bindStore(this.fieldStore);
- xFieldObj.setValue("Density");
- yFieldObj.setValue("Temperature");
- zFieldObj.setValue("CellMassMsun");
- win.query("#create")[0].on('click', makePlot);
- win.query("#cancel")[0].on('click', function(){win.destroy();});
- win.show();
- },
- },
-});
This diff is so big that we needed to truncate the remainder.
https://bitbucket.org/yt_analysis/yt/commits/d7723c5f299e/
Changeset: d7723c5f299e
Branch: yt
User: ngoldbaum
Date: 2015-08-24 19:04:22+00:00
Summary: Adding leaflet.js sources to mapserver module. Removing unused reason bits.
Affected #: 13 files
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/bottle_mods.py
--- a/yt/visualization/mapserver/bottle_mods.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""
-Modifications and extensions to Bottle, to make it slightly more useful for
-yt's purposes
-
-
-
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import uuid
-import json
-import logging, threading
-import sys
-from yt.extern.six.moves import urllib
-import numpy as np
-
-from yt.extern.bottle import \
- server_names, debug, route, run, request, ServerAdapter, response
-from .extdirect_router import DirectRouter, DirectProviderDefinition
-from yt.utilities.logger import ytLogger as mylog
-from yt.funcs import *
-
-route_functions = {}
-route_watchers = []
-payloads = []
-
-def preroute(future_route, *args, **kwargs):
- def router(func):
- route_functions[future_route] = (args, kwargs, func)
- return func
- return router
-
-def notify_route(watcher):
- route_watchers.append(watcher)
-
-class BinaryDelivery(object):
- delivered = False
- payload = ""
- def __init__(self, payload, name = ""):
- self.name = name
- self.payload = payload
- #sys.__stderr__.write("CREATING A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
-
- def get(self):
- # We set our
- #sys.__stderr__.write("REQUESTED A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
- p = self.payload
- if p == "":
- response.status = 404
- return
- self.payload = ""
- return p
-
-class PayloadHandler(object):
- _shared_state = {}
- payloads = None
- binary_payloads = None
- recorded_payloads = None
- multicast_ids = None
- multicast_payloads = None
- lock = None
- record = False
- event = None
- count = 0
- debug = False
- _prefix = ""
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.payloads is None: self.payloads = []
- if self.lock is None: self.lock = threading.Lock()
- if self.recorded_payloads is None: self.recorded_payloads = []
- if self.event is None: self.event = threading.Event()
- if self.multicast_payloads is None: self.multicast_payloads = {}
- if self.multicast_ids is None: self.multicast_ids = {}
- if self.binary_payloads is None: self.binary_payloads = []
-
- def deliver_payloads(self):
- with self.lock:
- payloads = self.payloads
- if self.record:
- self.recorded_payloads += self.payloads
- if self.debug:
- sys.__stderr__.write("**** Delivering %s payloads\n" % (len(payloads)))
- for p in payloads:
- sys.__stderr__.write("**** %s\n" % p['type'])
- self.payloads = []
- self.event.clear()
- try:
- self.deliver_multicast()
- except Exception as exc:
- sys.__stderr__.write("%s" % exc)
- return payloads
-
- def add_payload(self, to_add):
- with self.lock:
- if "binary" in to_add:
- self._add_binary_payload(to_add)
- self.payloads.append(to_add)
- # Does this next part need to be in the lock?
- if to_add.get("widget_id", None) in self.multicast_ids:
- self.multicast_payloads[to_add["widget_id"]] = to_add
- self.count += 1
- self.event.set()
- if self.debug:
- sys.__stderr__.write("**** Adding payload of type %s\n" % (to_add['type']))
-
- def _add_binary_payload(self, bp):
- # This shouldn't be called by anybody other than add_payload.
- bkeys = ensure_list(bp['binary'])
- bp['binary'] = []
- for bkey in bkeys:
- bdata = bp.pop(bkey) # Get the binary data
- if isinstance(bdata, np.ndarray):
- bdata = bdata.tostring()
- bpserver = BinaryDelivery(bdata, bkey)
- self.binary_payloads.append(bpserver)
- uu = uuid.uuid4().hex
- bp['binary'].append((bkey, uu))
- route("%s/%s" % (self._prefix, uu))(bpserver.get)
- if self.debug:
- sys.__stderr__.write(
- "**** Adding binary payload (%s) to %s\n" % (bkey, uu))
-
- def replay_payloads(self):
- return self.recorded_payloads
-
- def widget_payload(self, widget, data):
- data['type'] = 'widget_payload'
- data['widget_id'] = widget._ext_widget_id
- self.add_payload(data)
-
- def deliver_multicast(self):
- for widget_id in self.multicast_payloads:
- if widget_id not in self.multicast_payloads: continue
- server_id, session_token = self.multicast_ids[widget_id]
- # Now we execute a post to the correct location
- data = urllib.parse.urlencode({
- 'payload_session_id': server_id,
- 'payload_session_token': session_token,
- 'payload_data': self.multicast_payloads[widget_id],
- 'payload_metadata': {}
- })
- urllib.request.urlopen("http://localhost:8080/UpdatePayload", data = data)
-
-class YTRocketServer(ServerAdapter):
- server_info = {} # Hack to get back at instance vars
- def run(self, handler):
- from yt.extern.rocket import Rocket
- server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
- self.server_info[id(self)] = server
- server.start()
-
-class BottleDirectRouter(DirectRouter):
- # This class implements a mechanism for auto-routing an ExtDirect-callable
- # object through Bottle. It should be used as a base class of an object,
- # and the __init__ function will need to include the keyword argument
- # 'route' for it to work.
- _route_prefix = None
- def __init__(self, *args, **kwargs):
- future_route = self.api_url
- super(BottleDirectRouter, self).__init__(*args, **kwargs)
- self.__name__ = str(self.my_name)
- route_functions[future_route] = ((), {'method':("POST", "GET")}, self)
- preroute("/resources/ext-%s-api.js" % self.api_url, method="GET")(self._myapi)
- notify_route(self)
-
- def _myapi(self):
- dpd = DirectProviderDefinition(self, self.api_url, ns="yt_rpc")
- source = "Ext.Direct.addProvider(%s);" % json.dumps(dpd._config())
- response.headers['Content-Type'] = "text/javascript"
- return source
-
- def __call__(self):
- #print "Hi there, I just got this request:",
- val = request.body.read()
- #print val
- #import pdb;pdb.set_trace()
- rv = super(BottleDirectRouter, self).__call__(val)
- #print "With this response:", rv
- return rv
-
-def uuid_serve_functions(pre_routed = None, open_browser=False, port=9099,
- repl = None, token = None):
- if pre_routed == None: pre_routed = route_functions
- debug(mode=True)
- if token is None: token = uuid.uuid1()
- for r in pre_routed:
- args, kwargs, f = pre_routed[r]
- if r[0] == "/": r = r[1:]
- rp = "/%s/%s" % (token, r)
- func_name = getattr(f, 'func_name', str(f))
- print("Routing from %s => %s" % (rp, func_name))
- route(rp, *args, **kwargs)(f)
- for w in route_watchers:
- if not hasattr(w, "_route_prefix"):
- print("WARNING: %s has no _route_prefix attribute. Not notifying.")
- continue
- w._route_prefix = token
- repl._global_token = token
- repl.activate()
- repl.execution_thread.wait()
- print()
- print()
- print("=============================================================================")
- print("=============================================================================")
- print("Greetings, and welcome to Reason!")
- print("Your private token is %s ." % token)
- print("DO NOT SHARE THIS TOKEN.")
- print()
- print("Please direct your browser to:")
- print()
- print(" http://localhost:%s/%s/" % (port, token))
- print()
- print("=============================================================================")
- print()
- print("If you are currently ssh'd into a remote machine, you should be able")
- print("to create a new SSH tunnel by typing or copy/pasting this text")
- print("verbatim, while waiting to see the 'ssh>' prompt after the first line.")
- print()
- print("~C")
- print("-L%s:localhost:%s" % (port, port))
- print()
- print("and then pointing a web browser on your local machine to the above URL.")
- print()
- print("=============================================================================")
- print("=============================================================================")
- print()
- print()
- if open_browser:
- # We do some fancy footwork so that we can open the browser while the
- # server starts up. I got this from some recipe whose URL escapes me.
- # Thank you, to whoever wrote it!
- def local_browse():
- """Start a browser after waiting for half a second."""
- import webbrowser, threading
- def _local_browse():
- webbrowser.open('http://localhost:%s/%s/' % (port, token))
- thread = threading.Timer(0.5, _local_browse)
- thread.start()
- local_browse()
- try:
- import yt.extern.rocket as rocket
- server_type = YTRocketServer
- log = logging.getLogger('Rocket')
- log.setLevel(logging.WARNING)
- kwargs = {'timeout': 600, 'max_threads': 2}
- if repl is not None:
- repl.server = YTRocketServer.server_info
- except ImportError:
- server_type = server_names.get("wsgiref")
- kwargs = {}
- server = server_type(host='localhost', port=port, **kwargs)
- mylog.info("Starting up the server.")
- run(server=server)
-
-class MethodLock(object):
- _shared_state = {}
- locks = None
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.locks is None: self.locks = {}
-
- def __call__(self, func):
- if str(func) not in self.locks:
- self.locks[str(func)] = threading.Lock()
- @wraps(func)
- def locker(*args, **kwargs):
- print("Acquiring lock on %s" % (str(func)))
- with self.locks[str(func)]:
- rv = func(*args, **kwargs)
- print("Regained lock on %s" % (str(func)))
- return rv
- return locker
-
-lockit = MethodLock()
-
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/extdirect_router.py
--- a/yt/visualization/mapserver/extdirect_router.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""
-This is code from the extdirect package:
-
-http://pypi.python.org/pypi/extdirect/0.3
-https://github.com/iancmcc/extdirect
-
-written by Ian McCracken
-
-This code was released under the BSD License.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-import inspect
-
-class DirectException(Exception):
- pass
-
-
-try:
- import json
-except ImportError:
- try:
- import simplejson as json
- except ImportError:
- raise DirectException("No JSON library available. Please install"
- " simplejson or upgrade to Python 2.6.")
-
-
-class DirectRouter(object):
- """
- Basic Ext.Direct router class.
-
- Ext.Direct allows one to create an API that communicates with a single URL,
- which then routes requests to the appropriate method. The client-side API
- object matches the server-side API object.
-
- This base class parses an Ext.Direct request, which contains the name of
- the method and any data that should be passed, and routes the data to the
- approriate method. It then receives the output of that call and puts it
- into the data structure expected by Ext.Direct.
-
- Call an instance of this class with the JSON from an Ext.Direct request.
- """
- exception_handler = None
- def __call__(self, body):
- """
- """
- # Decode the request data
- body = json.loads(body)
- self._body = body
-
- if isinstance(body, list):
- directRequests = body
- elif isinstance(body, dict):
- directRequests = [body]
- else:
- raise DirectException("Body is not a support type: %s" % body)
-
- responses = []
-
- for req in directRequests:
- responses.append(self._doRequest(req))
-
- if len(responses) == 1:
- responses = responses[0]
-
- return json.dumps(responses)
-
- def _doRequest(self, request):
-
- # Double-check that this request is meant for this class
- action = request.get('action')
- clsname = self.__class__.__name__
- if action != clsname:
- raise DirectException(("Action specified in request ('%s') is"
- " not named %s.") % (action, clsname))
-
- # Pull out the method name and make sure it exists on this class
- method = request.get('method')
- if not method:
- raise DirectException("No method specified. Is this a valid"
- " Ext.Direct request?")
- try:
- _targetfn = getattr(self, method)
- except AttributeError:
- raise DirectException("'%s' is not the name of a method on %s" % (
- method, clsname
- ))
-
- # Pull out any arguments. Sent as an array containing a hash map, so
- # get the first member.
- data = request.get('data')
- if not data:
- data = {}
- else:
- data = data[0]
-
- # Cast all keys as strings, in case of encoding or other wrinkles
- data = dict((str(k), v) for k,v in data.iteritems())
- self._data = data
-
- # Finally, call the target method, passing in the data
- try:
- result = _targetfn(**data)
- except Exception as e:
- if self.exception_handler is not None:
- result = self.exception_handler(e)
- else:
- raise e
-
- return {
- 'type':'rpc',
- 'tid': request['tid'],
- 'action': action,
- 'method': method,
- 'result': result
- }
-
-
-class DirectProviderDefinition(object):
- """
- Turns a L{DirectRouter} subclass into JavaScript object representing the
- config of the client-side API.
-
- Inspects the given subclass and retrieves the names of all public methods,
- then defines those as actions on the Ext.Direct provider, and creates the
- JS that adds the provider.
-
- See http://extjs.com/products/extjs/direct.php for a full explanation of
- protocols and features of Ext.Direct.
- """
- def __init__(self, routercls, url, ns=None, timeout=None):
- """
- @param routercls: A L{DirectRouter} subclass
- @type routercls: class
- @param url: The url at which C{routercls} is available
- @type url: str
- @param ns: The client-side namespace in which the provider should live.
- The provider will be available at [ns].[routercls.__name__].
- For example, if ns is 'Zenoss.remote' and routercls is named
- 'EventConsole', client-side code would call
- C{Zenoss.remote.EventConsole.my_method(params, callback)}.
- """
- self.routercls = routercls
- self.url = url
- self.ns = ns
- self.timeout = timeout
-
- def _config(self):
- actions = []
- for name, value in inspect.getmembers(self.routercls):
- if name.startswith("_"):
- continue
- if inspect.ismethod(value):
-
- ## Update this when extdirect doesn't freak out when you specify
- ## actual lens (we're passing them all in as a single dict, so
- ## from the perspective of Ext.Direct they are all len 1)
- #args = inspect.getargspec(value)[0]
- #args.remove('self')
- #arglen = len(args)
- arglen = 1
-
- actions.append({'name':name, 'len':arglen})
- config = {
- 'id': self.routercls.__name__,
- 'type': 'remoting',
- 'url': self.url,
- 'actions': {
- self.routercls.__name__: actions
- }
- }
- if self.timeout:
- config['timeout'] = self.timeout
- if self.ns:
- config['namespace'] = self.ns
- return config
-
- def render(self):
- """
- Generate and return an Ext.Direct provider definition, wrapped in a
- <script> tag and ready for inclusion in an HTML document.
- """
- config = self._config()
- source = "Ext.Direct.addProvider(%s);" % json.dumps(config)
- return '<script type="text/javascript"> %s </script>' % source.strip()
-
-
-
-
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/images/marker-shadow.png
Binary file yt/visualization/mapserver/html/leaflet/images/marker-shadow.png has changed
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/images/marker.png
Binary file yt/visualization/mapserver/html/leaflet/images/marker.png has changed
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/images/popup-close.png
Binary file yt/visualization/mapserver/html/leaflet/images/popup-close.png has changed
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/images/zoom-in.png
Binary file yt/visualization/mapserver/html/leaflet/images/zoom-in.png has changed
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/images/zoom-out.png
Binary file yt/visualization/mapserver/html/leaflet/images/zoom-out.png has changed
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/leaflet.css
--- /dev/null
+++ b/yt/visualization/mapserver/html/leaflet/leaflet.css
@@ -0,0 +1,273 @@
+/* required styles */
+
+.leaflet-map-pane,
+.leaflet-tile,
+.leaflet-marker-icon,
+.leaflet-marker-shadow,
+.leaflet-tile-pane,
+.leaflet-overlay-pane,
+.leaflet-shadow-pane,
+.leaflet-marker-pane,
+.leaflet-popup-pane,
+.leaflet-overlay-pane svg,
+.leaflet-zoom-box,
+.leaflet-image-layer { /* TODO optimize classes */
+ position: absolute;
+ }
+.leaflet-container {
+ overflow: hidden;
+ }
+.leaflet-tile-pane {
+ -webkit-transform: translate3d(0,0,0);
+ }
+.leaflet-tile,
+.leaflet-marker-icon,
+.leaflet-marker-shadow {
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ user-select: none;
+ }
+.leaflet-marker-icon,
+.leaflet-marker-shadow {
+ display: block;
+ }
+.leaflet-clickable {
+ cursor: pointer;
+ }
+.leaflet-container img {
+ max-width: auto;
+ }
+
+.leaflet-tile-pane { z-index: 2; }
+.leaflet-overlay-pane { z-index: 3; }
+.leaflet-shadow-pane { z-index: 4; }
+.leaflet-marker-pane { z-index: 5; }
+.leaflet-popup-pane { z-index: 6; }
+
+.leaflet-zoom-box {
+ width: 0;
+ height: 0;
+ }
+
+.leaflet-tile {
+ visibility: hidden;
+ }
+.leaflet-tile-loaded {
+ visibility: inherit;
+ }
+
+a.leaflet-active {
+ outline: 2px solid orange;
+ }
+
+
+/* Leaflet controls */
+
+.leaflet-control {
+ position: relative;
+ z-index: 7;
+ }
+.leaflet-top,
+.leaflet-bottom {
+ position: absolute;
+ }
+.leaflet-top {
+ top: 0;
+ }
+.leaflet-right {
+ right: 0;
+ }
+.leaflet-bottom {
+ bottom: 0;
+ }
+.leaflet-left {
+ left: 0;
+ }
+.leaflet-control {
+ float: left;
+ clear: both;
+ }
+.leaflet-right .leaflet-control {
+ float: right;
+ }
+.leaflet-top .leaflet-control {
+ margin-top: 10px;
+ }
+.leaflet-bottom .leaflet-control {
+ margin-bottom: 10px;
+ }
+.leaflet-left .leaflet-control {
+ margin-left: 10px;
+ }
+.leaflet-right .leaflet-control {
+ margin-right: 10px;
+ }
+
+.leaflet-control-zoom {
+ padding: 5px;
+ background: rgba(0, 0, 0, 0.25);
+
+ -moz-border-radius: 7px;
+ -webkit-border-radius: 7px;
+ border-radius: 7px;
+ }
+.leaflet-control-zoom a {
+ display: block;
+ width: 19px;
+ height: 19px;
+ background-position: 50% 50%;
+ background-repeat: no-repeat;
+ background-color: rgba(255, 255, 255, 0.75);
+
+ -moz-border-radius: 4px;
+ -webkit-border-radius: 4px;
+ border-radius: 4px;
+ }
+.leaflet-control-zoom a:hover {
+ background-color: #fff;
+ }
+.leaflet-big-buttons .leaflet-control-zoom a {
+ width: 27px;
+ height: 27px;
+ }
+.leaflet-control-zoom-in {
+ background-image: url(images/zoom-in.png);
+ margin-bottom: 5px;
+ }
+.leaflet-control-zoom-out {
+ background-image: url(images/zoom-out.png);
+ }
+
+.leaflet-container .leaflet-control-attribution {
+ margin: 0;
+ padding: 0 5px;
+
+ font: 11px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif;
+ color: #333;
+
+ background-color: rgba(255, 255, 255, 0.7);
+
+ -moz-box-shadow: 0 0 7px #ccc;
+ -webkit-box-shadow: 0 0 7px #ccc;
+ box-shadow: 0 0 7px #ccc;
+ }
+
+
+/* Fade animations */
+
+.leaflet-fade-anim .leaflet-tile {
+ opacity: 0;
+
+ -webkit-transition: opacity 0.2s linear;
+ -moz-transition: opacity 0.2s linear;
+ -o-transition: opacity 0.2s linear;
+ transition: opacity 0.2s linear;
+ }
+.leaflet-fade-anim .leaflet-tile-loaded {
+ opacity: 1;
+ }
+
+.leaflet-fade-anim .leaflet-popup {
+ opacity: 0;
+
+ -webkit-transition: opacity 0.2s linear;
+ -moz-transition: opacity 0.2s linear;
+ -o-transition: opacity 0.2s linear;
+ transition: opacity 0.2s linear;
+ }
+.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
+ opacity: 1;
+ }
+
+.leaflet-zoom-anim .leaflet-tile {
+ -webkit-transition: none;
+ -moz-transition: none;
+ -o-transition: none;
+ transition: none;
+ }
+
+.leaflet-zoom-anim .leaflet-objects-pane {
+ visibility: hidden;
+ }
+
+
+/* Popup layout */
+
+.leaflet-popup {
+ position: absolute;
+ text-align: center;
+ -webkit-transform: translate3d(0,0,0);
+ }
+.leaflet-popup-content-wrapper {
+ padding: 1px;
+ text-align: left;
+ }
+.leaflet-popup-content {
+ margin: 19px;
+ }
+.leaflet-popup-tip-container {
+ margin: 0 auto;
+ width: 40px;
+ height: 16px;
+ position: relative;
+ overflow: hidden;
+ }
+.leaflet-popup-tip {
+ width: 15px;
+ height: 15px;
+ padding: 1px;
+
+ margin: -8px auto 0;
+
+ -moz-transform: rotate(45deg);
+ -webkit-transform: rotate(45deg);
+ -ms-transform: rotate(45deg);
+ -o-transform: rotate(45deg);
+ transform: rotate(45deg);
+ }
+.leaflet-popup-close-button {
+ position: absolute;
+ top: 9px;
+ right: 9px;
+
+ width: 10px;
+ height: 10px;
+
+ overflow: hidden;
+ }
+.leaflet-popup-content p {
+ margin: 18px 0;
+ }
+
+
+/* Visual appearance */
+
+.leaflet-container {
+ background: #ddd;
+ }
+.leaflet-container a {
+ color: #0078A8;
+ }
+.leaflet-zoom-box {
+ border: 2px dotted #05f;
+ background: white;
+ opacity: 0.5;
+ }
+.leaflet-popup-content-wrapper, .leaflet-popup-tip {
+ background: white;
+
+ box-shadow: 0 1px 10px #888;
+ -moz-box-shadow: 0 1px 10px #888;
+ -webkit-box-shadow: 0 1px 14px #999;
+ }
+.leaflet-popup-content-wrapper {
+ -moz-border-radius: 20px;
+ -webkit-border-radius: 20px;
+ border-radius: 20px;
+ }
+.leaflet-popup-content {
+ font: 12px/1.4 "Helvetica Neue", Arial, Helvetica, sans-serif;
+ }
+.leaflet-popup-close-button {
+ background: white url(images/popup-close.png);
+ }
\ No newline at end of file
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/leaflet.ie.css
--- /dev/null
+++ b/yt/visualization/mapserver/html/leaflet/leaflet.ie.css
@@ -0,0 +1,46 @@
+.leaflet-tile {
+ filter: inherit;
+ }
+
+.leaflet-vml-shape {
+ width: 1px;
+ height: 1px;
+ }
+.lvml {
+ behavior: url(#default#VML);
+ display: inline-block;
+ position: absolute;
+ }
+
+.leaflet-control {
+ display: inline;
+ }
+
+.leaflet-popup-tip {
+ width: 21px;
+ _width: 27px;
+ margin: 0 auto;
+ _margin-top: -3px;
+
+ filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
+ -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
+ }
+.leaflet-popup-tip-container {
+ margin-top: -1px;
+ }
+.leaflet-popup-content-wrapper, .leaflet-popup-tip {
+ border: 1px solid #bbb;
+ }
+
+.leaflet-control-zoom {
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#3F000000',EndColorStr='#3F000000');
+ }
+.leaflet-control-zoom a {
+ background-color: #eee;
+ }
+.leaflet-control-zoom a:hover {
+ background-color: #fff;
+ }
+.leaflet-control-attribution {
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#B2FFFFFF,endColorstr=#B2FFFFFF);
+ }
\ No newline at end of file
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/leaflet/leaflet.js
--- /dev/null
+++ b/yt/visualization/mapserver/html/leaflet/leaflet.js
@@ -0,0 +1,114 @@
+/*
+ Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin
+ Leaflet is a BSD-licensed JavaScript library for map display and interaction.
+ See http://cloudmade.github.com/Leaflet/ for more information.
+*/
+(function(a){var b={VERSION:"0.2",ROOT_URL:function(){for(var a=document.getElementsByTagName("script"),b=/^(.*\/)leaflet-?([\w-]*)\.js.*$/,e=0,f=a.length;e<f;e++){var g=a[e].src;if(g=g&&g.match(b)){if(g[2]=="include")break;return g[1]}}return"../../dist/"}(),noConflict:function(){a.L=this._originalL;return this},_originalL:a.L};window.L=b})(this);L.Util={extend:function(a){for(var b=Array.prototype.slice.call(arguments,1),c=0,d=b.length,e;c<d;c++){e=b[c]||{};for(var f in e)e.hasOwnProperty(f)&&(a[f]=e[f])}return a},bind:function(a,b){return function(){return a.apply(b,arguments)}},stamp:function(){var a=0;return function(b){b._leaflet_id=b._leaflet_id||++a;return b._leaflet_id}}(),requestAnimFrame:function(){function a(a){window.setTimeout(a,1E3/60)}var b=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||
+window.oRequestAnimationFrame||window.msRequestAnimationFrame||a;return function(c,d,e){c=d?L.Util.bind(c,d):d;e&&b===a?c():b(c)}}(),limitExecByInterval:function(a,b,c){function d(){e=!1;f&&(g.callee.apply(c,g),f=!1)}var e,f,g;return function(){g=arguments;e?f=!0:(e=!0,setTimeout(d,b),a.apply(c,g))}},falseFn:function(){return!1},formatNum:function(a,b){var c=Math.pow(10,b||5);return Math.round(a*c)/c},setOptions:function(a,b){a.options=L.Util.extend({},a.options,b)},getParamString:function(a){var b=
+[],c;for(c in a)a.hasOwnProperty(c)&&b.push(c+"="+a[c]);return"?"+b.join("&")}};L.Class=function(){};
+L.Class.extend=function(a){var b=function(){!L.Class._prototyping&&this.initialize&&this.initialize.apply(this,arguments)};L.Class._prototyping=!0;var c=new this;L.Class._prototyping=!1;c.constructor=b;b.prototype=c;c.superclass=this.prototype;a.statics&&(L.Util.extend(b,a.statics),delete a.statics);a.includes&&(L.Util.extend.apply(null,[c].concat(a.includes)),delete a.includes);if(a.options&&c.options)a.options=L.Util.extend({},c.options,a.options);L.Util.extend(c,a);b.extend=arguments.callee;b.include=
+function(a){L.Util.extend(this.prototype,a)};for(var d in this)this.hasOwnProperty(d)&&d!="prototype"&&(b[d]=this[d]);return b};L.Mixin={};
+L.Mixin.Events={addEventListener:function(a,b,c){var d=this._leaflet_events=this._leaflet_events||{};d[a]=d[a]||[];d[a].push({action:b,context:c});return this},hasEventListeners:function(a){return"_leaflet_events"in this&&a in this._leaflet_events&&this._leaflet_events[a].length>0},removeEventListener:function(a,b,c){if(!this.hasEventListeners(a))return this;for(var d=0,e=this._leaflet_events,f=e[a].length;d<f;d++)if(e[a][d].action===b&&(!c||e[a][d].context===c)){e[a].splice(d,1);break}return this},fireEvent:function(a,
+b){if(this.hasEventListeners(a)){for(var c=L.Util.extend({type:a,target:this},b),d=this._leaflet_events[a].slice(),e=0,f=d.length;e<f;e++)d[e].action.call(d[e].context||this,c);return this}}};L.Mixin.Events.on=L.Mixin.Events.addEventListener;L.Mixin.Events.off=L.Mixin.Events.removeEventListener;L.Mixin.Events.fire=L.Mixin.Events.fireEvent;(function(){var a=navigator.userAgent.toLowerCase(),b=!!window.ActiveXObject,c=a.indexOf("webkit")!=-1,d=a.indexOf("mobi")!=-1,e=a.indexOf("android")!=-1,f=window.opera;L.Browser={ie:b,ie6:b&&!window.XMLHttpRequest,webkit:c,webkit3d:c&&"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix,mobileWebkit:c&&(d||e),mobileOpera:d&&f,gecko:a.indexOf("gecko")!=-1,android:e};L.Browser.touch=L.Browser.mobileWebkit||L.Browser.mobileOpera})();L.Point=function(a,b,c){this.x=c?Math.round(a):a;this.y=c?Math.round(b):b};
+L.Point.prototype={add:function(a){return this.clone()._add(a)},_add:function(a){this.x+=a.x;this.y+=a.y;return this},subtract:function(a){return this.clone()._subtract(a)},_subtract:function(a){this.x-=a.x;this.y-=a.y;return this},divideBy:function(a,b){return new L.Point(this.x/a,this.y/a,b)},multiplyBy:function(a){return new L.Point(this.x*a,this.y*a)},distanceTo:function(a){var b=a.x-this.x,a=a.y-this.y;return Math.sqrt(b*b+a*a)},round:function(){return this.clone()._round()},_round:function(){this.x=
+Math.round(this.x);this.y=Math.round(this.y);return this},clone:function(){return new L.Point(this.x,this.y)},toString:function(){return"Point("+L.Util.formatNum(this.x)+", "+L.Util.formatNum(this.y)+")"}};L.Bounds=L.Class.extend({initialize:function(a,b){if(a)for(var c=a instanceof Array?a:[a,b],d=0,e=c.length;d<e;d++)this.extend(c[d])},extend:function(a){!this.min&&!this.max?(this.min=new L.Point(a.x,a.y),this.max=new L.Point(a.x,a.y)):(this.min.x=Math.min(a.x,this.min.x),this.max.x=Math.max(a.x,this.max.x),this.min.y=Math.min(a.y,this.min.y),this.max.y=Math.max(a.y,this.max.y))},getCenter:function(a){return new L.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,a)},contains:function(a){var b;
+if(a instanceof L.Bounds)b=a.min,a=a.max;return b.x>=this.min.x&&a.x<=this.max.x&&b.y>=this.min.y&&a.y<=this.max.y}});L.Transformation=L.Class.extend({initialize:function(a,b,c,d){this._a=a;this._b=b;this._c=c;this._d=d},transform:function(a,b){return this._transform(a.clone(),b)},_transform:function(a,b){b=b||1;a.x=b*(this._a*a.x+this._b);a.y=b*(this._c*a.y+this._d);return a},untransform:function(a,b){b=b||1;return new L.Point((a.x/b-this._b)/this._a,(a.y/b-this._d)/this._c)}});L.LineUtil={simplify:function(a,b){if(!b)return a.slice();a=this.reducePoints(a,b);return a=this.simplifyDP(a,b)},pointToSegmentDistance:function(a,b,c){return Math.sqrt(this._sqPointToSegmentDist(a,b,c))},simplifyDP:function(a,b){for(var c=0,d=0,e=b*b,f=1,g=a.length,h;f<g-1;f++)h=this._sqPointToSegmentDist(a[f],a[0],a[g-1]),h>c&&(d=f,c=h);return c>=e?(c=a.slice(0,d),d=a.slice(d),g=this.simplifyDP(c,b).slice(0,g-2),d=this.simplifyDP(d,b),g.concat(d)):[a[0],a[g-1]]},reducePoints:function(a,b){for(var c=
+[a[0]],d=b*b,e=1,f=0,g=a.length;e<g;e++)this._sqDist(a[e],a[f])<d||(c.push(a[e]),f=e);f<g-1&&c.push(a[g-1]);return c},clipSegment:function(a,b,c,d){var d=d?this._lastCode:this._getBitCode(a,c),e=this._getBitCode(b,c);for(this._lastCode=e;;)if(d|e)if(d&e)return!1;else{var f=d||e,g=this._getEdgeIntersection(a,b,f,c),h=this._getBitCode(g,c);f==d?(a=g,d=h):(b=g,e=h)}else return[a,b]},_getEdgeIntersection:function(a,b,c,d){var e=b.x-a.x,b=b.y-a.y,f=d.min,d=d.max;if(c&8)return new L.Point(a.x+e*(d.y-a.y)/
+b,d.y);else if(c&4)return new L.Point(a.x+e*(f.y-a.y)/b,f.y);else if(c&2)return new L.Point(d.x,a.y+b*(d.x-a.x)/e);else if(c&1)return new L.Point(f.x,a.y+b*(f.x-a.x)/e)},_getBitCode:function(a,b){var c=0;a.x<b.min.x?c|=1:a.x>b.max.x&&(c|=2);a.y<b.min.y?c|=4:a.y>b.max.y&&(c|=8);return c},_sqDist:function(a,b){var c=b.x-a.x,d=b.y-a.y;return c*c+d*d},_sqPointToSegmentDist:function(a,b,c){var d=c.x-b.x,e=c.y-b.y;if(!d&&!e)return this._sqDist(a,b);var f=((a.x-b.x)*d+(a.y-b.y)*e)/this._sqDist(b,c);if(f<
+0)return this._sqDist(a,b);if(f>1)return this._sqDist(a,c);b=new L.Point(b.x+d*f,b.y+e*f);return this._sqDist(a,b)}};L.PolyUtil={};L.PolyUtil.clipPolygon=function(a,b){var c,d=[1,4,2,8],e,f,g,h,j,k,l=L.LineUtil;e=0;for(j=a.length;e<j;e++)a[e]._code=l._getBitCode(a[e],b);for(g=0;g<4;g++){k=d[g];c=[];e=0;j=a.length;for(f=j-1;e<j;f=e++)if(h=a[e],f=a[f],h._code&k){if(!(f._code&k))f=l._getEdgeIntersection(f,h,k,b),f._code=l._getBitCode(f,b),c.push(f)}else{if(f._code&k)f=l._getEdgeIntersection(f,h,k,b),f._code=l._getBitCode(f,b),c.push(f);c.push(h)}a=c}return a};L.DomEvent={addListener:function(a,b,c,d){function e(b){return c.call(d||a,b||L.DomEvent._getEvent())}var f=L.Util.stamp(c);if(L.Browser.touch&&b=="dblclick"&&this.addDoubleTapListener)this.addDoubleTapListener(a,e,f);else if("addEventListener"in a)if(b=="mousewheel")a.addEventListener("DOMMouseScroll",e,!1),a.addEventListener(b,e,!1);else if(b=="mouseenter"||b=="mouseleave"){var g=e,e=function(b){if(L.DomEvent._checkMouse(a,b))return g(b)};a.addEventListener(b=="mouseenter"?"mouseover":"mouseout",
+e,!1)}else a.addEventListener(b,e,!1);else"attachEvent"in a&&a.attachEvent("on"+b,e);a["_leaflet_"+b+f]=e},removeListener:function(a,b,c){var c=L.Util.stamp(c),d="_leaflet_"+b+c;handler=a[d];L.Browser.mobileWebkit&&b=="dblclick"&&this.removeDoubleTapListener?this.removeDoubleTapListener(a,c):"removeEventListener"in a?b=="mousewheel"?(a.removeEventListener("DOMMouseScroll",handler,!1),a.removeEventListener(b,handler,!1)):b=="mouseenter"||b=="mouseleave"?a.removeEventListener(b=="mouseenter"?"mouseover":
+"mouseout",handler,!1):a.removeEventListener(b,handler,!1):"detachEvent"in a&&a.detachEvent("on"+b,handler);a[d]=null},_checkMouse:function(a,b){var c=b.relatedTarget;if(!c)return!0;try{for(;c&&c!=a;)c=c.parentNode}catch(d){return!1}return c!=a},_getEvent:function(){var a=window.event;if(!a)for(var b=arguments.callee.caller;b;){if((a=b.arguments[0])&&Event==a.constructor)break;b=b.caller}return a},stopPropagation:function(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0},disableClickPropagation:function(a){L.DomEvent.addListener(a,
+"mousedown",L.DomEvent.stopPropagation);L.DomEvent.addListener(a,"click",L.DomEvent.stopPropagation);L.DomEvent.addListener(a,"dblclick",L.DomEvent.stopPropagation)},preventDefault:function(a){a.preventDefault?a.preventDefault():a.returnValue=!1},stop:function(a){L.DomEvent.preventDefault(a);L.DomEvent.stopPropagation(a)},getMousePosition:function(a,b){var c=new L.Point(a.pageX?a.pageX:a.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,a.pageY?a.pageY:a.clientY+document.body.scrollTop+
+document.documentElement.scrollTop);return b?c.subtract(L.DomUtil.getCumulativeOffset(b)):c},getWheelDelta:function(a){var b=0;a.wheelDelta&&(b=a.wheelDelta/120);a.detail&&(b=-a.detail/3);return b}};L.Util.extend(L.DomEvent,{addDoubleTapListener:function(a,b,c){function d(a){if(a.touches.length==1){var b=Date.now(),c=b-(f||b);j=a.touches[0];g=c>0&&c<=h;f=b}}function e(){if(g)j.type="dblclick",b(j),f=null}var f,g=!1,h=250,j;a["_leaflet_touchstart"+c]=d;a["_leaflet_touchend"+c]=e;a.addEventListener("touchstart",d,!1);a.addEventListener("touchend",e,!1)},removeDoubleTapListener:function(a,b){a.removeEventListener(a,a["_leaflet_touchstart"+b],!1);a.removeEventListener(a,a["_leaflet_touchend"+b],
+!1)}});L.DomUtil={get:function(a){return typeof a=="string"?document.getElementById(a):a},getStyle:function(a,b){var c=a.style[b];!c&&a.currentStyle&&(c=a.currentStyle[b]);if(!c||c=="auto")c=(c=document.defaultView.getComputedStyle(a,null))?c[b]:null;return c=="auto"?null:c},getCumulativeOffset:function(a){var b=0,c=0;do b+=a.offsetTop||0,c+=a.offsetLeft||0,a=a.offsetParent;while(a);return new L.Point(c,b)},create:function(a,b,c){a=document.createElement(a);a.className=b;c&&c.appendChild(a);return a},disableTextSelection:function(){document.selection&&
+document.selection.empty&&document.selection.empty();if(!this._onselectstart)this._onselectstart=document.onselectstart,document.onselectstart=L.Util.falseFn},enableTextSelection:function(){document.onselectstart=this._onselectstart;this._onselectstart=null},CLASS_RE:/(\\s|^)'+cls+'(\\s|$)/,hasClass:function(a,b){return a.className.length>0&&RegExp("(^|\\s)"+b+"(\\s|$)").test(a.className)},addClass:function(a,b){L.DomUtil.hasClass(a,b)||(a.className+=(a.className?" ":"")+b)},setOpacity:function(a,
+b){L.Browser.ie?a.style.filter="alpha(opacity="+Math.round(b*100)+")":a.style.opacity=b},testProp:function(a){for(var b=document.documentElement.style,c=0;c<a.length;c++)if(a[c]in b)return a[c];return!1},getTranslateString:function(a){return L.DomUtil.TRANSLATE_OPEN+a.x+"px,"+a.y+"px"+L.DomUtil.TRANSLATE_CLOSE},getScaleString:function(a,b){return L.DomUtil.getTranslateString(b)+" scale("+a+") "+L.DomUtil.getTranslateString(b.multiplyBy(-1))},setPosition:function(a,b){a._leaflet_pos=b;L.Browser.webkit?
+a.style[L.DomUtil.TRANSFORM]=L.DomUtil.getTranslateString(b):(a.style.left=b.x+"px",a.style.top=b.y+"px")},getPosition:function(a){return a._leaflet_pos}};
+L.Util.extend(L.DomUtil,{TRANSITION:L.DomUtil.testProp(["transition","webkitTransition","OTransition","MozTransition","msTransition"]),TRANSFORM:L.DomUtil.testProp(["transformProperty","WebkitTransform","OTransform","MozTransform","msTransform"]),TRANSLATE_OPEN:"translate"+(L.Browser.webkit3d?"3d(":"("),TRANSLATE_CLOSE:L.Browser.webkit3d?",0)":")"});L.Draggable=L.Class.extend({includes:L.Mixin.Events,statics:{START:L.Browser.touch?"touchstart":"mousedown",END:L.Browser.touch?"touchend":"mouseup",MOVE:L.Browser.touch?"touchmove":"mousemove",TAP_TOLERANCE:15},initialize:function(a,b){this._element=a;this._dragStartTarget=b||a},enable:function(){if(!this._enabled)L.DomEvent.addListener(this._dragStartTarget,L.Draggable.START,this._onDown,this),this._enabled=!0},disable:function(){if(this._enabled)L.DomEvent.removeListener(this._dragStartTarget,
+L.Draggable.START,this._onDown),this._enabled=!1},_onDown:function(a){if(!(a.shiftKey||a.which!=1&&a.button!=1&&!a.touches)&&!(a.touches&&a.touches.length>1)){var b=a.touches&&a.touches.length==1?a.touches[0]:a;L.DomEvent.preventDefault(a);L.Browser.mobileWebkit&&(b.target.className+=" leaflet-active");this._moved=!1;L.DomUtil.disableTextSelection();this._setMovingCursor();this._startPos=this._newPos=L.DomUtil.getPosition(this._element);this._startPoint=new L.Point(b.clientX,b.clientY);L.DomEvent.addListener(document,
+L.Draggable.MOVE,this._onMove,this);L.DomEvent.addListener(document,L.Draggable.END,this._onUp,this)}},_onMove:function(a){if(!(a.touches&&a.touches.length>1)){L.DomEvent.preventDefault(a);a=a.touches&&a.touches.length==1?a.touches[0]:a;if(!this._moved)this.fire("dragstart"),this._moved=!0;this._newPos=this._startPos.add(new L.Point(a.clientX,a.clientY)).subtract(this._startPoint);L.Util.requestAnimFrame(this._updatePosition,this,!0);this.fire("drag")}},_updatePosition:function(){L.DomUtil.setPosition(this._element,
+this._newPos)},_onUp:function(a){if(a.changedTouches){var a=a.changedTouches[0],b=a.target,c=this._newPos&&this._newPos.distanceTo(this._startPos)||0;b.className=b.className.replace(" leaflet-active","");c<L.Draggable.TAP_TOLERANCE&&this._simulateEvent("click",a)}L.DomUtil.enableTextSelection();this._restoreCursor();L.DomEvent.removeListener(document,L.Draggable.MOVE,this._onMove);L.DomEvent.removeListener(document,L.Draggable.END,this._onUp);this._moved&&this.fire("dragend")},_removeActiveClass:function(){},
+_setMovingCursor:function(){this._bodyCursor=document.body.style.cursor;document.body.style.cursor="move"},_restoreCursor:function(){document.body.style.cursor=this._bodyCursor},_simulateEvent:function(a,b){var c=document.createEvent("MouseEvent");c.initMouseEvent(a,!0,!0,window,1,b.screenX,b.screenY,b.clientX,b.clientY,!1,!1,!1,!1,0,null);b.target.dispatchEvent(c)}});L.Transition=L.Class.extend({includes:L.Mixin.Events,statics:{CUSTOM_PROPS_SETTERS:{position:L.DomUtil.setPosition},implemented:function(){return L.Transition.NATIVE||L.Transition.TIMER}},options:{easing:"ease",duration:0.5},_setProperty:function(a,b){var c=L.Transition.CUSTOM_PROPS_SETTERS;if(a in c)c[a](this._el,b);else this._el.style[a]=b}});L.Transition=L.Transition.extend({statics:function(){var a=L.DomUtil.TRANSITION;return{NATIVE:!!a,TRANSITION:a,PROPERTY:a+"Property",DURATION:a+"Duration",EASING:a+"TimingFunction",END:a=="webkitTransition"||a=="OTransition"?a+"End":"transitionend",CUSTOM_PROPS_PROPERTIES:{position:L.Browser.webkit?L.DomUtil.TRANSFORM:"top, left"}}}(),options:{fakeStepInterval:100},initialize:function(a,b){this._el=a;L.Util.setOptions(this,b);L.DomEvent.addListener(a,L.Transition.END,this._onTransitionEnd,this);this._onFakeStep=
+L.Util.bind(this._onFakeStep,this)},run:function(a){var b,c=[],d=L.Transition.CUSTOM_PROPS_PROPERTIES;for(b in a)a.hasOwnProperty(b)&&(b=d[b]?d[b]:b,b=b.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()}),c.push(b));this._el.style[L.Transition.DURATION]=this.options.duration+"s";this._el.style[L.Transition.EASING]=this.options.easing;this._el.style[L.Transition.PROPERTY]=c.join(", ");for(b in a)a.hasOwnProperty(b)&&this._setProperty(b,a[b]);this._inProgress=!0;this.fire("start");L.Transition.NATIVE?
+this._timer=setInterval(this._onFakeStep,this.options.fakeStepInterval):this._onTransitionEnd()},_onFakeStep:function(){this.fire("step")},_onTransitionEnd:function(){if(this._inProgress)this._inProgress=!1,clearInterval(this._timer),this._el.style[L.Transition.PROPERTY]="none",this.fire("step"),this.fire("end")}});L.Transition=L.Transition.NATIVE?L.Transition:L.Transition.extend({statics:{getTime:Date.now||function(){return+new Date},TIMER:!0,EASINGS:{ease:[0.25,0.1,0.25,1],linear:[0,0,1,1],"ease-in":[0.42,0,1,1],"ease-out":[0,0,0.58,1],"ease-in-out":[0.42,0,0.58,1]},CUSTOM_PROPS_GETTERS:{position:L.DomUtil.getPosition},UNIT_RE:/^[\d\.]+(\D*)$/},options:{fps:50},initialize:function(a,b){this._el=a;L.Util.extend(this.options,b);var c=L.Transition.EASINGS[this.options.easing]||L.Transition.EASINGS.ease;this._p1=
+new L.Point(0,0);this._p2=new L.Point(c[0],c[1]);this._p3=new L.Point(c[2],c[3]);this._p4=new L.Point(1,1);this._step=L.Util.bind(this._step,this);this._interval=Math.round(1E3/this.options.fps)},run:function(a){this._props={};var b=L.Transition.CUSTOM_PROPS_GETTERS,c=L.Transition.UNIT_RE;this.fire("start");for(var d in a)if(a.hasOwnProperty(d)){var e={};if(d in b)e.from=b[d](this._el);else{var f=this._el.style[d].match(c);e.from=parseFloat(f[0]);e.unit=f[1]}e.to=a[d];this._props[d]=e}clearInterval(this._timer);
+this._timer=setInterval(this._step,this._interval);this._startTime=L.Transition.getTime()},_step:function(){var a=L.Transition.getTime()-this._startTime,b=this.options.duration*1E3;a<b?this._runFrame(this._cubicBezier(a/b)):(this._runFrame(1),this._complete())},_runFrame:function(a){var b=L.Transition.CUSTOM_PROPS_SETTERS,c,d;for(c in this._props)this._props.hasOwnProperty(c)&&(d=this._props[c],c in b?(d=d.to.subtract(d.from).multiplyBy(a).add(d.from),b[c](this._el,d)):this._el.style[c]=(d.to-d.from)*
+a+d.from+d.unit);this.fire("step")},_complete:function(){clearInterval(this._timer);this.fire("end")},_cubicBezier:function(a){var b=3*Math.pow(1-a,2)*a,c=3*(1-a)*Math.pow(a,2),d=Math.pow(a,3),a=this._p1.multiplyBy(Math.pow(1-a,3)),b=this._p2.multiplyBy(b),c=this._p3.multiplyBy(c),d=this._p4.multiplyBy(d);return a.add(b).add(c).add(d).y}});L.LatLng=function(a,b,c){c!==!0&&(a=Math.max(Math.min(a,90),-90),b=(b+180)%360+(b<-180?180:-180));this.lat=a;this.lng=b};L.Util.extend(L.LatLng,{DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,MAX_MARGIN:1.0E-9});L.LatLng.prototype={equals:function(a){if(!(a instanceof L.LatLng))return!1;return Math.max(Math.abs(this.lat-a.lat),Math.abs(this.lng-a.lng))<=L.LatLng.MAX_MARGIN},toString:function(){return"LatLng("+L.Util.formatNum(this.lat)+", "+L.Util.formatNum(this.lng)+")"}};L.LatLngBounds=L.Class.extend({initialize:function(a,b){if(a)for(var c=a instanceof Array?a:[a,b],d=0,e=c.length;d<e;d++)this.extend(c[d])},extend:function(a){!this._southWest&&!this._northEast?(this._southWest=new L.LatLng(a.lat,a.lng),this._northEast=new L.LatLng(a.lat,a.lng)):(this._southWest.lat=Math.min(a.lat,this._southWest.lat),this._southWest.lng=Math.min(a.lng,this._southWest.lng),this._northEast.lat=Math.max(a.lat,this._northEast.lat),this._northEast.lng=Math.max(a.lng,this._northEast.lng))},
+getCenter:function(){return new L.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new L.LatLng(this._northEast.lat,this._southWest.lng)},getSouthEast:function(){return new L.LatLng(this._southWest.lat,this._northEast.lng)},contains:function(a){var b=this._southWest,c=this._northEast,d;a instanceof L.LatLngBounds?(d=a.getSouthWest(),
+a=a.getNorthEast()):d=a;return d.lat>=b.lat&&a.lat<=c.lat&&d.lng>=b.lng&&a.lng<=c.lng}});L.Projection={};L.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(a){var b=L.LatLng.DEG_TO_RAD,c=this.MAX_LATITUDE,d=a.lng*b,a=Math.max(Math.min(c,a.lat),-c)*b,a=Math.log(Math.tan(Math.PI/4+a/2));return new L.Point(d,a)},unproject:function(a,b){var c=L.LatLng.RAD_TO_DEG;return new L.LatLng((2*Math.atan(Math.exp(a.y))-Math.PI/2)*c,a.x*c,b)}};L.Projection.LonLat={project:function(a){return new L.Point(a.lng,a.lat)},unproject:function(a,b){return new L.LatLng(a.y,a.x,b)}};L.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.3142,R_MAJOR:6378137,project:function(a){var b=L.LatLng.DEG_TO_RAD,c=this.MAX_LATITUDE,d=this.R_MAJOR,e=a.lng*b*d,a=Math.max(Math.min(c,a.lat),-c)*b,b=this.R_MINOR/d,b=Math.sqrt(1-b*b),c=b*Math.sin(a),c=Math.pow((1-c)/(1+c),b*0.5),a=-d*Math.log(Math.tan(0.5*(Math.PI*0.5-a))/c);return new L.Point(e,a)},unproject:function(a,b){for(var c=L.LatLng.RAD_TO_DEG,d=this.R_MAJOR,e=a.x*c/d,f=this.R_MINOR/d,f=Math.sqrt(1-f*f),d=Math.exp(-a.y/d),
+g=Math.PI/2-2*Math.atan(d),h=15,j=0.1;Math.abs(j)>1.0E-7&&--h>0;)j=f*Math.sin(g),j=Math.PI/2-2*Math.atan(d*Math.pow((1-j)/(1+j),0.5*f))-g,g+=j;return new L.LatLng(g*c,e,b)}};L.CRS={latLngToPoint:function(a,b){return this.transformation._transform(this.projection.project(a),b)},pointToLatLng:function(a,b,c){return this.projection.unproject(this.transformation.untransform(a,b),c)},project:function(a){return this.projection.project(a)}};L.CRS.EPSG3857=L.Util.extend({},L.CRS,{code:"EPSG:3857",projection:L.Projection.SphericalMercator,transformation:new L.Transformation(0.5/Math.PI,0.5,-0.5/Math.PI,0.5),project:function(a){return this.projection.project(a).multiplyBy(6378137)}});L.CRS.EPSG900913=L.Util.extend({},L.CRS.EPSG3857,{code:"EPSG:900913"});L.CRS.EPSG4326=L.Util.extend({},L.CRS,{code:"EPSG:4326",projection:L.Projection.LonLat,transformation:new L.Transformation(1/360,0.5,-1/360,0.5)});L.CRS.EPSG3395=L.Util.extend({},L.CRS,{code:"EPSG:3395",projection:L.Projection.Mercator,transformation:function(){var a=L.Projection.Mercator;return new L.Transformation(0.5/(Math.PI*a.R_MAJOR),0.5,-0.5/(Math.PI*a.R_MINOR),0.5)}()});L.LayerGroup=L.Class.extend({initialize:function(a){this._layers={};if(a)for(var b=0,c=a.length;b<c;b++)this.addLayer(a[b])},addLayer:function(a){this._layers[L.Util.stamp(a)]=a;this._map&&this._map.addLayer(a);return this},removeLayer:function(a){delete this._layers[L.Util.stamp(a)];this._map&&this._map.removeLayer(a);return this},clearLayers:function(){this._iterateLayers(this.removeLayer,this);return this},onAdd:function(a){this._map=a;this._iterateLayers(a.addLayer,a)},onRemove:function(a){this._iterateLayers(a.removeLayer,
+a);delete this._map},_iterateLayers:function(a,b){for(var c in this._layers)this._layers.hasOwnProperty(c)&&a.call(b,this._layers[c])}});L.FeatureGroup=L.LayerGroup.extend({includes:L.Mixin.Events,addLayer:function(a){this._initEvents(a);L.LayerGroup.prototype.addLayer.call(this,a);this._popupContent&&a.bindPopup&&a.bindPopup(this._popupContent)},bindPopup:function(a){this._popupContent=a;for(var b in this._layers)this._layers.hasOwnProperty(b)&&this._layers[b].bindPopup&&this._layers[b].bindPopup(a)},_events:["click","dblclick","mouseover","mouseout"],_initEvents:function(a){for(var b=0,c=this._events.length;b<c;b++)a.on(this._events[b],
+this._propagateEvent,this)},_propagateEvent:function(a){a.layer=a.target;a.target=this;this.fire(a.type,a)}});L.TileLayer=L.Class.extend({includes:L.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",opacity:1,scheme:"xyz",noWrap:!1,unloadInvisibleTiles:L.Browser.mobileWebkit,updateWhenIdle:L.Browser.mobileWebkit},initialize:function(a,b){L.Util.setOptions(this,b);this._url=a;if(typeof this.options.subdomains=="string")this.options.subdomains=this.options.subdomains.split("")},onAdd:function(a){this._map=a;this._initContainer();this._createTileProto();
+a.on("viewreset",this._reset,this);if(this.options.updateWhenIdle)a.on("moveend",this._update,this);else this._limitedUpdate=L.Util.limitExecByInterval(this._update,100,this),a.on("move",this._limitedUpdate,this);this._reset();this._update()},onRemove:function(){this._map.getPanes().tilePane.removeChild(this._container);this._container=null;this._map.off("viewreset",this._reset,this);this.options.updateWhenIdle?this._map.off("moveend",this._update,this):this._map.off("move",this._limitedUpdate,this)},
+getAttribution:function(){return this.options.attribution},setOpacity:function(a){this.options.opacity=a;this._setOpacity(a);if(L.Browser.webkit)for(i in this._tiles)this._tiles[i].style.webkitTransform+=" translate(0,0)"},_setOpacity:function(a){a<1&&L.DomUtil.setOpacity(this._container,a)},_initContainer:function(){var a=this._map.getPanes().tilePane;if(!this._container||a.empty)this._container=L.DomUtil.create("div","leaflet-layer",a),this._setOpacity(this.options.opacity)},_reset:function(){this._tiles=
+{};this._initContainer();this._container.innerHTML=""},_update:function(){var a=this._map.getPixelBounds(),b=this.options.tileSize,c=new L.Point(Math.floor(a.min.x/b),Math.floor(a.min.y/b)),a=new L.Point(Math.floor(a.max.x/b),Math.floor(a.max.y/b)),c=new L.Bounds(c,a);this._addTilesFromCenterOut(c);this.options.unloadInvisibleTiles&&this._removeOtherTiles(c)},_addTilesFromCenterOut:function(a){for(var b=[],c=a.getCenter(),d=a.min.y;d<=a.max.y;d++)for(var e=a.min.x;e<=a.max.x;e++)e+":"+d in this._tiles||
+b.push(new L.Point(e,d));b.sort(function(a,b){return a.distanceTo(c)-b.distanceTo(c)});this._tilesToLoad=b.length;a=0;for(d=this._tilesToLoad;a<d;a++)this._addTile(b[a])},_removeOtherTiles:function(a){var b,c,d;for(d in this._tiles)if(this._tiles.hasOwnProperty(d)&&(b=d.split(":"),c=parseInt(b[0],10),b=parseInt(b[1],10),c<a.min.x||c>a.max.x||b<a.min.y||b>a.max.y))this._tiles[d].src="",this._tiles[d].parentNode==this._container&&this._container.removeChild(this._tiles[d]),delete this._tiles[d]},_addTile:function(a){var b=
+this._getTilePos(a),c=this._map.getZoom(),d=a.x+":"+a.y,e=1<<c;if(!this.options.noWrap)a.x=(a.x%e+e)%e;if(!(a.y<0||a.y>=e)){var f=this._createTile();L.DomUtil.setPosition(f,b);this._tiles[d]=f;if(this.options.scheme=="tms")a.y=e-a.y-1;this._loadTile(f,a,c);this._container.appendChild(f)}},_getTilePos:function(a){var b=this._map.getPixelOrigin();return a.multiplyBy(this.options.tileSize).subtract(b)},getTileUrl:function(a,b){return this._url.replace("{s}",this.options.subdomains[(a.x+a.y)%this.options.subdomains.length]).replace("{z}",
+b).replace("{x}",a.x).replace("{y}",a.y)},_createTileProto:function(){this._tileImg=L.DomUtil.create("img","leaflet-tile");this._tileImg.galleryimg="no";var a=this.options.tileSize;this._tileImg.style.width=a+"px";this._tileImg.style.height=a+"px"},_createTile:function(){var a=this._tileImg.cloneNode(!1);a.onselectstart=a.onmousemove=L.Util.falseFn;return a},_loadTile:function(a,b,c){a._layer=this;a.onload=this._tileOnLoad;a.onerror=this._tileOnError;a.src=this.getTileUrl(b,c)},_tileOnLoad:function(){var a=
+this._layer;this.className+=" leaflet-tile-loaded";a.fire("tileload",{tile:this,url:this.src});a._tilesToLoad--;a._tilesToLoad||a.fire("load")},_tileOnError:function(){var a=this._layer;a.fire("tileerror",{tile:this,url:this.src});if(a=a.options.errorTileUrl)this.src=a}});L.TileLayer.WMS=L.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(a,b){this._url=a;this.wmsParams=L.Util.extend({},this.defaultWmsParams);this.wmsParams.width=this.wmsParams.height=this.options.tileSize;for(var c in b)this.options.hasOwnProperty(c)||(this.wmsParams[c]=b[c]);L.Util.setOptions(this,b)},onAdd:function(a){this.wmsParams[parseFloat(this.wmsParams.version)>=1.3?"crs":"srs"]=a.options.crs.code;
+L.TileLayer.prototype.onAdd.call(this,a)},getTileUrl:function(a){var b=this.options.tileSize,a=a.multiplyBy(b),b=a.add(new L.Point(b,b)),a=this._map.unproject(a,this._zoom,!0),b=this._map.unproject(b,this._zoom,!0),a=this._map.options.crs.project(a),b=this._map.options.crs.project(b),b=[a.x,b.y,b.x,a.y].join(",");return this._url+L.Util.getParamString(this.wmsParams)+"&bbox="+b}});L.TileLayer.Canvas=L.TileLayer.extend({options:{async:!1},initialize:function(a){L.Util.setOptions(this,a)},_createTileProto:function(){this._canvasProto=L.DomUtil.create("canvas","leaflet-tile");var a=this.options.tileSize;this._canvasProto.width=a;this._canvasProto.height=a},_createTile:function(){var a=this._canvasProto.cloneNode(!1);a.onselectstart=a.onmousemove=L.Util.falseFn;return a},_loadTile:function(a,b,c){a._layer=this;this.drawTile(a,b,c);this.options.async||this.tileDrawn(a)},drawTile:function(){},
+tileDrawn:function(a){this._tileOnLoad.call(a)}});L.ImageOverlay=L.Class.extend({includes:L.Mixin.Events,initialize:function(a,b){this._url=a;this._bounds=b},onAdd:function(a){this._map=a;this._image||this._initImage();a.getPanes().overlayPane.appendChild(this._image);a.on("viewreset",this._reset,this);this._reset()},onRemove:function(a){a.getPanes().overlayPane.removeChild(this._image);a.off("viewreset",this._reset,this)},_initImage:function(){this._image=L.DomUtil.create("img","leaflet-image-layer");this._image.style.visibility="hidden";L.Util.extend(this._image,
+{galleryimg:"no",onselectstart:L.Util.falseFn,onmousemove:L.Util.falseFn,onload:this._onImageLoad,src:this._url})},_reset:function(){var a=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),b=this._map.latLngToLayerPoint(this._bounds.getSouthEast()).subtract(a);L.DomUtil.setPosition(this._image,a);this._image.style.width=b.x+"px";this._image.style.height=b.y+"px"},_onImageLoad:function(){this.style.visibility=""}});L.Popup=L.Class.extend({includes:L.Mixin.Events,options:{maxWidth:300,autoPan:!0,closeButton:!0,offset:new L.Point(0,2),autoPanPadding:new L.Point(5,5)},initialize:function(a){L.Util.setOptions(this,a)},onAdd:function(a){this._map=a;this._container||this._initLayout();this._updateContent();this._container.style.opacity="0";this._map._panes.popupPane.appendChild(this._container);this._map.on("viewreset",this._updatePosition,this);if(this._map.options.closePopupOnClick)this._map.on("preclick",this._close,
+this);this._update();this._container.style.opacity="1";this._opened=!0},onRemove:function(a){a._panes.popupPane.removeChild(this._container);a.off("viewreset",this._updatePosition,this);a.off("click",this._close,this);this._container.style.opacity="0";this._opened=!1},setLatLng:function(a){this._latlng=a;this._opened&&this._update();return this},setContent:function(a){this._content=a;this._opened&&this._update();return this},_close:function(){this._opened&&this._map.removeLayer(this)},_initLayout:function(){this._container=
+L.DomUtil.create("div","leaflet-popup");this._closeButton=L.DomUtil.create("a","leaflet-popup-close-button",this._container);this._closeButton.href="#close";this._closeButton.onclick=L.Util.bind(this._onCloseButtonClick,this);this._wrapper=L.DomUtil.create("div","leaflet-popup-content-wrapper",this._container);L.DomEvent.disableClickPropagation(this._wrapper);this._contentNode=L.DomUtil.create("div","leaflet-popup-content",this._wrapper);this._tipContainer=L.DomUtil.create("div","leaflet-popup-tip-container",
+this._container);this._tip=L.DomUtil.create("div","leaflet-popup-tip",this._tipContainer)},_update:function(){this._container.style.visibility="hidden";this._updateContent();this._updateLayout();this._updatePosition();this._container.style.visibility="";this._adjustPan()},_updateContent:function(){if(this._content)typeof this._content=="string"?this._contentNode.innerHTML=this._content:(this._contentNode.innerHTML="",this._contentNode.appendChild(this._content))},_updateLayout:function(){this._container.style.width=
+"";this._container.style.whiteSpace="nowrap";var a=this._container.offsetWidth;this._container.style.width=(a>this.options.maxWidth?this.options.maxWidth:a)+"px";this._container.style.whiteSpace="";this._containerWidth=this._container.offsetWidth},_updatePosition:function(){var a=this._map.latLngToLayerPoint(this._latlng);this._containerBottom=-a.y-this.options.offset.y;this._containerLeft=a.x-Math.round(this._containerWidth/2)+this.options.offset.x;this._container.style.bottom=this._containerBottom+
+"px";this._container.style.left=this._containerLeft+"px"},_adjustPan:function(){if(this.options.autoPan){var a=this._container.offsetHeight,b=this._map.layerPointToContainerPoint(new L.Point(this._containerLeft,-a-this._containerBottom)),c=new L.Point(0,0),d=this.options.autoPanPadding,e=this._map.getSize();if(b.x<0)c.x=b.x-d.x;if(b.x+this._containerWidth>e.x)c.x=b.x+this._containerWidth-e.x+d.x;if(b.y<0)c.y=b.y-d.y;if(b.y+a>e.y)c.y=b.y+a-e.y+d.y;(c.x||c.y)&&this._map.panBy(c)}},_onCloseButtonClick:function(a){this._close();
+L.DomEvent.stop(a)}});L.Icon=L.Class.extend({iconUrl:L.ROOT_URL+"images/marker.png",shadowUrl:L.ROOT_URL+"images/marker-shadow.png",iconSize:new L.Point(25,41),shadowSize:new L.Point(41,41),iconAnchor:new L.Point(13,41),popupAnchor:new L.Point(0,-33),initialize:function(a){if(a)this.iconUrl=a},createIcon:function(){return this._createIcon("icon")},createShadow:function(){return this._createIcon("shadow")},_createIcon:function(a){var b=this[a+"Size"],c=this[a+"Url"],d=this._createImg(c);if(!c)return null;d.className="leaflet-marker-"+
+a;d.style.marginLeft=-this.iconAnchor.x+"px";d.style.marginTop=-this.iconAnchor.y+"px";if(b)d.style.width=b.x+"px",d.style.height=b.y+"px";return d},_createImg:function(a){var b;L.Browser.ie6?(b=document.createElement("div"),b.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+a+'")'):(b=document.createElement("img"),b.src=a);return b}});L.Marker=L.Class.extend({includes:L.Mixin.Events,options:{icon:new L.Icon,title:"",clickable:!0,draggable:!1},initialize:function(a,b){L.Util.setOptions(this,b);this._latlng=a},onAdd:function(a){this._map=a;this._initIcon();a.on("viewreset",this._reset,this);this._reset()},onRemove:function(a){this._removeIcon();a.off("viewreset",this._reset,this)},getLatLng:function(){return this._latlng},setLatLng:function(a){this._latlng=a;this._reset()},setIcon:function(a){this._removeIcon();this._icon=this._shadow=
+null;this.options.icon=a;this._initIcon()},_initIcon:function(){if(!this._icon){this._icon=this.options.icon.createIcon();if(this.options.title)this._icon.title=this.options.title;this._initInteraction()}if(!this._shadow)this._shadow=this.options.icon.createShadow();this._map._panes.markerPane.appendChild(this._icon);this._shadow&&this._map._panes.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this._map._panes.markerPane.removeChild(this._icon);this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow)},
+_reset:function(){var a=this._map.latLngToLayerPoint(this._latlng).round();L.DomUtil.setPosition(this._icon,a);this._shadow&&L.DomUtil.setPosition(this._shadow,a);this._icon.style.zIndex=a.y},_initInteraction:function(){if(this.options.clickable){this._icon.className+=" leaflet-clickable";L.DomEvent.addListener(this._icon,"click",this._onMouseClick,this);for(var a=["dblclick","mousedown","mouseover","mouseout"],b=0;b<a.length;b++)L.DomEvent.addListener(this._icon,a[b],this._fireMouseEvent,this)}if(L.Handler.MarkerDrag)this.dragging=
+new L.Handler.MarkerDrag(this),this.options.draggable&&this.dragging.enable()},_onMouseClick:function(a){L.DomEvent.stopPropagation(a);(!this.dragging||!this.dragging.moved())&&this.fire(a.type)},_fireMouseEvent:function(a){this.fire(a.type);L.DomEvent.stopPropagation(a)}});L.Marker.include({openPopup:function(){this._popup.setLatLng(this._latlng);this._map.openPopup(this._popup);return this},closePopup:function(){this._popup&&this._popup._close()},bindPopup:function(a,b){b=L.Util.extend({offset:this.options.icon.popupAnchor},b);this._popup=new L.Popup(b);this._popup.setContent(a);this.on("click",this.openPopup,this);return this}});L.Path=L.Class.extend({includes:[L.Mixin.Events],statics:function(){return{SVG_NS:"http://www.w3.org/2000/svg",SVG:!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect),CLIP_PADDING:0.5}}(),options:{stroke:!0,color:"#0033ff",weight:5,opacity:0.5,fill:!1,fillColor:null,fillOpacity:0.2,clickable:!0,updateOnMoveEnd:!1},initialize:function(a){L.Util.setOptions(this,a)},onAdd:function(a){this._map=a;this._initElements();this._initEvents();this.projectLatlngs();
+this._updatePath();a.on("viewreset",this.projectLatlngs,this);this._updateTrigger=this.options.updateOnMoveEnd?"moveend":"viewreset";a.on(this._updateTrigger,this._updatePath,this)},onRemove:function(a){a._pathRoot.removeChild(this._container);a.off("viewreset",this._projectLatlngs,this);a.off(this._updateTrigger,this._updatePath,this)},projectLatlngs:function(){},getPathString:function(){},setStyle:function(a){L.Util.setOptions(this,a);this._path&&this._updateStyle()},_initElements:function(){this._initRoot();
+this._initPath();this._initStyle()},_initRoot:function(){if(!this._map._pathRoot)this._map._pathRoot=this._createElement("svg"),this._map._panes.overlayPane.appendChild(this._map._pathRoot),this._map.on("moveend",this._updateSvgViewport,this),this._updateSvgViewport()},_updateSvgViewport:function(){this._updateViewport();var a=this._map._pathViewport,b=a.min,c=a.max,a=c.x-b.x,c=c.y-b.y,d=this._map._pathRoot,e=this._map._panes.overlayPane;L.Browser.mobileWebkit&&e.removeChild(d);L.DomUtil.setPosition(d,
+b);d.setAttribute("width",a);d.setAttribute("height",c);d.setAttribute("viewBox",[b.x,b.y,a,c].join(" "));L.Browser.mobileWebkit&&e.appendChild(d)},_updateViewport:function(){var a=L.Path.CLIP_PADDING,b=this._map.getSize(),c=L.DomUtil.getPosition(this._map._mapPane).multiplyBy(-1).subtract(b.multiplyBy(a)),a=c.add(b.multiplyBy(1+a*2));this._map._pathViewport=new L.Bounds(c,a)},_initPath:function(){this._container=this._createElement("g");this._path=this._createElement("path");this._container.appendChild(this._path);
+this._map._pathRoot.appendChild(this._container)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round"));this.options.fill?this._path.setAttribute("fill-rule","evenodd"):this._path.setAttribute("fill","none");this._updateStyle()},_updateStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",
+this.options.weight));this.options.fill&&(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity))},_updatePath:function(){var a=this.getPathString();a||(a="M0 0");this._path.setAttribute("d",a)},_createElement:function(a){return document.createElementNS(L.Path.SVG_NS,a)},_initEvents:function(){if(this.options.clickable){L.Path.VML||this._path.setAttribute("class","leaflet-clickable");L.DomEvent.addListener(this._container,
+"click",this._onMouseClick,this);for(var a=["dblclick","mousedown","mouseover","mouseout"],b=0;b<a.length;b++)L.DomEvent.addListener(this._container,a[b],this._fireMouseEvent,this)}},_onMouseClick:function(a){(!this._map.dragging||!this._map.dragging.moved())&&this._fireMouseEvent(a)},_fireMouseEvent:function(a){this.hasEventListeners(a.type)&&(this.fire(a.type,{latlng:this._map.mouseEventToLatLng(a),layerPoint:this._map.mouseEventToLayerPoint(a)}),L.DomEvent.stopPropagation(a))},_redraw:function(){this.projectLatlngs();
+this._updatePath()}});L.Path.VML=function(){var a=document.createElement("div");a.innerHTML='<v:shape adj="1"/>';a=a.firstChild;a.style.behavior="url(#default#VML)";return a&&typeof a.adj=="object"}();
+L.Path=L.Path.SVG||!L.Path.VML?L.Path:L.Path.extend({statics:{CLIP_PADDING:0.02},_createElement:function(){try{return document.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(a){return document.createElement("<lvml:"+a+' class="lvml">')}}catch(a){return function(a){return document.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initRoot:function(){if(!this._map._pathRoot)this._map._pathRoot=document.createElement("div"),this._map._pathRoot.className=
+"leaflet-vml-container",this._map._panes.overlayPane.appendChild(this._map._pathRoot),this._map.on("moveend",this._updateViewport,this),this._updateViewport()},_initPath:function(){this._container=this._createElement("shape");this._container.className+=" leaflet-vml-shape"+(this.options.clickable?" leaflet-clickable":"");this._container.coordsize="1 1";this._path=this._createElement("path");this._container.appendChild(this._path);this._map._pathRoot.appendChild(this._container)},_initStyle:function(){this.options.stroke?
+(this._stroke=this._createElement("stroke"),this._stroke.endcap="round",this._container.appendChild(this._stroke)):this._container.stroked=!1;this.options.fill?(this._container.filled=!0,this._fill=this._createElement("fill"),this._container.appendChild(this._fill)):this._container.filled=!1;this._updateStyle()},_updateStyle:function(){if(this.options.stroke)this._stroke.weight=this.options.weight+"px",this._stroke.color=this.options.color,this._stroke.opacity=this.options.opacity;if(this.options.fill)this._fill.color=
+this.options.fillColor||this.options.color,this._fill.opacity=this.options.fillOpacity},_updatePath:function(){this._container.style.display="none";this._path.v=this.getPathString()+" ";this._container.style.display=""}});L.Path.include({bindPopup:function(a,b){if(!this._popup||this._popup.options!==b)this._popup=new L.Popup(b);this._popup.setContent(a);if(!this._openPopupAdded)this.on("click",this._openPopup,this),this._openPopupAdded=!0;return this},_openPopup:function(a){this._popup.setLatLng(a.latlng);this._map.openPopup(this._popup)}});L.Polyline=L.Path.extend({initialize:function(a,b){L.Path.prototype.initialize.call(this,b);this._latlngs=a},options:{smoothFactor:1,noClip:!1,updateOnMoveEnd:!0},projectLatlngs:function(){this._originalPoints=[];for(var a=0,b=this._latlngs.length;a<b;a++)this._originalPoints[a]=this._map.latLngToLayerPoint(this._latlngs[a])},getPathString:function(){for(var a=0,b=this._parts.length,c="";a<b;a++)c+=this._getPathPartStr(this._parts[a]);return c},getLatLngs:function(){return this._latlngs},setLatLngs:function(a){this._latlngs=
+a;this._redraw();return this},addLatLng:function(a){this._latlngs.push(a);this._redraw();return this},spliceLatLngs:function(){var a=[].splice.apply(this._latlngs,arguments);this._redraw();return a},_getPathPartStr:function(a){for(var b=L.Path.VML,c=0,d=a.length,e="",f;c<d;c++)f=a[c],b&&f._round(),e+=(c?"L":"M")+f.x+" "+f.y;return e},_clipPoints:function(){var a=this._originalPoints,b=a.length,c,d,e;if(this.options.noClip)this._parts=[a];else{var f=this._parts=[],g=this._map._pathViewport,h=L.LineUtil;
+for(d=c=0;c<b-1;c++)if(e=h.clipSegment(a[c],a[c+1],g,c))if(f[d]=f[d]||[],f[d].push(e[0]),e[1]!=a[c+1]||c==b-2)f[d].push(e[1]),d++}},_simplifyPoints:function(){for(var a=this._parts,b=L.LineUtil,c=0,d=a.length;c<d;c++)a[c]=b.simplify(a[c],this.options.smoothFactor)},_updatePath:function(){this._clipPoints();this._simplifyPoints();L.Path.prototype._updatePath.call(this)}});L.Polygon=L.Polyline.extend({options:{fill:!0},initialize:function(a,b){L.Polyline.prototype.initialize.call(this,a,b);if(a[0]instanceof Array)this._latlngs=a[0],this._holes=a.slice(1)},projectLatlngs:function(){L.Polyline.prototype.projectLatlngs.call(this);this._holePoints=[];if(this._holes)for(var a=0,b=this._holes.length;a<b;a++){this._holePoints[a]=[];for(var c=0,d=this._holes[a].length;c<d;c++)this._holePoints[a][c]=this._map.latLngToLayerPoint(this._holes[a][c])}},_clipPoints:function(){var a=
+[];this._parts=[this._originalPoints].concat(this._holePoints);if(!this.options.noClip){for(var b=0,c=this._parts.length;b<c;b++){var d=L.PolyUtil.clipPolygon(this._parts[b],this._map._pathViewport);d.length&&a.push(d)}this._parts=a}},_getPathPartStr:function(a){return L.Polyline.prototype._getPathPartStr.call(this,a)+(L.Path.SVG?"z":"x")}});(function(){function a(a){return L.FeatureGroup.extend({initialize:function(c,d){this._layers={};for(var e=0,f=c.length;e<f;e++)this.addLayer(new a(c[e],d))},setStyle:function(a){for(var b in this._layers)this._layers.hasOwnProperty(b)&&this._layers[b].setStyle&&this._layers[b].setStyle(a)}})}L.MultiPolyline=a(L.Polyline);L.MultiPolygon=a(L.Polygon)})();L.Circle=L.Path.extend({initialize:function(a,b,c){L.Path.prototype.initialize.call(this,c);this._latlng=a;this._mRadius=b},options:{fill:!0},setLatLng:function(a){this._latlng=a;this._redraw();return this},setRadius:function(a){this._mRadius=a;this._redraw();return this},projectLatlngs:function(){var a=this._map.options.scale(this._map._zoom);this._point=this._map.latLngToLayerPoint(this._latlng);this._radius=this._mRadius/40075017*a},getPathString:function(){var a=this._point,b=this._radius;return L.Path.SVG?
+"M"+a.x+","+(a.y-b)+"A"+b+","+b+",0,1,1,"+(a.x-0.1)+","+(a.y-b)+" z":(a._round(),b=Math.round(b),"AL "+a.x+","+a.y+" "+b+","+b+" 0,23592600")}});L.CircleMarker=L.Circle.extend({options:{radius:10,weight:2},initialize:function(a,b){L.Circle.prototype.initialize.call(this,a,null,b);this._radius=this.options.radius},projectLatlngs:function(){this._point=this._map.latLngToLayerPoint(this._latlng)},setRadius:function(a){this._radius=a;this._redraw();return this}});L.GeoJSON=L.LayerGroup.extend({includes:L.Mixin.Events,initialize:function(a,b){L.Util.setOptions(this,b);this._geojson=a;this._layers={};a&&this.addGeoJSON(a)},addGeoJSON:function(a){if(a.features)for(var b=0,c=a.features.length;b<c;b++)this.addGeoJSON(a.features[b]);else b=a.type=="Feature"?a.geometry:a,c=L.GeoJSON.geometryToLayer(b,this.options.pointToLayer),this.fire("featureparse",{layer:c,properties:a.properties,geometryType:b.type,bbox:a.bbox,id:a.id}),this.addLayer(c)}});
+L.Util.extend(L.GeoJSON,{geometryToLayer:function(a,b){var c=a.coordinates,d,e,f,g=[];switch(a.type){case "Point":return d=this.coordsToLatLng(c),b?b(d):new L.Marker(d);case "MultiPoint":e=0;for(f=c.length;e<f;e++)d=this.coordsToLatLng(c[e]),d=b?b(d):new L.Marker(d),g.push(d);return new L.FeatureGroup(g);case "LineString":return c=this.coordsToLatLngs(c),new L.Polyline(c);case "Polygon":return c=this.coordsToLatLngs(c,1),new L.Polygon(c);case "MultiLineString":return c=this.coordsToLatLngs(c,1),new L.MultiPolyline(c);
+case "MultiPolygon":return c=this.coordsToLatLngs(c,2),new L.MultiPolygon(c);case "GeometryCollection":e=0;for(f=a.geometries.length;e<f;e++)d=this.geometryToLayer(a.geometries[e]),g.push(d);return new L.FeatureGroup(g);default:throw Error("Invalid GeoJSON object.");}},coordsToLatLng:function(a,b){var c=parseFloat(a[b?0:1]),d=parseFloat(a[b?1:0]);return new L.LatLng(c,d)},coordsToLatLngs:function(a,b,c){var d,e=[],f,g=a.length;for(f=0;f<g;f++)d=b?this.coordsToLatLngs(a[f],b-1,c):this.coordsToLatLng(a[f],
+c),e.push(d);return e}});L.Handler=L.Class.extend({initialize:function(a){this._map=a},enabled:function(){return!!this._enabled}});L.Handler.MapDrag=L.Handler.extend({enable:function(){if(!this._enabled){if(!this._draggable)this._draggable=new L.Draggable(this._map._mapPane,this._map._container),this._draggable.on("dragstart",this._onDragStart,this),this._draggable.on("drag",this._onDrag,this),this._draggable.on("dragend",this._onDragEnd,this);this._draggable.enable();this._enabled=!0}},disable:function(){if(this._enabled)this._draggable.disable(),this._enabled=!1},moved:function(){return this._draggable._moved},_onDragStart:function(){this._map.fire("movestart");
+this._map.fire("dragstart")},_onDrag:function(){this._map.fire("move");this._map.fire("drag")},_onDragEnd:function(){this._map.fire("moveend");this._map.fire("dragend")}});L.Handler.TouchZoom=L.Handler.extend({enable:function(){if(L.Browser.mobileWebkit&&!this._enabled)L.DomEvent.addListener(this._map._container,"touchstart",this._onTouchStart,this),this._enabled=!0},disable:function(){if(this._enabled)L.DomEvent.removeListener(this._map._container,"touchstart",this._onTouchStart,this),this._enabled=!1},_onTouchStart:function(a){if(a.touches&&!(a.touches.length!=2||this._map._animatingZoom)){var b=this._map.mouseEventToLayerPoint(a.touches[0]),c=this._map.mouseEventToLayerPoint(a.touches[1]),
+d=this._map.containerPointToLayerPoint(this._map.getSize().divideBy(2));this._startCenter=b.add(c).divideBy(2,!0);this._startDist=b.distanceTo(c);this._moved=!1;this._zooming=!0;this._centerOffset=d.subtract(this._startCenter);L.DomEvent.addListener(document,"touchmove",this._onTouchMove,this);L.DomEvent.addListener(document,"touchend",this._onTouchEnd,this);L.DomEvent.preventDefault(a)}},_onTouchMove:function(a){if(a.touches&&a.touches.length==2){if(!this._moved)this._map._mapPane.className+=" leaflet-zoom-anim",
+this._map._prepareTileBg(),this._moved=!0;var b=this._map.mouseEventToLayerPoint(a.touches[0]),c=this._map.mouseEventToLayerPoint(a.touches[1]);this._scale=b.distanceTo(c)/this._startDist;this._delta=b.add(c).divideBy(2,!0).subtract(this._startCenter);this._map._tileBg.style.webkitTransform=[L.DomUtil.getTranslateString(this._delta),L.DomUtil.getScaleString(this._scale,this._startCenter)].join(" ");L.DomEvent.preventDefault(a)}},_onTouchEnd:function(){if(this._moved&&this._zooming){this._zooming=
+!1;var a=this._map.getZoom(),b=Math.log(this._scale)/Math.LN2,b=this._map._limitZoom(a+(b>0?Math.ceil(b):Math.floor(b))),a=b-a,c=this._centerOffset.subtract(this._delta).divideBy(this._scale),d=this._map.unproject(this._map.getPixelOrigin().add(this._startCenter).add(c));L.DomEvent.removeListener(document,"touchmove",this._onTouchMove);L.DomEvent.removeListener(document,"touchend",this._onTouchEnd);this._map._runAnimation(d,b,Math.pow(2,a)/this._scale,this._startCenter.add(c))}}});L.Handler.ScrollWheelZoom=L.Handler.extend({enable:function(){if(!this._enabled)L.DomEvent.addListener(this._map._container,"mousewheel",this._onWheelScroll,this),this._delta=0,this._enabled=!0},disable:function(){if(this._enabled)L.DomEvent.removeListener(this._map._container,"mousewheel",this._onWheelScroll),this._enabled=!1},_onWheelScroll:function(a){this._delta+=L.DomEvent.getWheelDelta(a);this._lastMousePos=this._map.mouseEventToContainerPoint(a);clearTimeout(this._timer);this._timer=setTimeout(L.Util.bind(this._performZoom,
+this),50);L.DomEvent.preventDefault(a)},_performZoom:function(){var a=Math.round(this._delta);this._delta=0;if(a){var b=this._getCenterForScrollWheelZoom(this._lastMousePos,a),a=this._map.getZoom()+a;this._map._limitZoom(a)!=this._map._zoom&&this._map.setView(b,a)}},_getCenterForScrollWheelZoom:function(a,b){var c=this._map.getPixelBounds().getCenter(),d=this._map.getSize().divideBy(2),d=a.subtract(d).multiplyBy(1-Math.pow(2,-b));return this._map.unproject(c.add(d),this._map._zoom,!0)}});L.Handler.DoubleClickZoom=L.Handler.extend({enable:function(){if(!this._enabled)this._map.on("dblclick",this._onDoubleClick,this._map),this._enabled=!0},disable:function(){if(this._enabled)this._map.off("dblclick",this._onDoubleClick,this._map),this._enabled=!1},_onDoubleClick:function(a){this.setView(a.latlng,this._zoom+1)}});L.Handler.ShiftDragZoom=L.Handler.extend({initialize:function(a){this._map=a;this._container=a._container;this._pane=a._panes.overlayPane},enable:function(){if(!this._enabled)L.DomEvent.addListener(this._container,"mousedown",this._onMouseDown,this),this._enabled=!0},disable:function(){if(this._enabled)L.DomEvent.removeListener(this._container,"mousedown",this._onMouseDown),this._enabled=!1},_onMouseDown:function(a){if(!a.shiftKey||a.which!=1&&a.button!=1)return!1;L.DomUtil.disableTextSelection();
+this._startLayerPoint=this._map.mouseEventToLayerPoint(a);this._box=L.DomUtil.create("div","leaflet-zoom-box",this._pane);L.DomUtil.setPosition(this._box,this._startLayerPoint);this._container.style.cursor="crosshair";L.DomEvent.addListener(document,"mousemove",this._onMouseMove,this);L.DomEvent.addListener(document,"mouseup",this._onMouseUp,this);L.DomEvent.preventDefault(a)},_onMouseMove:function(a){var b=this._map.mouseEventToLayerPoint(a),a=b.x-this._startLayerPoint.x,c=b.y-this._startLayerPoint.y,
+b=new L.Point(Math.min(b.x,this._startLayerPoint.x),Math.min(b.y,this._startLayerPoint.y));L.DomUtil.setPosition(this._box,b);this._box.style.width=Math.abs(a)-4+"px";this._box.style.height=Math.abs(c)-4+"px"},_onMouseUp:function(a){this._pane.removeChild(this._box);this._container.style.cursor="";L.DomUtil.enableTextSelection();L.DomEvent.removeListener(document,"mousemove",this._onMouseMove);L.DomEvent.removeListener(document,"mouseup",this._onMouseUp);a=this._map.mouseEventToLayerPoint(a);this._map.fitBounds(new L.LatLngBounds(this._map.layerPointToLatLng(this._startLayerPoint),
+this._map.layerPointToLatLng(a)))}});L.Handler.MarkerDrag=L.Handler.extend({initialize:function(a){this._marker=a},enable:function(){if(!this._enabled){if(!this._draggable)this._draggable=new L.Draggable(this._marker._icon,this._marker._icon),this._draggable.on("dragstart",this._onDragStart,this),this._draggable.on("drag",this._onDrag,this),this._draggable.on("dragend",this._onDragEnd,this);this._draggable.enable();this._enabled=!0}},disable:function(){if(this._enabled)this._draggable.disable(),this._enabled=!1},moved:function(){return this._draggable&&
+this._draggable._moved},_onDragStart:function(){this._marker.closePopup();this._marker.fire("movestart");this._marker.fire("dragstart")},_onDrag:function(){var a=L.DomUtil.getPosition(this._marker._icon);L.DomUtil.setPosition(this._marker._shadow,a);this._marker._latlng=this._marker._map.layerPointToLatLng(a);this._marker.fire("move");this._marker.fire("drag")},_onDragEnd:function(){this._marker.fire("moveend");this._marker.fire("dragend")}});L.Control={};L.Control.Position={TOP_LEFT:"topLeft",TOP_RIGHT:"topRight",BOTTOM_LEFT:"bottomLeft",BOTTOM_RIGHT:"bottomRight"};L.Control.Zoom=L.Class.extend({onAdd:function(a){this._map=a;this._container=L.DomUtil.create("div","leaflet-control-zoom");this._zoomInButton=this._createButton("Zoom in","leaflet-control-zoom-in",this._map.zoomIn,this._map);this._zoomOutButton=this._createButton("Zoom out","leaflet-control-zoom-out",this._map.zoomOut,this._map);this._container.appendChild(this._zoomInButton);this._container.appendChild(this._zoomOutButton)},getContainer:function(){return this._container},getPosition:function(){return L.Control.Position.TOP_LEFT},
+_createButton:function(a,b,c,d){var e=document.createElement("a");e.href="#";e.title=a;e.className=b;L.DomEvent.disableClickPropagation(e);L.DomEvent.addListener(e,"click",L.DomEvent.preventDefault);L.DomEvent.addListener(e,"click",c,d);return e}});L.Control.Attribution=L.Class.extend({onAdd:function(a){this._container=L.DomUtil.create("div","leaflet-control-attribution");this._map=a;this._prefix='Powered by <a href="http://leaflet.cloudmade.com">Leaflet</a>';this._attributions={};this._update()},getPosition:function(){return L.Control.Position.BOTTOM_RIGHT},getContainer:function(){return this._container},setPrefix:function(a){this._prefix=a},addAttribution:function(a){a&&(this._attributions[a]=!0,this._update())},removeAttribution:function(a){a&&
+(delete this._attributions[a],this._update())},_update:function(){if(this._map){var a=[],b;for(b in this._attributions)this._attributions.hasOwnProperty(b)&&a.push(b);b=[];this._prefix&&b.push(this._prefix);a.length&&b.push(a.join(", "));this._container.innerHTML=b.join(" — ")}}});L.Map=L.Class.extend({includes:L.Mixin.Events,options:{crs:L.CRS.EPSG3857||L.CRS.EPSG4326,scale:function(a){return 256*(1<<a)},center:null,zoom:null,layers:[],dragging:!0,touchZoom:L.Browser.mobileWebkit&&!L.Browser.android,scrollWheelZoom:!L.Browser.mobileWebkit,doubleClickZoom:!0,shiftDragZoom:!0,zoomControl:!0,attributionControl:!0,fadeAnimation:L.DomUtil.TRANSITION&&!L.Browser.android,zoomAnimation:L.DomUtil.TRANSITION&&!L.Browser.android&&!L.Browser.mobileOpera,trackResize:!0,closePopupOnClick:!0},
+initialize:function(a,b){L.Util.setOptions(this,b);this._container=L.DomUtil.get(a);this._initLayout();L.DomEvent&&(this._initEvents(),L.Handler&&this._initInteraction(),L.Control&&this._initControls());var c=this.options.center,d=this.options.zoom;c!==null&&d!==null&&this.setView(c,d,!0);c=this.options.layers;c=c instanceof Array?c:[c];this._tileLayersNum=0;this._initLayers(c)},setView:function(a,b){this._resetView(a,this._limitZoom(b));return this},setZoom:function(a){return this.setView(this.getCenter(),
+a)},zoomIn:function(){return this.setZoom(this._zoom+1)},zoomOut:function(){return this.setZoom(this._zoom-1)},fitBounds:function(a){var b=this.getBoundsZoom(a);return this.setView(a.getCenter(),b)},fitWorld:function(){var a=new L.LatLng(-60,-170),b=new L.LatLng(85,179);return this.fitBounds(new L.LatLngBounds(a,b))},panTo:function(a){return this.setView(a,this._zoom)},panBy:function(a){this.fire("movestart");this._rawPanBy(a);this.fire("move");this.fire("moveend");return this},addLayer:function(a){var b=
+L.Util.stamp(a);if(this._layers[b])return this;this._layers[b]=a;if(a.options&&!isNaN(a.options.maxZoom))this._layersMaxZoom=Math.max(this._layersMaxZoom||0,a.options.maxZoom);if(a.options&&!isNaN(a.options.minZoom))this._layersMinZoom=Math.min(this._layersMinZoom||Infinity,a.options.minZoom);this.options.zoomAnimation&&L.TileLayer&&a instanceof L.TileLayer&&(this._tileLayersNum++,a.on("load",this._onTileLayerLoad,this));this.attributionControl&&a.getAttribution&&this.attributionControl.addAttribution(a.getAttribution());
+b=function(){a.onAdd(this);this.fire("layeradd",{layer:a})};if(this._loaded)b.call(this);else this.on("load",b,this);return this},removeLayer:function(a){var b=L.Util.stamp(a);this._layers[b]&&(a.onRemove(this),delete this._layers[b],this.options.zoomAnimation&&L.TileLayer&&a instanceof L.TileLayer&&(this._tileLayersNum--,a.off("load",this._onTileLayerLoad,this)),this.attributionControl&&a.getAttribution&&this.attributionControl.removeAttribution(a.getAttribution()),this.fire("layerremove",{layer:a}));
+return this},invalidateSize:function(){this._sizeChanged=!0;this.fire("move");clearTimeout(this._sizeTimer);this._sizeTimer=setTimeout(L.Util.bind(function(){this.fire("moveend")},this),200);return this},getCenter:function(a){var b=this.getSize().divideBy(2);return this.unproject(this._getTopLeftPoint().add(b),this._zoom,a)},getZoom:function(){return this._zoom},getBounds:function(){var a=this.getPixelBounds(),b=this.unproject(new L.Point(a.min.x,a.max.y)),a=this.unproject(new L.Point(a.max.x,a.min.y));
+return new L.LatLngBounds(b,a)},getMinZoom:function(){return isNaN(this.options.minZoom)?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return isNaN(this.options.maxZoom)?this._layersMaxZoom||Infinity:this.options.maxZoom},getBoundsZoom:function(a){var b=this.getSize(),c=this.getMinZoom(),d=this.getMaxZoom(),e=a.getNorthEast(),a=a.getSouthWest(),f,g;do c++,f=this.project(e,c),g=this.project(a,c),f=new L.Point(f.x-g.x,g.y-f.y);while(f.x<=b.x&&f.y<=b.y&&c<=d);return c-1},getSize:function(){if(!this._size||
+this._sizeChanged)this._size=new L.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1;return this._size},getPixelBounds:function(){var a=this._getTopLeftPoint(),b=this.getSize();return new L.Bounds(a,a.add(b))},getPixelOrigin:function(){return this._initialTopLeftPoint},getPanes:function(){return this._panes},mouseEventToContainerPoint:function(a){return L.DomEvent.getMousePosition(a,this._container)},mouseEventToLayerPoint:function(a){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(a))},
+mouseEventToLatLng:function(a){return this.layerPointToLatLng(this.mouseEventToLayerPoint(a))},containerPointToLayerPoint:function(a){return a.subtract(L.DomUtil.getPosition(this._mapPane))},layerPointToContainerPoint:function(a){return a.add(L.DomUtil.getPosition(this._mapPane))},layerPointToLatLng:function(a){return this.unproject(a.add(this._initialTopLeftPoint))},latLngToLayerPoint:function(a){return this.project(a)._subtract(this._initialTopLeftPoint)},project:function(a,b){b=typeof b=="undefined"?
+this._zoom:b;return this.options.crs.latLngToPoint(a,this.options.scale(b))},unproject:function(a,b,c){b=typeof b=="undefined"?this._zoom:b;return this.options.crs.pointToLatLng(a,this.options.scale(b),c)},_initLayout:function(){var a=this._container;a.className+=" leaflet-container";this.options.fadeAnimation&&(a.className+=" leaflet-fade-anim");var b=L.DomUtil.getStyle(a,"position");if(b!="absolute"&&b!="relative")a.style.position="relative";this._initPanes();this._initControlPos&&this._initControlPos()},
+_initPanes:function(){var a=this._panes={};this._mapPane=a.mapPane=this._createPane("leaflet-map-pane",this._container);this._tilePane=a.tilePane=this._createPane("leaflet-tile-pane",this._mapPane);this._objectsPane=a.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane);a.shadowPane=this._createPane("leaflet-shadow-pane");a.overlayPane=this._createPane("leaflet-overlay-pane");a.markerPane=this._createPane("leaflet-marker-pane");a.popupPane=this._createPane("leaflet-popup-pane")},_createPane:function(a,
+b){return L.DomUtil.create("div",a,b||this._objectsPane)},_resetView:function(a,b,c){var d=this._zoom!=b;this.fire("movestart");this._zoom=b;this._initialTopLeftPoint=this._getNewTopLeftPoint(a);c?this._initialTopLeftPoint._add(L.DomUtil.getPosition(this._mapPane)):L.DomUtil.setPosition(this._mapPane,new L.Point(0,0));this._tileLayersToLoad=this._tileLayersNum;this.fire("viewreset");this.fire("move");d&&this.fire("zoomend");this.fire("moveend");if(!this._loaded)this._loaded=!0,this.fire("load")},
+_initLayers:function(a){this._layers={};for(var b=0,c=a.length;b<c;b++)this.addLayer(a[b])},_initControls:function(){this.options.zoomControl&&this.addControl(new L.Control.Zoom);if(this.options.attributionControl)this.attributionControl=new L.Control.Attribution,this.addControl(this.attributionControl)},_rawPanBy:function(a){var b=L.DomUtil.getPosition(this._mapPane);L.DomUtil.setPosition(this._mapPane,b.subtract(a))},_initEvents:function(){L.DomEvent.addListener(this._container,"click",this._onMouseClick,
+this);for(var a=["dblclick","mousedown","mouseenter","mouseleave","mousemove"],b=0;b<a.length;b++)L.DomEvent.addListener(this._container,a[b],this._fireMouseEvent,this);this.options.trackResize&&L.DomEvent.addListener(window,"resize",this.invalidateSize,this)},_onMouseClick:function(a){if(!this.dragging||!this.dragging.moved())this.fire("pre"+a.type),this._fireMouseEvent(a)},_fireMouseEvent:function(a){var b=a.type,b=b=="mouseenter"?"mouseover":b=="mouseleave"?"mouseout":b;this.hasEventListeners(b)&&
+this.fire(b,{latlng:this.mouseEventToLatLng(a),layerPoint:this.mouseEventToLayerPoint(a)})},_initInteraction:function(){var a={dragging:L.Handler.MapDrag,touchZoom:L.Handler.TouchZoom,doubleClickZoom:L.Handler.DoubleClickZoom,scrollWheelZoom:L.Handler.ScrollWheelZoom,shiftDragZoom:L.Handler.ShiftDragZoom},b;for(b in a)a.hasOwnProperty(b)&&a[b]&&(this[b]=new a[b](this),this.options[b]&&this[b].enable())},_onTileLayerLoad:function(){this._tileLayersToLoad--;if(this._tileLayersNum&&!this._tileLayersToLoad&&
+this._tileBg)clearTimeout(this._clearTileBgTimer),this._clearTileBgTimer=setTimeout(L.Util.bind(this._clearTileBg,this),500)},_getTopLeftPoint:function(){if(!this._loaded)throw Error("Set map center and zoom first.");return this._initialTopLeftPoint.subtract(L.DomUtil.getPosition(this._mapPane))},_getNewTopLeftPoint:function(a){var b=this.getSize().divideBy(2);return this.project(a).subtract(b).round()},_limitZoom:function(a){var b=this.getMinZoom(),c=this.getMaxZoom();return Math.max(b,Math.min(c,
+a))}});L.Map.include({locate:function(a){var b={timeout:1E4};L.Util.extend(b,a);navigator.geolocation?navigator.geolocation.getCurrentPosition(L.Util.bind(this._handleGeolocationResponse,this),L.Util.bind(this._handleGeolocationError,this),b):this.fire("locationerror",{code:0,message:"Geolocation not supported."});return this},locateAndSetView:function(a,b){this._setViewOnLocate=!0;this._maxLocateZoom=a||Infinity;return this.locate(b)},_handleGeolocationError:function(a){var a=a.code,b=a==1?"permission denied":
+a==2?"position unavailable":"timeout";if(this._setViewOnLocate)this.fitWorld(),this._setViewOnLocate=!1;this.fire("locationerror",{code:a,message:"Geolocation error: "+b+"."})},_handleGeolocationResponse:function(a){var b=180*a.coords.accuracy/4E7,c=b*2,d=a.coords.latitude,e=a.coords.longitude,f=new L.LatLng(d-b,e-c),b=new L.LatLng(d+b,e+c),f=new L.LatLngBounds(f,b);if(this._setViewOnLocate)b=Math.min(this.getBoundsZoom(f),this._maxLocateZoom),this.setView(f.getCenter(),b),this._setViewOnLocate=!1;
+this.fire("locationfound",{latlng:new L.LatLng(d,e),bounds:f,accuracy:a.coords.accuracy})}});L.Map.include({openPopup:function(a){this.closePopup();this._popup=a;return this.addLayer(a)},closePopup:function(){this._popup&&this.removeLayer(this._popup);return this}});L.Map.include(!L.Transition||!L.Transition.implemented()?{}:{setView:function(a,b,c){var b=this._limitZoom(b),d=this._zoom!=b;if(this._loaded&&!c&&this._layers&&(c=this._getNewTopLeftPoint(a).subtract(this._getTopLeftPoint()),d?this._zoomToIfCenterInView&&this._zoomToIfCenterInView(a,b,c):this._panByIfClose(c)))return this;this._resetView(a,b);return this},panBy:function(a){if(!this._panTransition)this._panTransition=new L.Transition(this._mapPane,{duration:0.3}),this._panTransition.on("step",this._onPanTransitionStep,
+this),this._panTransition.on("end",this._onPanTransitionEnd,this);this.fire(this,"movestart");this._panTransition.run({position:L.DomUtil.getPosition(this._mapPane).subtract(a)});return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){this.fire("moveend")},_panByIfClose:function(a){if(this._offsetIsWithinView(a))return this.panBy(a),!0;return!1},_offsetIsWithinView:function(a,b){var c=b||1,d=this.getSize();return Math.abs(a.x)<=d.x*c&&Math.abs(a.y)<=d.y*c}});L.Map.include(!L.DomUtil.TRANSITION?{}:{_zoomToIfCenterInView:function(a,b,c){if(this._animatingZoom)return!0;if(!this.options.zoomAnimation)return!1;var d=Math.pow(2,b-this._zoom),c=c.divideBy(1-1/d);if(!this._offsetIsWithinView(c,1))return!1;this._mapPane.className+=" leaflet-zoom-anim";c=this.containerPointToLayerPoint(this.getSize().divideBy(2)).add(c);this._prepareTileBg();this._runAnimation(a,b,d,c);return!0},_runAnimation:function(a,b,c,d){this._animatingZoom=!0;this._animateToCenter=a;this._animateToZoom=
+b;a=L.DomUtil.TRANSFORM;if(L.Browser.gecko||window.opera)this._tileBg.style[a]+=" translate(0,0)";L.Browser.android?(this._tileBg.style[a+"Origin"]=d.x+"px "+d.y+"px",c="scale("+c+")"):c=L.DomUtil.getScaleString(c,d);L.Util.falseFn(this._tileBg.offsetWidth);d={};d[a]=this._tileBg.style[a]+" "+c;this._tileBg.transition.run(d)},_prepareTileBg:function(){if(!this._tileBg)this._tileBg=this._createPane("leaflet-tile-pane",this._mapPane),this._tileBg.style.zIndex=1;var a=this._tilePane,b=this._tileBg;b.style[L.DomUtil.TRANSFORM]=
+"";b.style.visibility="hidden";b.empty=!0;a.empty=!1;this._tilePane=this._panes.tilePane=b;this._tileBg=a;if(!this._tileBg.transition)this._tileBg.transition=new L.Transition(this._tileBg,{duration:0.3,easing:"cubic-bezier(0.25,0.1,0.25,0.75)"}),this._tileBg.transition.on("end",this._onZoomTransitionEnd,this);this._stopLoadingBgTiles()},_stopLoadingBgTiles:function(){for(var a=[].slice.call(this._tileBg.getElementsByTagName("img")),b=0,c=a.length;b<c;b++)if(!a[b].complete)a[b].src="",a[b].parentNode.removeChild(a[b])},
+_onZoomTransitionEnd:function(){this._restoreTileFront();L.Util.falseFn(this._tileBg.offsetWidth);this._resetView(this._animateToCenter,this._animateToZoom,!0);this._mapPane.className=this._mapPane.className.replace(" leaflet-zoom-anim","");this._animatingZoom=!1},_restoreTileFront:function(){this._tilePane.innerHTML="";this._tilePane.style.visibility="";this._tilePane.style.zIndex=2;this._tileBg.style.zIndex=1},_clearTileBg:function(){if(!this._animatingZoom&&!this.touchZoom._zooming)this._tileBg.innerHTML=
+""}});L.Map.include({addControl:function(a){a.onAdd(this);var b=a.getPosition(),c=this._controlCorners[b],a=a.getContainer();L.DomUtil.addClass(a,"leaflet-control");b.indexOf("bottom")!=-1?c.insertBefore(a,c.firstChild):c.appendChild(a);return this},removeControl:function(a){var b=this._controlCorners[a.getPosition()],c=a.getContainer();b.removeChild(c);if(a.onRemove)a.onRemove(this);return this},_initControlPos:function(){var a=this._controlCorners={},b=L.DomUtil.create("div","leaflet-control-container",
+this._container);L.Browser.mobileWebkit&&(b.className+=" leaflet-big-buttons");a.topLeft=L.DomUtil.create("div","leaflet-top leaflet-left",b);a.topRight=L.DomUtil.create("div","leaflet-top leaflet-right",b);a.bottomLeft=L.DomUtil.create("div","leaflet-bottom leaflet-left",b);a.bottomRight=L.DomUtil.create("div","leaflet-bottom leaflet-right",b)}});
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/html/map_index.html
--- a/yt/visualization/mapserver/html/map_index.html
+++ b/yt/visualization/mapserver/html/map_index.html
@@ -2,8 +2,8 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><!-- Leaflet JavaScript -->
-<script type="text/javascript" src="/reason-js/leaflet/leaflet.js"></script>
-<link rel="stylesheet" href="/reason-js/leaflet/leaflet.css" />
+<script type="text/javascript" src="/leaflet/leaflet.js"></script>
+<link rel="stylesheet" href="/leaflet/leaflet.css" /><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script><script type="text/javascript">
$(document).ready(function() {
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/pannable_map.py
--- a/yt/visualization/mapserver/pannable_map.py
+++ b/yt/visualization/mapserver/pannable_map.py
@@ -17,6 +17,8 @@
import zipfile
import sys
+from functools import wraps
+
from yt.visualization.image_writer import apply_colormap
from yt.visualization.fixed_resolution import FixedResolutionBuffer
from yt.utilities.lib.misc_utilities import get_color_bounds
@@ -24,7 +26,6 @@
import yt.extern.bottle as bottle
-from yt.funcs import *
local_dir = os.path.dirname(__file__)
def exc_writeout(f):
@@ -34,34 +35,25 @@
try:
rv = f(*args, **kwargs)
return rv
- except Exception as e:
+ except Exception:
traceback.print_exc(None, open("temp.exc", "w"))
raise
return func
class PannableMapServer(object):
_widget_name = "pannable_map"
- reasonjs_file = None
def __init__(self, data, field, route_prefix = ""):
self.data = data
self.ds = data.ds
self.field = field
-
+
bottle.route("%s/map/:L/:x/:y.png" % route_prefix)(self.map)
bottle.route("%s/" % route_prefix)(self.index)
bottle.route("%s/index.html" % route_prefix)(self.index)
# This is a double-check, since we do not always mandate this for
# slices:
self.data[self.field] = self.data[self.field].astype("float64")
- if route_prefix == "":
- # We assume this means we're running standalone
- from .utils import get_reasonjs_path
- try:
- reasonjs_path = get_reasonjs_path()
- except IOError:
- sys.exit(1)
- self.reasonjs_file = zipfile.ZipFile(reasonjs_path, 'r')
- bottle.route("/reason-js/:path#.+#", "GET")(self.static)
+ bottle.route(":path#.+#", "GET")(self.static)
def map(self, L, x, y):
dd = 1.0 / (2.0**(int(L)))
@@ -96,17 +88,11 @@
root=os.path.join(local_dir, "html"))
def static(self, path):
- if self.reasonjs_file is None: raise RuntimeError
- pp = os.path.join("reason-js", path)
- try:
- f = self.reasonjs_file.open(pp)
- except KeyError:
- bottle.response.status = 404
- return
if path[-4:].lower() in (".png", ".gif", ".jpg"):
bottle.response.headers['Content-Type'] = "image/%s" % (path[-3:].lower())
elif path[-4:].lower() == ".css":
bottle.response.headers['Content-Type'] = "text/css"
elif path[-3:].lower() == ".js":
bottle.response.headers['Content-Type'] = "text/javascript"
- return f.read()
+ full_path = os.path.join(os.path.join(local_dir, 'html'), path)
+ return open(full_path, 'r').read()
diff -r 33dadd43445dafcebb5ceb688577c628e2918667 -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 yt/visualization/mapserver/utils.py
--- a/yt/visualization/mapserver/utils.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""
-Utilities for Reason
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from .bottle_mods import PayloadHandler
-import base64
-import types
-import os
-
-def load_script(filename):
- contents = open(filename).read()
- payload_handler = PayloadHandler()
- payload_handler.add_payload(
- {'type': 'script',
- 'value': contents}
- )
- return
-
-def deliver_image(im):
- if hasattr(im, 'read'):
- img_data = base64.b64encode(im.read())
- elif isinstance(im, str) and \
- im.endswith(".png"):
- img_data = base64.b64encode(open(im).read())
- elif isinstance(im, str):
- img_data = im
- else:
- raise RuntimeError
- ph = PayloadHandler()
- payload = {'type':'cell',
- 'output': '',
- 'input': '',
- 'raw_input': '',
- 'result_id': None,
- 'image_data':img_data}
- ph.add_payload(payload)
-
-def get_list_of_datasets():
- # Note that this instantiates the index. This can be a costly
- # event. However, we're going to assume that it's okay, if you have
- # decided to load up the dataset.
- from yt.data_objects.static_output import _cached_datasets
- rv = []
- for fn, ds in sorted(_cached_datasets.items()):
- objs = []
- ds_varname = "_cached_datasets['%s']" % (fn)
- field_list = []
- if ds._instantiated_index is not None:
- field_list = list(set(ds.field_list + ds.derived_field_list))
- field_list = [dict(text = f) for f in sorted(field_list)]
- for i,obj in enumerate(ds.h.objects):
- try:
- name = str(obj)
- except ReferenceError:
- continue
- objs.append(dict(name=name, type=obj._type_name,
- filename = '', field_list = [],
- varname = "%s.h.objects[%s]" % (ds_varname, i)))
- rv.append( dict(name = str(ds), children = objs, filename=fn,
- type = "dataset",
- varname = ds_varname, field_list = field_list) )
- return rv
-
-def get_reasonjs_path():
- fn = "reason-js-20120623.zip"
- if "YT_DEST" not in os.environ:
- print()
- print("*** You must set the environment variable YT_DEST ***")
- print("*** to point to the installation location! ***")
- print()
- raise IOError
- reasonjs_path = os.path.join(os.environ["YT_DEST"], "src", fn)
- if not os.path.isfile(reasonjs_path):
- print()
- print("*** You are missing the Reason support files. You ***")
- print("*** You can get these by either rerunning the ***")
- print("*** install script installing, or downloading ***")
- print("*** them manually. ***")
- print("*** ***")
- print("*** FOR INSTANCE: ***")
- print()
- print("cd %s" % os.path.join(os.environ["YT_DEST"], "src"))
- print("wget http://yt-project.org/dependencies/reason-js-20120623.zip")
- print()
- raise IOError
- return reasonjs_path
https://bitbucket.org/yt_analysis/yt/commits/2198b1fc5e69/
Changeset: 2198b1fc5e69
Branch: yt
User: ngoldbaum
Date: 2015-08-24 19:20:38+00:00
Summary: Removing unused imports
Affected #: 1 file
diff -r d7723c5f299e3fc8ac6b325a3e4771254b86d525 -r 2198b1fc5e693c591ee2abfc54638adff1748510 yt/visualization/mapserver/pannable_map.py
--- a/yt/visualization/mapserver/pannable_map.py
+++ b/yt/visualization/mapserver/pannable_map.py
@@ -14,8 +14,6 @@
#-----------------------------------------------------------------------------
import os
import numpy as np
-import zipfile
-import sys
from functools import wraps
https://bitbucket.org/yt_analysis/yt/commits/b11b40f33cad/
Changeset: b11b40f33cad
Branch: yt
User: ngoldbaum
Date: 2015-08-24 19:22:47+00:00
Summary: Removing reason from MANIFEST.in, adding mapserver html stuff
Affected #: 1 file
diff -r 2198b1fc5e693c591ee2abfc54638adff1748510 -r b11b40f33cad199f640f0a16a600a15e1ff2ad5e MANIFEST.in
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,5 @@
include distribute_setup.py README* CREDITS COPYING.txt CITATION requirements.txt optional-requirements.txt
-recursive-include yt/gui/reason/html *.html *.png *.ico *.js *.gif *.css
+recursive-include yt/visualization/mapserver/html *.html *.png *.ico *.js *.gif *.css
recursive-include yt *.py *.pyx *.pxd *.h README* *.txt LICENSE* *.cu
recursive-include doc *.rst *.txt *.py *.ipynb *.png *.jpg *.css *.inc *.html
recursive-include doc *.h *.c *.sh *.svgz *.pdf *.svg *.pyx
@@ -10,5 +10,4 @@
recursive-include yt/analysis_modules/halo_finding/rockstar *.py *.pyx
prune yt/frontends/_skeleton
prune tests
-graft yt/gui/reason/html/resources
exclude clean.sh .hgchurn
https://bitbucket.org/yt_analysis/yt/commits/ba543398053f/
Changeset: ba543398053f
Branch: yt
User: ngoldbaum
Date: 2015-08-24 19:25:08+00:00
Summary: Remove reason from the install script
Affected #: 1 file
diff -r b11b40f33cad199f640f0a16a600a15e1ff2ad5e -r ba543398053f6f013b3db3d83d216ced4e389f05 doc/install_script.sh
--- a/doc/install_script.sh
+++ b/doc/install_script.sh
@@ -644,7 +644,6 @@
echo '609cc82586fabecb25f25ecb410f2938e01d21cde85dd3f8824fe55c6edde9ecf3b7609195473d3fa05a16b9b121464f5414db1a0187103b78ea6edfa71684a7 Python-3.4.3.tgz' > Python-3.4.3.tgz.sha512
echo '276bd9c061ec9a27d478b33078a86f93164ee2da72210e12e2c9da71dcffeb64767e4460b93f257302b09328eda8655e93c4b9ae85e74472869afbeae35ca71e blas.tar.gz' > blas.tar.gz.sha512
echo '00ace5438cfa0c577e5f578d8a808613187eff5217c35164ffe044fbafdfec9e98f4192c02a7d67e01e5a5ccced630583ad1003c37697219b0f147343a3fdd12 bzip2-1.0.6.tar.gz' > bzip2-1.0.6.tar.gz.sha512
-echo 'a296dfcaef7e853e58eed4e24b37c4fa29cfc6ac688def048480f4bb384b9e37ca447faf96eec7b378fd764ba291713f03ac464581d62275e28eb2ec99110ab6 reason-js-20120623.zip' > reason-js-20120623.zip.sha512
echo '609a68a3675087e0cc95268574f31e104549daa48efe15a25a33b8e269a93b4bd160f4c3e8178dca9c950ef5ca514b039d6fd1b45db6af57f25342464d0429ce freetype-2.4.12.tar.gz' > freetype-2.4.12.tar.gz.sha512
echo '4a83f9ae1855a7fad90133b327d426201c8ccfd2e7fbe9f39b2d61a2eee2f3ebe2ea02cf80f3d4e1ad659f8e790c173df8cc99b87d0b7ce63d34aa88cfdc7939 h5py-2.5.0.tar.gz' > h5py-2.5.0.tar.gz.sha512
echo '4073fba510ccadaba41db0939f909613c9cb52ba8fb6c1062fc9118edc601394c75e102310be1af4077d07c9b327e6bbb1a6359939a7268dc140382d0c1e0199 hdf5-1.8.14.tar.gz' > hdf5-1.8.14.tar.gz.sha512
@@ -686,7 +685,6 @@
get_ytproject $IPYTHON.tar.gz
get_ytproject $H5PY.tar.gz
get_ytproject $CYTHON.tar.gz
-get_ytproject reason-js-20120623.zip
get_ytproject $NOSE.tar.gz
get_ytproject $PYTHON_HGLIB.tar.gz
get_ytproject $SYMPY.tar.gz
https://bitbucket.org/yt_analysis/yt/commits/161448bf729a/
Changeset: 161448bf729a
Branch: yt
User: ngoldbaum
Date: 2015-08-24 20:12:49+00:00
Summary: Remove gui subpackage from yt/setup.py
Affected #: 1 file
diff -r ba543398053f6f013b3db3d83d216ced4e389f05 -r 161448bf729a4c531f4bc4134d344947f2a8c2a3 yt/setup.py
--- a/yt/setup.py
+++ b/yt/setup.py
@@ -13,7 +13,6 @@
config.add_subpackage('extern')
config.add_subpackage('frontends')
config.add_subpackage('geometry')
- config.add_subpackage('gui')
config.add_subpackage('units')
config.add_subpackage('utilities')
config.add_subpackage('visualization')
https://bitbucket.org/yt_analysis/yt/commits/ece3516855c7/
Changeset: ece3516855c7
Branch: yt
User: ngoldbaum
Date: 2015-08-24 20:13:08+00:00
Summary: Ensure mapserver data is in source distribution and is installed
Affected #: 2 files
diff -r 161448bf729a4c531f4bc4134d344947f2a8c2a3 -r ece3516855c73dff4c17991b98ce162ea36dd432 MANIFEST.in
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,8 @@
include distribute_setup.py README* CREDITS COPYING.txt CITATION requirements.txt optional-requirements.txt
-recursive-include yt/visualization/mapserver/html *.html *.png *.ico *.js *.gif *.css
+include yt/visualization/mapserver/html/map_index.html
+include yt/visualization/mapserver/html/leaflet/*.css
+include yt/visualization/mapserver/html/leaflet/*.js
+include yt/visualization/mapserver/html/leaflet/images/*.png
recursive-include yt *.py *.pyx *.pxd *.h README* *.txt LICENSE* *.cu
recursive-include doc *.rst *.txt *.py *.ipynb *.png *.jpg *.css *.inc *.html
recursive-include doc *.h *.c *.sh *.svgz *.pdf *.svg *.pyx
diff -r 161448bf729a4c531f4bc4134d344947f2a8c2a3 -r ece3516855c73dff4c17991b98ce162ea36dd432 setup.py
--- a/setup.py
+++ b/setup.py
@@ -22,31 +22,19 @@
from distutils.core import Command
from distutils.spawn import find_executable
-REASON_FILES = []
-REASON_DIRS = [
+MAPSERVER_FILES = []
+MAPSERVER_DIRS = [
"",
- "resources",
- "resources/ux",
- "resources/images",
- "resources/css",
- "resources/css/images",
- "app",
- "app/store",
- "app/store/widgets",
- "app/view",
- "app/view/widgets",
- "app/model",
- "app/controller",
- "app/controller/widgets",
- "app/templates",
+ "leaflet",
+ "leaflet/images"
]
-for subdir in REASON_DIRS:
- dir_name = os.path.join("yt", "gui", "reason", "html", subdir)
+for subdir in MAPSERVER_DIRS:
+ dir_name = os.path.join("yt", "visualization", "mapserver", "html", subdir)
files = []
for ext in ["js", "html", "css", "png", "ico", "gif"]:
files += glob.glob("%s/*.%s" % (dir_name, ext))
- REASON_FILES.append((dir_name, files))
+ MAPSERVER_FILES.append((dir_name, files))
# Verify that we have Cython installed
REQ_CYTHON = '0.22'
@@ -218,7 +206,7 @@
license="BSD",
configuration=configuration,
zip_safe=False,
- data_files=REASON_FILES,
+ data_files=MAPSERVER_FILES,
cmdclass={'build_py': my_build_py, 'build_src': my_build_src},
)
return
https://bitbucket.org/yt_analysis/yt/commits/89dd8b5534fe/
Changeset: 89dd8b5534fe
Branch: yt
User: xarthisius
Date: 2015-08-27 16:16:11+00:00
Summary: Merged in ngoldbaum/yt (pull request #1719)
Remove reason, make mapserver work with regular source distributions
Affected #: 138 files
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db MANIFEST.in
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,8 @@
include distribute_setup.py README* CREDITS COPYING.txt CITATION requirements.txt optional-requirements.txt
-recursive-include yt/gui/reason/html *.html *.png *.ico *.js *.gif *.css
+include yt/visualization/mapserver/html/map_index.html
+include yt/visualization/mapserver/html/leaflet/*.css
+include yt/visualization/mapserver/html/leaflet/*.js
+include yt/visualization/mapserver/html/leaflet/images/*.png
recursive-include yt *.py *.pyx *.pxd *.h README* *.txt LICENSE* *.cu
recursive-include doc *.rst *.txt *.py *.ipynb *.png *.jpg *.css *.inc *.html
recursive-include doc *.h *.c *.sh *.svgz *.pdf *.svg *.pyx
@@ -10,5 +13,4 @@
recursive-include yt/analysis_modules/halo_finding/rockstar *.py *.pyx
prune yt/frontends/_skeleton
prune tests
-graft yt/gui/reason/html/resources
exclude clean.sh .hgchurn
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db doc/install_script.sh
--- a/doc/install_script.sh
+++ b/doc/install_script.sh
@@ -644,7 +644,6 @@
echo '609cc82586fabecb25f25ecb410f2938e01d21cde85dd3f8824fe55c6edde9ecf3b7609195473d3fa05a16b9b121464f5414db1a0187103b78ea6edfa71684a7 Python-3.4.3.tgz' > Python-3.4.3.tgz.sha512
echo '276bd9c061ec9a27d478b33078a86f93164ee2da72210e12e2c9da71dcffeb64767e4460b93f257302b09328eda8655e93c4b9ae85e74472869afbeae35ca71e blas.tar.gz' > blas.tar.gz.sha512
echo '00ace5438cfa0c577e5f578d8a808613187eff5217c35164ffe044fbafdfec9e98f4192c02a7d67e01e5a5ccced630583ad1003c37697219b0f147343a3fdd12 bzip2-1.0.6.tar.gz' > bzip2-1.0.6.tar.gz.sha512
-echo 'a296dfcaef7e853e58eed4e24b37c4fa29cfc6ac688def048480f4bb384b9e37ca447faf96eec7b378fd764ba291713f03ac464581d62275e28eb2ec99110ab6 reason-js-20120623.zip' > reason-js-20120623.zip.sha512
echo '609a68a3675087e0cc95268574f31e104549daa48efe15a25a33b8e269a93b4bd160f4c3e8178dca9c950ef5ca514b039d6fd1b45db6af57f25342464d0429ce freetype-2.4.12.tar.gz' > freetype-2.4.12.tar.gz.sha512
echo '4a83f9ae1855a7fad90133b327d426201c8ccfd2e7fbe9f39b2d61a2eee2f3ebe2ea02cf80f3d4e1ad659f8e790c173df8cc99b87d0b7ce63d34aa88cfdc7939 h5py-2.5.0.tar.gz' > h5py-2.5.0.tar.gz.sha512
echo '4073fba510ccadaba41db0939f909613c9cb52ba8fb6c1062fc9118edc601394c75e102310be1af4077d07c9b327e6bbb1a6359939a7268dc140382d0c1e0199 hdf5-1.8.14.tar.gz' > hdf5-1.8.14.tar.gz.sha512
@@ -686,7 +685,6 @@
get_ytproject $IPYTHON.tar.gz
get_ytproject $H5PY.tar.gz
get_ytproject $CYTHON.tar.gz
-get_ytproject reason-js-20120623.zip
get_ytproject $NOSE.tar.gz
get_ytproject $PYTHON_HGLIB.tar.gz
get_ytproject $SYMPY.tar.gz
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db scripts/pyro_queue.py
--- a/scripts/pyro_queue.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from yt.config import ytcfg;ytcfg["yt","__withinreason"]="True"
-import os
-import Pyro4
-import uuid
-
-from yt.mods import *
-from yt.utilities.parallel_tools.parallel_analysis_interface import \
- _get_comm
-from yt.gui.reason.pyro_queue import \
- PyroQueueRoot, \
- PyroQueueNonRoot
-
-comm = _get_comm(())
-my_rank = comm.comm.rank
-
-if my_rank == 0:
- my_q = PyroQueueRoot(comm)
- Pyro4.config.HMAC_KEY = uuid.uuid4().hex
- key_file = 'reason.key'
- fd = os.open(key_file, os.O_CREAT, 0600)
- os.close(fd)
- out_file = file(key_file, 'w')
- out_file.write("HMAC KEY: %s\n" % Pyro4.config.HMAC_KEY)
- out_file.close()
- mylog.info('See %s for HMAC key.', key_file)
- Pyro4.Daemon.serveSimple(
- {my_q: "yt.executor"},
- ns=False, verbose=True)
-else:
- my_q = PyroQueueNonRoot(comm)
- my_q.run()
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db setup.py
--- a/setup.py
+++ b/setup.py
@@ -22,31 +22,19 @@
from distutils.core import Command
from distutils.spawn import find_executable
-REASON_FILES = []
-REASON_DIRS = [
+MAPSERVER_FILES = []
+MAPSERVER_DIRS = [
"",
- "resources",
- "resources/ux",
- "resources/images",
- "resources/css",
- "resources/css/images",
- "app",
- "app/store",
- "app/store/widgets",
- "app/view",
- "app/view/widgets",
- "app/model",
- "app/controller",
- "app/controller/widgets",
- "app/templates",
+ "leaflet",
+ "leaflet/images"
]
-for subdir in REASON_DIRS:
- dir_name = os.path.join("yt", "gui", "reason", "html", subdir)
+for subdir in MAPSERVER_DIRS:
+ dir_name = os.path.join("yt", "visualization", "mapserver", "html", subdir)
files = []
for ext in ["js", "html", "css", "png", "ico", "gif"]:
files += glob.glob("%s/*.%s" % (dir_name, ext))
- REASON_FILES.append((dir_name, files))
+ MAPSERVER_FILES.append((dir_name, files))
# Verify that we have Cython installed
REQ_CYTHON = '0.22'
@@ -218,7 +206,7 @@
license="BSD",
configuration=configuration,
zip_safe=False,
- data_files=REASON_FILES,
+ data_files=MAPSERVER_FILES,
cmdclass={'build_py': my_build_py, 'build_src': my_build_src},
)
return
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/config.py
--- a/yt/config.py
+++ b/yt/config.py
@@ -30,7 +30,6 @@
loglevel = '20',
inline = 'False',
numthreads = '-1',
- __withinreason = 'False',
__withintesting = 'False',
__parallel = 'False',
__global_parallel_rank = '0',
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/funcs.py
--- a/yt/funcs.py
+++ b/yt/funcs.py
@@ -367,9 +367,6 @@
"__IPYTHON__" in dir(builtins) or \
ytcfg.getboolean("yt", "__withintesting"):
return DummyProgressBar()
- elif ytcfg.getboolean("yt", "__withinreason"):
- from yt.gui.reason.extdirect_repl import ExtProgressBar
- return ExtProgressBar(title, maxval)
elif ytcfg.getboolean("yt", "__parallel"):
return ParallelProgressBar(title, maxval)
widgets = [ title,
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/basic_repl.py
--- a/yt/gui/reason/basic_repl.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""
-A read-eval-print-loop. This code was released in the CherryPy project
-initially, but has been heavily modified and again re-released in compliance
-with the terms of its original license.
-
-
-
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import codeop
-import inspect
-import re
-import json
-import sys
-import traceback
-from yt.extern.six.moves import StringIO
-
-class ProgrammaticREPL(object):
- stopped = False
- debug = False
- def __init__(self, locals=None):
- self.executed_cell_texts = []
- self.locals = {}
- if locals:
- self.locals.update(locals)
- self.buffer = []
- # Nominally at this point we could populate our namespace with widgets
- # or other useful functions. We aren't really ready for that just yet.
-
- def evaluate_cell(self, input):
- result = []
- for line in input.split("\n"):
- r = self.push(line)
- if r is not None: result.append(r)
- # To catch if people leave a little bit at the end for us
- if r is None:
- r = self.push("\n")
- if r is not None: result.append(r)
- # Usually they have \n already
- return "".join(result)
-
- def push(self, line):
- """Push 'line' and return exec results (None if more input needed)."""
- if line == "help":
- return "Type help(object) for help about object."
- if line == "help()":
- return "You cannot call help() without an argument."
-
- self.buffer.append(line)
- source = "\n".join(self.buffer)
-
- try:
- code = codeop.compile_command(source, "<HTTP input>", 'single')
- except (OverflowError, SyntaxError, ValueError):
- self.buffer = []
- return traceback.format_exc()
-
- if code is None:
- # More lines needed.
- return None
-
- self.buffer = []
- return self.execute(code)
-
- def execute(self, code):
- """Execute the given code in self.locals and return any stdout/sterr."""
- out = StringIO()
- oldout = sys.stdout
- olderr = sys.stderr
- sys.stdout = sys.stderr = out
- try:
- try:
- exec code in self.locals
- except:
- result = traceback.format_exc()
- else:
- result = out.getvalue()
- finally:
- sys.stdout = oldout
- sys.stderr = olderr
- out.close()
- return result
-
- def dir(self, line):
- """Examine a partial line and provide attr list of final expr."""
- line = re.split(r"\s", line)[-1].strip()
- # Support lines like "thing.attr" as "thing.", because the browser
- # may not finish calculating the partial line until after the user
- # has clicked on a few more keys.
- line = ".".join(line.split(".")[:-1])
- try:
- result = eval("dir(%s)" % line, {}, self.locals)
- except:
- return []
- return result
-
- def doc(self, line):
- """Examine a partial line and provide sig+doc of final expr."""
- line = re.split(r"\s", line)[-1].strip()
- # Support lines like "func(text" as "func(", because the browser
- # may not finish calculating the partial line until after the user
- # has clicked on a few more keys.
- line = "(".join(line.split("(")[:-1])
- try:
- result = eval(line, {}, self.locals)
- try:
- if isinstance(result, type):
- func = result.__init__
- else:
- func = result
- args, varargs, varkw, defaults = inspect.getargspec(func)
- except TypeError:
- if callable(result):
- doc = getattr(result, "__doc__", "") or ""
- return "%s\n\n%s" % (line, doc)
- return None
- except:
- return None
-
- if args and args[0] == 'self':
- args.pop(0)
- missing = object()
- defaults = defaults or []
- defaults = ([missing] * (len(args) - len(defaults))) + list(defaults)
- arglist = []
- for a, d in zip(args, defaults):
- if d is missing:
- arglist.append(a)
- else:
- arglist.append("%s=%s" % (a, d))
- if varargs:
- arglist.append("*%s" % varargs)
- if varkw:
- arglist.append("**%s" % varkw)
- doc = getattr(result, "__doc__", "") or ""
- return "%s(%s)\n%s" % (line, ", ".join(arglist), doc)
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/bottle_mods.py
--- a/yt/gui/reason/bottle_mods.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""
-Modifications and extensions to Bottle, to make it slightly more useful for
-yt's purposes
-
-
-
-"""
-from __future__ import print_function
-from __future__ import absolute_import
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-import uuid
-import json
-import logging, threading
-import sys
-from yt.extern.six.moves import urllib
-import numpy as np
-
-from yt.extern.bottle import \
- server_names, debug, route, run, request, ServerAdapter, response
-from .extdirect_router import DirectRouter, DirectProviderDefinition
-from yt.utilities.logger import ytLogger as mylog
-from yt.funcs import *
-
-route_functions = {}
-route_watchers = []
-payloads = []
-
-def preroute(future_route, *args, **kwargs):
- def router(func):
- route_functions[future_route] = (args, kwargs, func)
- return func
- return router
-
-def notify_route(watcher):
- route_watchers.append(watcher)
-
-class BinaryDelivery(object):
- delivered = False
- payload = ""
- def __init__(self, payload, name = ""):
- self.name = name
- self.payload = payload
- #sys.__stderr__.write("CREATING A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
-
- def get(self):
- # We set our
- #sys.__stderr__.write("REQUESTED A BINARY PAYLOAD %s (%s)\n" % (
- # self.name, len(self.payload)))
- p = self.payload
- if p == "":
- response.status = 404
- return
- self.payload = ""
- return p
-
-class PayloadHandler(object):
- _shared_state = {}
- payloads = None
- binary_payloads = None
- recorded_payloads = None
- multicast_ids = None
- multicast_payloads = None
- lock = None
- record = False
- event = None
- count = 0
- debug = False
- _prefix = ""
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.payloads is None: self.payloads = []
- if self.lock is None: self.lock = threading.Lock()
- if self.recorded_payloads is None: self.recorded_payloads = []
- if self.event is None: self.event = threading.Event()
- if self.multicast_payloads is None: self.multicast_payloads = {}
- if self.multicast_ids is None: self.multicast_ids = {}
- if self.binary_payloads is None: self.binary_payloads = []
-
- def deliver_payloads(self):
- with self.lock:
- payloads = self.payloads
- if self.record:
- self.recorded_payloads += self.payloads
- if self.debug:
- sys.__stderr__.write("**** Delivering %s payloads\n" % (len(payloads)))
- for p in payloads:
- sys.__stderr__.write("**** %s\n" % p['type'])
- self.payloads = []
- self.event.clear()
- try:
- self.deliver_multicast()
- except Exception as exc:
- sys.__stderr__.write("%s" % exc)
- return payloads
-
- def add_payload(self, to_add):
- with self.lock:
- if "binary" in to_add:
- self._add_binary_payload(to_add)
- self.payloads.append(to_add)
- # Does this next part need to be in the lock?
- if to_add.get("widget_id", None) in self.multicast_ids:
- self.multicast_payloads[to_add["widget_id"]] = to_add
- self.count += 1
- self.event.set()
- if self.debug:
- sys.__stderr__.write("**** Adding payload of type %s\n" % (to_add['type']))
-
- def _add_binary_payload(self, bp):
- # This shouldn't be called by anybody other than add_payload.
- bkeys = ensure_list(bp['binary'])
- bp['binary'] = []
- for bkey in bkeys:
- bdata = bp.pop(bkey) # Get the binary data
- if isinstance(bdata, np.ndarray):
- bdata = bdata.tostring()
- bpserver = BinaryDelivery(bdata, bkey)
- self.binary_payloads.append(bpserver)
- uu = uuid.uuid4().hex
- bp['binary'].append((bkey, uu))
- route("%s/%s" % (self._prefix, uu))(bpserver.get)
- if self.debug:
- sys.__stderr__.write(
- "**** Adding binary payload (%s) to %s\n" % (bkey, uu))
-
- def replay_payloads(self):
- return self.recorded_payloads
-
- def widget_payload(self, widget, data):
- data['type'] = 'widget_payload'
- data['widget_id'] = widget._ext_widget_id
- self.add_payload(data)
-
- def deliver_multicast(self):
- for widget_id in self.multicast_payloads:
- if widget_id not in self.multicast_payloads: continue
- server_id, session_token = self.multicast_ids[widget_id]
- # Now we execute a post to the correct location
- data = urllib.parse.urlencode({
- 'payload_session_id': server_id,
- 'payload_session_token': session_token,
- 'payload_data': self.multicast_payloads[widget_id],
- 'payload_metadata': {}
- })
- urllib.request.urlopen("http://localhost:8080/UpdatePayload", data = data)
-
-class YTRocketServer(ServerAdapter):
- server_info = {} # Hack to get back at instance vars
- def run(self, handler):
- from yt.extern.rocket import Rocket
- server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
- self.server_info[id(self)] = server
- server.start()
-
-class BottleDirectRouter(DirectRouter):
- # This class implements a mechanism for auto-routing an ExtDirect-callable
- # object through Bottle. It should be used as a base class of an object,
- # and the __init__ function will need to include the keyword argument
- # 'route' for it to work.
- _route_prefix = None
- def __init__(self, *args, **kwargs):
- future_route = self.api_url
- super(BottleDirectRouter, self).__init__(*args, **kwargs)
- self.__name__ = str(self.my_name)
- route_functions[future_route] = ((), {'method':("POST", "GET")}, self)
- preroute("/resources/ext-%s-api.js" % self.api_url, method="GET")(self._myapi)
- notify_route(self)
-
- def _myapi(self):
- dpd = DirectProviderDefinition(self, self.api_url, ns="yt_rpc")
- source = "Ext.Direct.addProvider(%s);" % json.dumps(dpd._config())
- response.headers['Content-Type'] = "text/javascript"
- return source
-
- def __call__(self):
- #print "Hi there, I just got this request:",
- val = request.body.read()
- #print val
- #import pdb;pdb.set_trace()
- rv = super(BottleDirectRouter, self).__call__(val)
- #print "With this response:", rv
- return rv
-
-def uuid_serve_functions(pre_routed = None, open_browser=False, port=9099,
- repl = None, token = None):
- if pre_routed == None: pre_routed = route_functions
- debug(mode=True)
- if token is None: token = uuid.uuid1()
- for r in pre_routed:
- args, kwargs, f = pre_routed[r]
- if r[0] == "/": r = r[1:]
- rp = "/%s/%s" % (token, r)
- func_name = getattr(f, 'func_name', str(f))
- print("Routing from %s => %s" % (rp, func_name))
- route(rp, *args, **kwargs)(f)
- for w in route_watchers:
- if not hasattr(w, "_route_prefix"):
- print("WARNING: %s has no _route_prefix attribute. Not notifying.")
- continue
- w._route_prefix = token
- repl._global_token = token
- repl.activate()
- repl.execution_thread.wait()
- print()
- print()
- print("=============================================================================")
- print("=============================================================================")
- print("Greetings, and welcome to Reason!")
- print("Your private token is %s ." % token)
- print("DO NOT SHARE THIS TOKEN.")
- print()
- print("Please direct your browser to:")
- print()
- print(" http://localhost:%s/%s/" % (port, token))
- print()
- print("=============================================================================")
- print()
- print("If you are currently ssh'd into a remote machine, you should be able")
- print("to create a new SSH tunnel by typing or copy/pasting this text")
- print("verbatim, while waiting to see the 'ssh>' prompt after the first line.")
- print()
- print("~C")
- print("-L%s:localhost:%s" % (port, port))
- print()
- print("and then pointing a web browser on your local machine to the above URL.")
- print()
- print("=============================================================================")
- print("=============================================================================")
- print()
- print()
- if open_browser:
- # We do some fancy footwork so that we can open the browser while the
- # server starts up. I got this from some recipe whose URL escapes me.
- # Thank you, to whoever wrote it!
- def local_browse():
- """Start a browser after waiting for half a second."""
- import webbrowser, threading
- def _local_browse():
- webbrowser.open('http://localhost:%s/%s/' % (port, token))
- thread = threading.Timer(0.5, _local_browse)
- thread.start()
- local_browse()
- try:
- import yt.extern.rocket as rocket
- server_type = YTRocketServer
- log = logging.getLogger('Rocket')
- log.setLevel(logging.WARNING)
- kwargs = {'timeout': 600, 'max_threads': 2}
- if repl is not None:
- repl.server = YTRocketServer.server_info
- except ImportError:
- server_type = server_names.get("wsgiref")
- kwargs = {}
- server = server_type(host='localhost', port=port, **kwargs)
- mylog.info("Starting up the server.")
- run(server=server)
-
-class MethodLock(object):
- _shared_state = {}
- locks = None
-
- def __new__(cls, *p, **k):
- self = object.__new__(cls, *p, **k)
- self.__dict__ = cls._shared_state
- return self
-
- def __init__(self):
- if self.locks is None: self.locks = {}
-
- def __call__(self, func):
- if str(func) not in self.locks:
- self.locks[str(func)] = threading.Lock()
- @wraps(func)
- def locker(*args, **kwargs):
- print("Acquiring lock on %s" % (str(func)))
- with self.locks[str(func)]:
- rv = func(*args, **kwargs)
- print("Regained lock on %s" % (str(func)))
- return rv
- return locker
-
-lockit = MethodLock()
-
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/extdirect_repl.py
--- a/yt/gui/reason/extdirect_repl.py
+++ /dev/null
@@ -1,499 +0,0 @@
-"""
-A read-eval-print-loop that is served up through Bottle and accepts its
-commands through ExtDirect calls
-
-
-
-"""
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-from yt.extern.six.moves import urllib
-import json
-import os
-import stat
-from cStringIO import StringIO
-import logging
-import uuid
-import numpy as np
-import time
-import pprint
-import traceback
-import tempfile
-import base64
-import imp
-import threading
-import Queue
-import zipfile
-try:
- import Pyro4
-except ImportError:
- pass
-
-from yt.funcs import *
-from yt.utilities.logger import ytLogger, ufstring
-from yt.visualization.image_writer import apply_colormap
-from yt.visualization.api import Streamlines
-from .widget_store import WidgetStore
-
-from .bottle_mods import preroute, BottleDirectRouter, notify_route, \
- PayloadHandler, lockit
-from yt.extern.bottle import response, request, route, static_file
-from .utils import get_list_of_datasets
-from .basic_repl import ProgrammaticREPL
-
-try:
- import pygments
- import pygments.lexers
- import pygments.formatters
- def _highlighter():
- pl = pygments.lexers.PythonLexer()
- hf = pygments.formatters.HtmlFormatter(
- linenos='table', linenospecial=2)
- def __highlighter(a):
- return pygments.highlight(a, pl, hf)
- return __highlighter, hf.get_style_defs()
- # We could add an additional '.highlight_pyg' in the call
- highlighter, highlighter_css = _highlighter()
-except ImportError:
- highlighter = lambda a: a
- highlight_css = ''
-
-local_dir = os.path.dirname(__file__)
-
-class ExecutionThread(threading.Thread):
- def __init__(self, repl):
- self.repl = repl
- self.payload_handler = PayloadHandler()
- self.queue = Queue.Queue()
- threading.Thread.__init__(self)
- self.daemon = True
-
- def heartbeat(self):
- return
-
- def run(self):
- while 1:
- #print "Checking for a queue ..."
- try:
- task = self.queue.get(True, 1)
- except Queue.Empty:
- if self.repl.stopped: return
- continue
- print("Received the task", task)
- if task['type'] != 'code':
- raise NotImplementedError
- print(task)
- self.execute_one(task['code'], task['hide'], task['result_id'])
- self.queue.task_done()
-
- def wait(self):
- self.queue.join()
-
- def execute_one(self, code, hide, result_id):
- self.repl.executed_cell_texts.append(code)
- result = ProgrammaticREPL.execute(self.repl, code)
- if self.repl.debug:
- print("==================== Cell Execution ====================")
- print(code)
- print("==================== ====================")
- print(result)
- print("========================================================")
- self.payload_handler.add_payload(
- {'type': 'cell',
- 'output': result,
- 'input': highlighter(code),
- 'image_data': '',
- 'result_id': result_id,
- 'hide': hide,
- 'raw_input': code},
- )
- objs = get_list_of_datasets()
- self.payload_handler.add_payload(
- {'type': 'dataobjects',
- 'objs': objs})
-
-class PyroExecutionThread(ExecutionThread):
- def __init__(self, repl):
- ExecutionThread.__init__(self, repl)
- hmac_key = raw_input("HMAC_KEY? ").strip()
- uri = raw_input("URI? ").strip()
- Pyro4.config.HMAC_KEY = hmac_key
- self.executor = Pyro4.Proxy(uri)
-
- def execute_one(self, code, hide, result_id):
- self.repl.executed_cell_texts.append(code)
- print(code)
- result = self.executor.execute(code)
- if not hide:
- self.repl.payload_handler.add_payload(
- {'type': 'cell',
- 'output': result,
- 'input': highlighter(code),
- 'result_id': result_id,
- 'raw_input': code},
- )
- ph = self.executor.deliver()
- for p in ph:
- self.repl.payload_handler.add_payload(p)
-
- def heartbeat(self):
- ph = self.executor.deliver()
- for p in ph:
- self.repl.payload_handler.add_payload(p)
-
-def reason_pylab():
- from .utils import deliver_image
- def _canvas_deliver(canvas):
- tf = tempfile.TemporaryFile()
- canvas.print_png(tf)
- tf.seek(0)
- img_data = base64.b64encode(tf.read())
- tf.close()
- deliver_image(img_data)
- def reason_draw_if_interactive():
- if matplotlib.is_interactive():
- figManager = Gcf.get_active()
- if figManager is not None:
- _canvas_deliver(figManager.canvas)
- def reason_show(mainloop = True):
- # We ignore mainloop here
- for manager in Gcf.get_all_fig_managers():
- _canvas_deliver(manager.canvas)
- # Matplotlib has very nice backend overriding.
- # We should really use that. This is just a hack.
- import matplotlib
- matplotlib.use("agg") # Hotfix for when we import pylab below
- new_agg = imp.new_module("reason_agg")
- import matplotlib.backends.backend_agg as bagg
- new_agg.__dict__.update(bagg.__dict__)
- new_agg.__dict__.update(
- {'show': reason_show,
- 'draw_if_interactive': reason_draw_if_interactive})
- sys.modules["reason_agg"] = new_agg
- bagg.draw_if_interactive = reason_draw_if_interactive
- from matplotlib._pylab_helpers import Gcf
- matplotlib.rcParams["backend"] = "module://reason_agg"
- import pylab
- pylab.switch_backend("module://reason_agg")
-
-_startup_template = r"""\
-import pylab
-from yt.mods import *
-from yt.gui.reason.utils import load_script, deliver_image
-from yt.gui.reason.widget_store import WidgetStore
-from yt.data_objects.static_output import _cached_datasets
-
-pylab.ion()
-data_objects = []
-widget_store = WidgetStore()
-"""
-
-class ExtDirectREPL(ProgrammaticREPL, BottleDirectRouter):
- _skip_expose = ('index')
- my_name = "ExtDirectREPL"
- timeout = 660 # a minute longer than the rocket server timeout
- server = None
- _heartbeat_timer = None
-
- def __init__(self, reasonjs_path, locals=None,
- use_pyro=False):
- # First we do the standard initialization
- self.reasonjs_file = zipfile.ZipFile(reasonjs_path, 'r')
- ProgrammaticREPL.__init__(self, locals)
- # Now, since we want to only preroute functions we know about, and
- # since they have different arguments, and most of all because we only
- # want to add them to the routing tables (which are a singleton for the
- # entire interpreter state) we apply all the pre-routing now, rather
- # than through metaclasses or other fancy decorating.
- preroute_table = dict(index = ("/", "GET"),
- _help_html = ("/help.html", "GET"),
- _myapi = ("/ext-repl-api.js", "GET"),
- _session_py = ("/session.py", "GET"),
- _highlighter_css = ("/highlighter.css", "GET"),
- _reasonjs = ("/reason-js/:path#.+#", "GET"),
- _app = ("/reason/:path#.+#", "GET"),
- )
- for v, args in preroute_table.items():
- preroute(args[0], method=args[1])(getattr(self, v))
- # This has to be routed to the root directory
- self.api_url = "repl"
- BottleDirectRouter.__init__(self)
- self.payload_handler = PayloadHandler()
- if use_pyro:
- self.execution_thread = PyroExecutionThread(self)
- else:
- self.execution_thread = ExecutionThread(self)
- # We pass in a reference to ourself
- self.execute(_startup_template)
- self.widget_store = WidgetStore(self)
- # Now we load up all the yt.mods stuff, but only after we've finished
- # setting up.
- reason_pylab()
-
- def activate(self):
- self.payload_handler._prefix = self._global_token
- self._setup_logging_handlers()
- # Setup our heartbeat
- self.last_heartbeat = time.time()
- self._check_heartbeat()
- self.execute("widget_store._global_token = '%s'" % self._global_token)
- self.execution_thread.start()
-
- def exception_handler(self, exc):
- result = {'type': 'cell',
- 'input': 'ERROR HANDLING IN REASON',
- 'result_id': None,
- 'output': traceback.format_exc()}
- return result
-
- def _setup_logging_handlers(self):
- handler = PayloadLoggingHandler()
- formatter = logging.Formatter(ufstring)
- handler.setFormatter(formatter)
- ytLogger.addHandler(handler)
-
- def index(self):
- root = os.path.join(local_dir, "html")
- return static_file("index.html", root)
-
- def heartbeat(self):
- self.last_heartbeat = time.time()
- if self.debug: print("### Heartbeat ... started: %s" % (time.ctime()))
- for i in range(30):
- # Check for stop
- if self.debug: print(" ###")
- if self.stopped: return {'type':'shutdown'} # No race condition
- if self.payload_handler.event.wait(1): # One second timeout
- if self.debug: print(" ### Delivering payloads")
- rv = self.payload_handler.deliver_payloads()
- if self.debug: print(" ### Got back, returning")
- return rv
- self.execution_thread.heartbeat()
- if self.debug: print("### Heartbeat ... finished: %s" % (time.ctime()))
- return []
-
- def _check_heartbeat(self):
- if self.server is not None:
- if not all((s._monitor.is_alive() for s in self.server.values())):
- self.shutdown()
- return
- if time.time() - self.last_heartbeat > self.timeout:
- print("Shutting down after a timeout of %s" % (self.timeout))
- #sys.exit(0)
- # Still can't shut down yet, because bottle doesn't return the
- # server instance by default.
- self.shutdown()
- return
- if self._heartbeat_timer is not None: return
- self._heartbeat_timer = threading.Timer(10, self._check_heartbeat)
- self._heartbeat_timer.start()
-
- def shutdown(self):
- if self.server is None:
- return
- self._heartbeat_timer.cancel()
- self.stopped = True
- self.payload_handler.event.set()
- for v in self.server.values():
- v.stop()
- for t in threading.enumerate():
- print("Found a living thread:", t)
-
- def _help_html(self):
- root = os.path.join(local_dir, "html")
- return static_file("help.html", root)
-
- def _reasonjs(self, path):
- pp = os.path.join("reason-js", path)
- try:
- f = self.reasonjs_file.open(pp)
- except KeyError:
- response.status = 404
- return
- if path[-4:].lower() in (".png", ".gif", ".jpg"):
- response.headers['Content-Type'] = "image/%s" % (path[-3:].lower())
- elif path[-4:].lower() == ".css":
- response.headers['Content-Type'] = "text/css"
- elif path[-3:].lower() == ".js":
- response.headers['Content-Type'] = "text/javascript"
- return f.read()
-
- def _app(self, path):
- root = os.path.join(local_dir, "html")
- return static_file(path, root)
-
- def _highlighter_css(self):
- response.headers['Content-Type'] = "text/css"
- return highlighter_css
-
- def execute(self, code, hide = False, result_id = None):
- task = {'type': 'code',
- 'code': code,
- 'hide': hide,
- 'result_id': result_id,
- }
- self.execution_thread.queue.put(task)
- return dict(status = True)
-
- def get_history(self):
- return self.executed_cell_texts[:]
-
- @lockit
- def save_session(self, filename):
- if filename.startswith('~'):
- filename = os.path.expanduser(filename)
- elif not filename.startswith('/'):
- filename = os.path.join(os.getcwd(), filename)
- if os.path.exists(filename):
- return {'status': 'FAIL', 'filename': filename,
- 'error': 'File exists!'}
- try:
- f = open(filename, 'w')
- f.write("\n######\n".join(self.executed_cell_texts))
- f.close()
- except IOError as xxx_todo_changeme:
- (errno, strerror) = xxx_todo_changeme.args
- return {'status': 'FAIL', 'filename': filename,
- 'error': strerror}
- except:
- return {'status': 'FAIL', 'filename': filename,
- 'error': 'Unexpected error.'}
- return {'status': 'SUCCESS', 'filename': filename}
-
- @lockit
- def paste_session(self):
- import xmlrpclib
- p = xmlrpclib.ServerProxy(
- "http://paste.yt-project.org/xmlrpc/",
- allow_none=True)
- cs = StringIO()
- cs.write("\n######\n".join(self.executed_cell_texts))
- cs = cs.getvalue()
- ret = p.pastes.newPaste('python', cs, None, '', '', True)
- site = "http://paste.yt-project.org/show/%s" % ret
- return {'status': 'SUCCESS', 'site': site}
-
- @lockit
- def paste_text(self, to_paste):
- import xmlrpclib
- p = xmlrpclib.ServerProxy(
- "http://paste.yt-project.org/xmlrpc/",
- allow_none=True)
- ret = p.pastes.newPaste('python', to_paste, None, '', '', True)
- site = "http://paste.yt-project.org/show/%s" % ret
- return {'status': 'SUCCESS', 'site': site}
-
- _api_key = 'f62d550859558f28c4c214136bc797c7'
- def upload_image(self, image_data, caption):
- if not image_data.startswith("data:"): return {'uploaded':False}
- prefix = "data:image/png;base64,"
- image_data = image_data[len(prefix):]
- parameters = {'key':self._api_key, 'image':image_data, type:'base64',
- 'caption': caption, 'title': "Uploaded Image from reason"}
- data = urllib.parse.urlencode(parameters)
- req = urllib.request.Request('http://api.imgur.com/2/upload.json', data)
- try:
- response = urllib.request.urlopen(req).read()
- except urllib.error.HTTPError as e:
- print("ERROR", e)
- return {'uploaded':False}
- rv = json.loads(response)
- rv['uploaded'] = True
- pprint.pprint(rv)
- return rv
-
- @lockit
- def _session_py(self):
- cs = StringIO()
- cs.write("\n######\n".join(self.executed_cell_texts))
- cs.seek(0)
- response.headers["content-disposition"] = "attachment;"
- return cs
-
- @lockit
- def load(self, base_dir, filename):
- pp = os.path.join(base_dir, filename)
- funccall = "datasets.append(load('%s'))" % pp
- self.execute(funccall)
- return []
-
- def file_listing(self, base_dir, sub_dir):
- if base_dir == "":
- cur_dir = os.getcwd()
- elif sub_dir == "":
- cur_dir = base_dir
- else:
- cur_dir = os.path.join(base_dir, sub_dir)
- cur_dir = os.path.abspath(cur_dir)
- if not os.path.isdir(cur_dir):
- return {'change':False}
- fns = os.listdir(cur_dir)
- results = [("..", 0, "directory")]
- for fn in sorted((os.path.join(cur_dir, f) for f in fns)):
- if not os.access(fn, os.R_OK): continue
- if os.path.isfile(fn):
- size = os.path.getsize(fn)
- t = "file"
- else:
- size = 0
- t = "directory"
- results.append((os.path.basename(fn), size, t))
- return dict(objs = results, cur_dir=cur_dir)
-
-class PayloadLoggingHandler(logging.StreamHandler):
- def __init__(self, *args, **kwargs):
- logging.StreamHandler.__init__(self, *args, **kwargs)
- self.payload_handler = PayloadHandler()
-
- def emit(self, record):
- msg = self.format(record)
- self.payload_handler.add_payload(
- {'type':'logentry',
- 'log_entry':msg})
-
-if os.path.exists(os.path.expanduser("~/.yt/favicon.ico")):
- ico = os.path.expanduser("~/.yt/")
-else:
- ico = os.path.join(local_dir, "html", "resources", "images")
- at route("/favicon.ico", method="GET")
-def _favicon_ico():
- print(ico)
- return static_file("favicon.ico", ico)
-
-class ExtProgressBar(object):
- def __init__(self, title, maxval):
- self.title = title
- self.maxval = maxval
- self.last = 0
- # Now we add a payload for the progress bar
- self.payload_handler = PayloadHandler()
- self.payload_handler.add_payload(
- {'type': 'widget',
- 'widget_type': 'progressbar',
- 'varname': 'pbar_top',
- 'data': {'title':title}
- })
-
- def update(self, val):
- # An update is only meaningful if it's on the order of 1/100 or greater
-
- if (val - self.last) > (self.maxval / 100.0):
- self.last = val
- self.payload_handler.add_payload(
- {'type': 'widget_payload',
- 'widget_id': 'pbar_top',
- 'value': float(val) / self.maxval})
-
- def finish(self):
- self.payload_handler.add_payload(
- {'type': 'widget_payload',
- 'widget_id': 'pbar_top',
- 'value': -1})
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/extdirect_router.py
--- a/yt/gui/reason/extdirect_router.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""
-This is code from the extdirect package:
-
-http://pypi.python.org/pypi/extdirect/0.3
-https://github.com/iancmcc/extdirect
-
-written by Ian McCracken
-
-This code was released under the BSD License.
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-import inspect
-
-class DirectException(Exception):
- pass
-
-
-try:
- import json
-except ImportError:
- try:
- import simplejson as json
- except ImportError:
- raise DirectException("No JSON library available. Please install"
- " simplejson or upgrade to Python 2.6.")
-
-
-class DirectRouter(object):
- """
- Basic Ext.Direct router class.
-
- Ext.Direct allows one to create an API that communicates with a single URL,
- which then routes requests to the appropriate method. The client-side API
- object matches the server-side API object.
-
- This base class parses an Ext.Direct request, which contains the name of
- the method and any data that should be passed, and routes the data to the
- approriate method. It then receives the output of that call and puts it
- into the data structure expected by Ext.Direct.
-
- Call an instance of this class with the JSON from an Ext.Direct request.
- """
- exception_handler = None
- def __call__(self, body):
- """
- """
- # Decode the request data
- body = json.loads(body)
- self._body = body
-
- if isinstance(body, list):
- directRequests = body
- elif isinstance(body, dict):
- directRequests = [body]
- else:
- raise DirectException("Body is not a support type: %s" % body)
-
- responses = []
-
- for req in directRequests:
- responses.append(self._doRequest(req))
-
- if len(responses) == 1:
- responses = responses[0]
-
- return json.dumps(responses)
-
- def _doRequest(self, request):
-
- # Double-check that this request is meant for this class
- action = request.get('action')
- clsname = self.__class__.__name__
- if action != clsname:
- raise DirectException(("Action specified in request ('%s') is"
- " not named %s.") % (action, clsname))
-
- # Pull out the method name and make sure it exists on this class
- method = request.get('method')
- if not method:
- raise DirectException("No method specified. Is this a valid"
- " Ext.Direct request?")
- try:
- _targetfn = getattr(self, method)
- except AttributeError:
- raise DirectException("'%s' is not the name of a method on %s" % (
- method, clsname
- ))
-
- # Pull out any arguments. Sent as an array containing a hash map, so
- # get the first member.
- data = request.get('data')
- if not data:
- data = {}
- else:
- data = data[0]
-
- # Cast all keys as strings, in case of encoding or other wrinkles
- data = dict((str(k), v) for k,v in data.iteritems())
- self._data = data
-
- # Finally, call the target method, passing in the data
- try:
- result = _targetfn(**data)
- except Exception as e:
- if self.exception_handler is not None:
- result = self.exception_handler(e)
- else:
- raise e
-
- return {
- 'type':'rpc',
- 'tid': request['tid'],
- 'action': action,
- 'method': method,
- 'result': result
- }
-
-
-class DirectProviderDefinition(object):
- """
- Turns a L{DirectRouter} subclass into JavaScript object representing the
- config of the client-side API.
-
- Inspects the given subclass and retrieves the names of all public methods,
- then defines those as actions on the Ext.Direct provider, and creates the
- JS that adds the provider.
-
- See http://extjs.com/products/extjs/direct.php for a full explanation of
- protocols and features of Ext.Direct.
- """
- def __init__(self, routercls, url, ns=None, timeout=None):
- """
- @param routercls: A L{DirectRouter} subclass
- @type routercls: class
- @param url: The url at which C{routercls} is available
- @type url: str
- @param ns: The client-side namespace in which the provider should live.
- The provider will be available at [ns].[routercls.__name__].
- For example, if ns is 'Zenoss.remote' and routercls is named
- 'EventConsole', client-side code would call
- C{Zenoss.remote.EventConsole.my_method(params, callback)}.
- """
- self.routercls = routercls
- self.url = url
- self.ns = ns
- self.timeout = timeout
-
- def _config(self):
- actions = []
- for name, value in inspect.getmembers(self.routercls):
- if name.startswith("_"):
- continue
- if inspect.ismethod(value):
-
- ## Update this when extdirect doesn't freak out when you specify
- ## actual lens (we're passing them all in as a single dict, so
- ## from the perspective of Ext.Direct they are all len 1)
- #args = inspect.getargspec(value)[0]
- #args.remove('self')
- #arglen = len(args)
- arglen = 1
-
- actions.append({'name':name, 'len':arglen})
- config = {
- 'id': self.routercls.__name__,
- 'type': 'remoting',
- 'url': self.url,
- 'actions': {
- self.routercls.__name__: actions
- }
- }
- if self.timeout:
- config['timeout'] = self.timeout
- if self.ns:
- config['namespace'] = self.ns
- return config
-
- def render(self):
- """
- Generate and return an Ext.Direct provider definition, wrapped in a
- <script> tag and ready for inclusion in an HTML document.
- """
- config = self._config()
- source = "Ext.Direct.addProvider(%s);" % json.dumps(config)
- return '<script type="text/javascript"> %s </script>' % source.strip()
-
-
-
-
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app.js
--- a/yt/gui/reason/html/app.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/**********************************************************************
-The main GUI facility for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.Loader.setConfig({enabled:true});
-
-var reason, rdebug, examine;
-
-Ext.application({
- requires: ['Ext.container.Viewport',
- 'Reason.view.LoggingGrid',
- 'Reason.view.DataObjectTree',
- 'Reason.controller.widgets.SampleWidget',
- ],
- name: 'Reason',
-
- appFolder: 'reason/app',
-
- launch: function() {
- reason = this;
- this.numberOfRequests = 0;
- rdebug = this.getController("Debugger");
- this.server = this.getController("ServerCommunication");
- Ext.create('Ext.container.Viewport', {
- layout: 'border',
- items: [
- {
- xtype: 'logginggrid',
- autofill: true,
- region: 'south',
- id: "status-region",
- cls: "status-logger",
- split: true,
- height: 100,
- maxSize: 200,
- collapsible: true,
- title: 'Status',
- margins: '0 0 0 0',
- }, {
- id: 'west-panel',
- region: 'west',
- split: true,
- width: 200,
- minSize: 175,
- maxSize: 400,
- collapsible: true,
- layout: {
- type: 'vbox',
- pack: 'start',
- align: 'stretch',
- },
- items: [
- { xtype: 'dataobjecttree',
- flex: 1.0},
- { xtype: 'panel',
- tpl: 'Pending Requests: {0}',
- data: [0],
- height: 30,
- id: 'pending',
- }
- ],
- }, {
- xtype: 'tabpanel',
- region: 'center',
- id: 'center-panel',
- activeTab: 0,
- dockedItems: [ {
- dock: 'top',
- xtype: 'mainmenu',
- } ],
- items: [
- { xtype: 'panel',
- title: 'Welcome!',
- closeable: true,
- autoLoad: 'help.html',
- },
- { xtype: 'ytnotebook' },
- ]
- }
- ]
- });
- this.pending = Ext.getCmp("pending");
- this.fireEvent("allowinput");
- },
- controllers : [
- 'Logging',
- 'DataObjects',
- 'Notebook',
- 'ServerCommunication',
- 'WidgetDirector',
- 'MenuActions',
- 'Debugger',
- 'FileOpen',
- ],
-
-});
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/DataObjects.js
--- a/yt/gui/reason/html/app/controller/DataObjects.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/**********************************************************************
-Data object controller for Reason
-
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, yt Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-***********************************************************************/
-
-Ext.define('Reason.controller.DataObjects', {
- extend: 'Ext.app.Controller',
- stores: [ 'DataObjects' ],
- models: ['DataObject'],
- view: ['DataObjectTree'],
- refs: [
- { ref: 'dataObjectTree',
- selector: 'dataobjecttree#dataobjects',
- xtype: 'dataobjecttree',
- itemId: 'dataobjects',
- autoCreate: true,
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloaddataobjects : {fn: this.refreshDataObjects, scope: this},
- });
- this.control({
- "#dataobjects": { itemcontextmenu:
- function(view, rec, node, index, e) {
- e.preventDefault();
- this.application.fireEvent("showwidgets", rec, e);
- }
- }});
- this.callParent(arguments);
- },
-
- refreshDataObjects: function(payload) {
- /*console.log("Refreshing data objects");*/
- var objs = payload['objs'];
- var root = this.getDataObjectsStore().getRootNode();
- root.removeAll();
- var pf;
- Ext.each(objs, function(o, i, os) {
- /*console.log("Appending " + o['name']);*/
- pf = root.appendChild({
- name: o.name,
- type: o.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: o.varname,
- leaf: false,
- expanded: true,
- iconCls: 'pf_icon'
- });
- Ext.each(o['children'], function(c, ci, cs) {
- /*console.log(" Appending " + c['name']);*/
- pf.appendChild({name: c.name,
- type: c.type,
- filename: o.filename,
- field_list: o.field_list,
- varname: c.varname,
- leaf: true,
- iconcls: 'data_obj'});
-
- });
- });
- },
-});
-
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/Debugger.js
--- a/yt/gui/reason/html/app/controller/Debugger.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**********************************************************************
-Debug helper for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Debugger', {
- extend: 'Ext.app.Controller',
- stores: ['WidgetTypes', 'WidgetInstances', 'Requests'],
-
- getWidget: function(widgetId) {
- this.getWidgetInstancesStore().find(
- {'widgetid': widgetId});
- var widgetInfo = this.getWidgetInstancesStore().getAt(resultId).data;
- return widgetInfo.widget;
- },
-
- getAllWidgetsByType: function(typeName) {
- var arr = []
- this.getWidgetInstancesStore().each(function(r) {
- if (r.data['widgettype'] == typeName) {
- arr.push(r.data);
- }
- });
- return arr;
- },
-
-});
-
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/FileOpen.js
--- a/yt/gui/reason/html/app/controller/FileOpen.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/**********************************************************************
-File Open Dialog for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.FileOpen', {
- extend: 'Ext.app.Controller',
- stores: ['FileListing'],
- requires: ["Reason.view.FileOpen"],
-
- init: function() {
-
- },
-
- openDialog: function() {
- this.currentDirectory = '',
- this.getFileListingStore().removeAll();
- reason.server.method("file_listing",
- {base_dir:"", sub_dir:""}, this.fillStore);
- this.win = Ext.widget("fileopenwindow");
- this.win.query("#file_listing")[0].bindStore(this.getFileListingStore());
- /* Set up our handlers */
- this.control({
- '#current_file': { specialkey: this.specialKeyPressed, },
- '#file_listing': { celldblclick: this.doubleClicked, },
- '#load': { click: this.loadFile, },
- '#cancel': { click: this.cancelWindow, }
- });
- this.win.show();
- },
-
- specialKeyPressed: function(f, e) {
- if (e.getKey() != e.ENTER) { return; }
- reason.server.method("file_listing",
- {base_dir:f.getValue(), sub_dir:""}, this.fillStore);
- },
-
- doubleClicked: function(view, td, cellIndex, record) {
- conf = {'base_dir': this.currentDirectory};
- if (record.data.type == 'directory') {
- conf['sub_dir'] = record.data.filename;
- reason.server.method('file_listing', conf, this.fillStore);
- } else {
- conf['filename'] = record.data.filename;
- reason.server.method('load', conf);
- this.win.destroy();
- }
- },
-
- loadFile: function(b, e) {
- var conf = {filename: '', base_dir: this.currentDirectory};
- var fl = this.win.query("#file_listing")[0];
- var idx = fl.getSelectionModel().getSelection();
- if (idx == 1) {
- conf['filename'] = this.getFileListingStore().getAt(idx).data.filename;
- }
- reason.server.method('load', conf);
- },
-
- cancelWindow: function(b, e) {
- this.win.destroy();
- },
-
- fillStore: function(f, a) {
- var con = reason.getController("FileOpen");
- if(a.status == false){
- Ext.Msg.alert("Error", "Something has gone wrong.");
- con.window.destroy();
- }
- if(a.result['change'] == false) {
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- return;
- }
- con.getFileListingStore().removeAll();
- var rec = [];
- con.getFileListingStore().loadData(a.result['objs']);
- con.currentDirectory = a.result['cur_dir'];
- con.win.query("#current_file")[0].setValue(con.currentDirectory);
- },
-});
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/Logging.js
--- a/yt/gui/reason/html/app/controller/Logging.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/**********************************************************************
-Logging entry controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Logging', {
- extend: 'Ext.app.Controller',
- stores: [ 'LogEntries' ],
- view: ['LoggingGrid'],
-
- refs: [
- { ref: 'logEntries',
- selector: '#logentries'
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadlogentry: {fn: this.addLogPayload, scope: this},
- logentry: {fn: this.addLogEntry, scope: this},
- });
- },
-
- addLogPayload: function(payload) {
- this.addLogEntry(payload['log_entry']);
- },
-
- addLogEntry: function(text) {
- this.getLogEntriesStore().add({record: text});
- var i = this.getLogEntriesStore().getCount();
- this.getLogEntries().getView().focusRow(i - 1);
- },
-});
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/MenuActions.js
--- a/yt/gui/reason/html/app/controller/MenuActions.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**********************************************************************
-Menu actions in Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-
-Ext.define('Reason.controller.MenuActions', {
- extend: 'Ext.app.Controller',
- views: ['MainMenu'],
-
- init: function() {
- this.control({
- '#openfile': { click: this.openFile },
- '#savescript': { click: this.saveScript},
- '#downloadscript': { click: this.downloadScript },
- '#pastebinscript': { click: this.pastebinScript },
- '#ytchat': {click: this.openIRCChannel },
- '#quit': {click: this.quitReason },
- '#enabledebug': {click: this.enableDebug },
- });
- this.callParent(arguments);
- },
-
- saveScript: function (b,e) {
- /* This function gets called on success */
- var controller = this;
- function handleResponse(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Saved session to ' + a.result['filename'];
- Ext.Msg.alert('Success!', alert_text);
- controller.application.fireEvent("logentry", alert_text);
- } else {
- Ext.Msg.alert('Always naysaying!',
- 'Failed to save to ' + a.result['filename'] + '<br>Error: ' +
- a.result['error']);
- }
- };
- /* Now we prompt */
- Ext.Msg.prompt("We have important work to do.", "Enter filename.",
- function(btn, text) {
- if (btn == 'ok') {
- reason.server.method('save_session',
- {filename:text}, handleResponse);
- }
- }
- );
- },
-
- openFile: function(b, e) {
- this.application.getController("FileOpen").openDialog();
- },
-
- downloadScript: function(b, e) {
- window.open("session.py", "_top");
- this.application.fireEvent("logentry", 'Saved session locally.')
- },
-
- pastebinScript: function(b, e) {
- reason.server.method('paste_session', {}, function(f, a) {
- if (a.result['status'] == 'SUCCESS') {
- var alert_text = 'Pasted session to:<br>' +
- a.result['site']
- var alert_text_rec = 'Pasted session to: ' +
- a.result['site']
- Ext.Msg.alert('Pastebin', alert_text);
- this.application.fireEvent("logentry", alert_text_rec);
- }
- });
- },
-
- openIRCChannel: function(b, e) {
- window.open("http://yt-project.org/irc.html", "_new");
- },
-
- quitReason: function(b, e) {
- this.application.fireEvent("stopheartbeat");
- reason.server.method('shutdown', {}, function(f, a) {
- Ext.Msg.alert("Goodbye!", "Goodbye from Reason!", function() {
- window.open("http://www.google.com/", "_top");});});
- },
-
- enableDebug: function() {
- this.application.fireEvent("enabledebug");
- },
-});
-
diff -r 677e2f175540c89f7761eae0d2a74ae2e62369dd -r 89dd8b5534fee839aa66ece835c93beb36eb74db yt/gui/reason/html/app/controller/Notebook.js
--- a/yt/gui/reason/html/app/controller/Notebook.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/**********************************************************************
-Notebook controller for Reason
-
-Copyright (c) 2013, yt Development Team.
-
-Distributed under the terms of the Modified BSD License.
-
-The full license is in the file COPYING.txt, distributed with this software.
-***********************************************************************/
-
-Ext.define('Reason.controller.Notebook', {
- extend: 'Ext.app.Controller',
- stores: [ 'CellValues' , 'Requests'],
- views: ['Notebook', 'CellView'],
- refs: [
- { ref: 'inputLine',
- selector: '#inputline'
- },
- { ref: 'cellDisplay',
- selector: 'notebookcells#cells',
- xtype: 'notebookcells',
- autoCreate: true,
- itemId: 'cells',
- },
- ],
-
- init: function() {
- this.application.addListener({
- payloadcell: {fn: this.addCell, scope: this},
- payloadscript: {fn: this.loadScript, scope: this},
- executecell: {fn: this.executeCell, scope: this},
- wipeinput: {fn: this.wipeInputLine, scope: this},
- blockinput: {fn: this.blockInput, scope: this},
- allowinput: {fn: this.allowInput, scope: this},
- scrolltobottom: {fn: this.scrollToBottom, scope: this},
- })
- this.control({
- '#executecellbutton': {
- click: function(f, e) {
- this.executeCell(this.getInputLine().getValue());
- }
- },
- '#inputline': {
- specialkey: function(field, e, opts){
- if (e.shiftKey && e.getKey() == e.ENTER) {
- this.executeCell(field.getValue());
- }
- },
- },
- });
- this.callParent(arguments);
- },
-
- addRequest: function(request_id, command) {
- /*console.log("Adding request " + request_id);*/
- this.getRequestsStore().add({
- request_id: request_id, command: command,
- });
- reason.pending.update([this.getRequestsStore().count()]);
- },
-
- addCell: function(cell) {
- this.application.fireEvent("wipeinput");
- this.application.fireEvent("allowinput");
- if (cell['result_id'] != null) {
- var ind = this.getRequestsStore().find(
- 'request_id', cell['result_id']);
- if (ind != -1) {
- /*console.log("Removing request " + cell['result_id']);*/
- var rec = this.getRequestsStore().removeAt(ind);
- }
- reason.pending.update([this.getRequestsStore().count()]);
- }
- if (cell['hide'] == true) { return; }
- this.getCellValuesStore().add({
- input: cell['input'],
- output: cell['output'],
- raw_input: cell['raw_input'],
- image_data: cell['image_data'],
- executiontime: cell['executiontime'],
- result_id: cell['result_id'],
- });
- this.application.fireEvent("scrolltobottom");
- },
-
- loadScript: function(payload) {
- this.getInputLine().setValue(payload['value']);
- this.getInputLine()._lock = true;
- },
-
- executeCell: function(line) {
- this.application.fireEvent("blockinput");
- reason.server.execute(line, false);
- },
-
- scrollToBottom: function() {
- var i = this.getCellValuesStore().getCount();
- this.getCellDisplay().getView().focusRow(i-1);
- },
-
- wipeInputLine: function() {
- if(this.getInputLine()._lock == true) {
- this.getInputLine()._lock = false;
- } else {
- this.getInputLine().setValue("");
- }
- },
-
- blockInput: function() {
- this.getInputLine().addClass("cell_waiting");
- this.getInputLine().setReadOnly(true);
- },
-
- allowInput: function() {
- this.getInputLine().removeCls("cell_waiting");
- this.getInputLine().setReadOnly(false);
- var application = this.application;
- },
-
-});
-
This diff is so big that we needed to truncate the remainder.
Repository URL: https://bitbucket.org/yt_analysis/yt/
--
This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.
More information about the yt-svn
mailing list