11 new commits in galaxy-central: https://bitbucket.org/galaxy/galaxy-central/commits/cadad49537de/ Changeset: cadad49537de User: martenson Date: 2014-09-08 18:27:49+00:00 Summary: initial implementation of UI, API and flow for importing from Galaxy user directories, introduces jstree browser into the project, includes refactoring of some library API methods into common managers Affected #: 22 files diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/util/dictobj.py --- /dev/null +++ b/lib/galaxy/util/dictobj.py @@ -0,0 +1,229 @@ +import pickle + +class DictionaryObject(object): + """ + A class that has all the functionality of a normal Python dictionary, except + for the fact it is itself immutable. It also has the added feature of + being able to lookup values by using keys as attributes. + + The reason for the class being immutable by default is to help make it a + little easier to use in multiprocessing situations. Granted, the underlying + values themselves are not deeply copied, but the aim is to enforce some + ensurances of immutability on the container class. + + When using positional arguments, the first argument must always be something + that would be a valid argument for a dict(). However, a second, optional + argument may be passed to create a default value when keys are not found. + + Examples: + >>> d = DictionaryObject({'a':1, 'b':True, 3:'x'}) + >>> print d.a, d.b, d[3] + 1 True x + + >>> d = DictionaryObject((('a',1),('b',2))) + >>> print d.a, d.b + 1 2 + + >>> d = DictionaryObject(a=1, b=True) + >>> print d + DictionaryObject({'a': 1, 'b': True}) + + >>> d = DictionaryObject({'a':1, 'b':True}, None) + >>> print d.a, d.b, d.c, d.d + 1 True None None + + >>> d = DictionaryObject({'a':1}, None) + >>> m = MutableDictionaryObject(d) + >>> print d == m + True + >>> m.a = 0 + >>> print d == m, d < m, d > m, d != m, d <= m, d >= m + False False True True False True + + >>> import pickle + >>> m1 = MutableDictionaryObject({'a':1}, None) + >>> m2 = pickle.loads(pickle.dumps(m1)) + >>> print m1 == m2 + True + >>> m1.a = 3 + >>> print m1 == m2 + False + >>> m1.a == 3 + True + >>> m1['c'] = 5 + >>> m1['c'] + 5 + """ + def __init__(self, contents=(), *args, **kwargs): + """ + Take as input a dictionary-like object and return a DictionaryObject. + It also makes sure any keys containing dictionaries are also converted + to DictionaryObjects. + """ + super(DictionaryObject, self).__init__() + if isinstance(contents, DictionaryObject): + self.__dict__.update(pickle.loads(pickle.dumps(contents.__dict__))) + return + + self.__dict__['_items'] = dict(contents, **kwargs) + + if len(args) > 1: + raise TypeError("too many arguments") + + # If we have more than one argument passed in, use the second argument + # as a default value. + if args: + try: + default = type(self)(args[0]) + except: + default = args[0] + self.__dict__['_defaultValue'] = default + else: + self.__dict__['_defaultValue'] = None + self.__dict__['_defaultIsSet'] = len(args) > 0 + + for k in self._items: + if isinstance(self._items[k], dict): + self._items[k] = type(self)(self._items[k]) + + def __setstate__(self, dict): + self.__dict__.update(dict) + + def __getstate__(self): + return self.__dict__.copy() + + def __getattr__(self, name): + """ + This is the method that makes all the magic happen. Search for + 'name' in self._items and return the value if found. If a default + value has been set and 'name' is not found in self._items, return it. + Otherwise raise an AttributeError. + + Example: + >>> d = DictionaryObject({'keys':[1,2], 'values':3, 'x':1}) + >>> d.keys + <bound method DictionaryObject.keys of DictionaryObject({'keys': [1, 2], 'x': 1, 'values': 3})> + >>> d.values + <bound method DictionaryObject.values of DictionaryObject({'keys': [1, 2], 'x': 1, 'values': 3})> + >>> d.x + 1 + >>> d['keys'] + [1, 2] + >>> d['values'] + 3 + """ + if name in self._items: + return self._items[name] + if self._defaultIsSet: + return self._defaultValue + raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) + + def __setattr__(self, name, value): + """ + This class is immutable-by-default. See MutableDictionaryObject. + """ + raise AttributeError("'%s' object does not support assignment" % type(self).__name__) + + def __getitem__(self, name): + return self._items[name] + + def __contains__(self, name): + return name in self._items + + def __len__(self): + return len(self._items) + + def __iter__(self): + return iter(self._items) + + def __repr__(self): + if self._defaultIsSet: + params = "%s, %s" % (repr(self._items), self._defaultValue) + else: + params = repr(self._items) + return "%s(%s)" % (type(self).__name__, params) + + def __cmp__(self, rhs): + if self < rhs: + return -1 + if self > rhs: + return 1 + return 0 + + def __eq__(self, rhs): + val = cmp(self._items, rhs._items) + if 0 == val: + return 0 == cmp(self._defaultValue, rhs._defaultValue) + return 0 == val + + def __ne__(self, rhs): + return not (self == rhs) + + def __lt__(self, rhs): + val = cmp(self._items, rhs._items) + if 0 == val: + return -1 == cmp(self._defaultValue, rhs._defaultValue) + return -1 == val + + def __le__(self, rhs): + return self < rhs or self == rhs + + def __gt__(self, rhs): + return not (self <= rhs) + + def __ge__(self, rhs): + return self > rhs or self == rhs + + def keys(self): + return self._items.keys() + + def values(self): + return self._items.values() + + def asdict(self): + """ + Copy the data back out of here and into a dict. Then return it. + Some libraries may check specifically for dict objects, such + as the json library; so, this makes it convenient to get the data + back out. + + >>> import dictobj + >>> d = {'a':1, 'b':2} + >>> dictobj.DictionaryObject(d).asdict() == d + True + >>> d['c'] = {1:2, 3:4} + >>> dictobj.DictionaryObject(d).asdict() == d + True + """ + items = {} + for name in self._items: + value = self._items[name] + if isinstance(value, DictionaryObject): + items[name] = value.asdict() + else: + items[name] = value + return items + +class MutableDictionaryObject(DictionaryObject): + """ + Slight enhancement of the DictionaryObject allowing one to add + attributes easily, in cases where that functionality is wanted. + + Examples: + >>> d = MutableDictionaryObject({'a':1, 'b':True}, None) + >>> print d.a, d.b, d.c, d.d + 1 True None None + >>> d.c = 3 + >>> del d.a + >>> print d.a, d.b, d.c, d.d + None True 3 None + """ + def __setattr__(self, name, value): + self._items[name] = value + + def __delattr__(self, name): + del self._items[name] + + __setitem__ = __setattr__ + __delitem__ = __delattr__ + diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/util/jstree.py --- /dev/null +++ b/lib/galaxy/util/jstree.py @@ -0,0 +1,173 @@ +import os +import copy +from galaxy.util import dictobj +from collections import namedtuple + +Path = namedtuple('Path', ('path', 'id', 'options')) + + +class Node(dictobj.DictionaryObject): + """ + This class exists as a helper to the JSTree. Its "jsonData" method can + generate sub-tree JSON without putting the logic directly into the JSTree. + + This data structure is only semi-immutable. The JSTree uses a directly + iterative (i.e. no stack is managed) builder pattern to construct a + tree out of paths. Therefore, the children are not known in advance, and + we have to keep the children attribute mutable. + """ + + def __init__(self, path, oid, **kwargs): + """ + kwargs allows users to pass arbitrary information into a Node that + will later be output in jsonData(). It allows for more advanced + configuration than the default path handling that JSTree currently allows. + For example, users may want to pass "attr" or some other valid jsTree options. + + Example: + >>> import jstree + >>> node = jstree.Node('a', None) + >>> print node + Node({'text': 'a', 'children': MutableDictionaryObject({})}) + >>> print node.jsonData() + {'text': 'a'} + + >>> import jstree + >>> node = jstree.Node('a', 1) + >>> print node + Node({'text': 'a', 'children': MutableDictionaryObject({}), 'li_attr': DictionaryObject({'id': 1}), 'id': 1}) + >>> print node.jsonData() + {'text': 'a', 'id': 1, 'li_attr': {'id': 1}} + + >>> import jstree + >>> node = jstree.Node('a', 5, icon="folder", state = {'opened': True}) + >>> print node + Node({'text': 'a', 'id': 5, 'state': DictionaryObject({'opened': True}), 'children': MutableDictionaryObject({}), 'li_attr': DictionaryObject({'id': 5}), 'icon': 'folder'}) + >>> print node.jsonData() + {'text': 'a', 'state': {'opened': True}, 'id': 5, 'li_attr': {'id': 5}, 'icon': 'folder'} + """ + super(Node, self).__init__() + + children = kwargs.get('children', {}) + if len(filter(lambda key: not isinstance(children[key], Node), children)): + raise TypeError( + "One or more children were not instances of '%s'" % Node.__name__) + if 'children' in kwargs: + del kwargs['children'] + self._items['children'] = dictobj.MutableDictionaryObject(children) + + if oid is not None: + li_attr = kwargs.get('li_attr', {}) + li_attr['id'] = oid + kwargs['li_attr'] = li_attr + self._items['id'] = oid + + self._items.update(dictobj.DictionaryObject(**kwargs)) + self._items['text'] = path + + def jsonData(self): + children = [self.children[k].jsonData() for k in sorted(self.children)] + output = {} + for k in self._items: + if 'children' == k: + continue + if isinstance(self._items[k], dictobj.DictionaryObject): + output[k] = self._items[k].asdict() + else: + output[k] = self._items[k] + if len(children): + output['children'] = children + return output + + +class JSTree(dictobj.DictionaryObject): + """ + An immutable dictionary-like object that converts a list of "paths" + into a tree structure suitable for jQuery's jsTree. + """ + + def __init__(self, paths, **kwargs): + """ + Take a list of paths and put them into a tree. Paths with the same prefix should + be at the same level in the tree. + + kwargs may be standard jsTree options used at all levels in the tree. These will be outputted + in the JSON. + + Example (basic usage): + >>> import jstree + >>> paths = [jstree.Path("editor/2012-07/31/.classpath", 1), jstree.Path("editor/2012-07/31/.project", 2)] + >>> t1 = jstree.JSTree(paths) + >>> print t1.jsonData() + [{'text': 'editor/2012-07/31/.classpath', 'id': 1, 'li_attr': {'id': 1}}, {'text': 'editor/2012-07/31/.project', 'id': 2, 'li_attr': {'id': 2}}] + """ + if len(filter(lambda p: not isinstance(p, Path), paths)): + raise TypeError( + "All paths must be instances of '%s'" % Path.__name__) + + super(JSTree, self).__init__() + + root = Node('', None, **kwargs) + for path in sorted(paths): + curr = root + subpaths = path.path.split(os.path.sep) + for i, subpath in enumerate(subpaths): + if subpath not in curr.children: + opt = copy.deepcopy(kwargs) + if len(subpaths) - 1 == i: + oid = path.id + opt.update(path.options) if path.options is not None else None + else: + oid = None + curr.children[subpath] = Node(subpath, oid, **opt) + # oid = path.id if len(subpaths) - 1 == i else None + # curr.children[subpath] = Node(subpath, oid, **kwargs) + curr = curr.children[subpath] + self._items['_root'] = root + + def pretty(self, root=None, depth=0, spacing=2): + """ + Create a "pretty print" represenation of the tree with customized indentation at each + level of the tree. + + Example: + >>> import jstree + >>> paths = [jstree.Path("editor/2012-07/31/.classpath", 1), jstree.Path("editor/2012-07/31/.project", 2)] + >>> print jstree.JSTree(paths).pretty() + / + editor/ + 2012-07/ + 31/ + .classpath + .project + """ + if root is None: + root = self._root + fmt = "%s%s/" if root.children else "%s%s" + s = fmt % (" " * depth * spacing, root.text) + for child in root.children: + child = root.children[child] + s += "\n%s" % self.pretty(child, depth + 1, spacing) + return s + + def jsonData(self): + """ + Returns a copy of the internal tree in a JSON-friendly format, + ready for consumption by jsTree. The data is represented as a + list of dictionaries, each of which are our internal nodes. + + Examples: + >>> import jstree + >>> paths = [jstree.Path("editor/2012-07/31/.classpath", 1), jstree.Path("editor/2012-07/31/.project", 2)] + >>> t = jstree.JSTree(paths) + >>> d = t.jsonData() + >>> print d + [{'data': 'editor', 'children': [{'data': '2012-07', 'children': [{'data': '31', 'children': [{'data': '.classpath', 'metadata': {'id': 1}}, {'data': '.project', 'metadata': {'id': 2}}]}]}]}] + >>> print d[0]['children'][0]['children'][0]['children'][1] + {'data': '.project', 'metadata': {'id': 2}} + >>> print d[0]['children'][0]['children'][0]['children'][1]['data'] + .project + >>> print d[0]['children'][0]['children'][0]['children'][1]['metadata']['id'] + 2 + """ + return [self._root.children[k].jsonData() for k in sorted(self._root.children)] diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/webapps/galaxy/api/folder_contents.py --- a/lib/galaxy/webapps/galaxy/api/folder_contents.py +++ b/lib/galaxy/webapps/galaxy/api/folder_contents.py @@ -4,6 +4,7 @@ from galaxy import web from galaxy import util from galaxy import exceptions +from galaxy.managers import folders from galaxy.web import _future_expose_api as expose_api from galaxy.web import _future_expose_api_anonymous as expose_api_anonymous from sqlalchemy.orm.exc import MultipleResultsFound @@ -19,6 +20,10 @@ Class controls retrieval, creation and updating of folder contents. """ + def __init__( self, app ): + super( FolderContentsController, self ).__init__( app ) + self.folder_manager = folders.FolderManager() + @expose_api_anonymous def index( self, trans, folder_id, **kwd ): """ @@ -46,32 +51,17 @@ """ is_admin = trans.user_is_admin() deleted = kwd.get( 'include_deleted', 'missing' ) + current_user_roles = trans.get_current_user_roles() try: deleted = util.asbool( deleted ) except ValueError: deleted = False - if ( len( folder_id ) == 17 and folder_id.startswith( 'F' ) ): - try: - decoded_folder_id = trans.security.decode_id( folder_id[ 1: ] ) - except TypeError: - raise exceptions.MalformedId( 'Malformed folder id ( %s ) specified, unable to decode.' % str( folder_id ) ) - else: - raise exceptions.MalformedId( 'Malformed folder id ( %s ) specified, unable to decode.' % str( folder_id ) ) - - try: - folder = trans.sa_session.query( trans.app.model.LibraryFolder ).filter( trans.app.model.LibraryFolder.table.c.id == decoded_folder_id ).one() - except MultipleResultsFound: - raise exceptions.InconsistentDatabase( 'Multiple folders with same id found.' ) - except NoResultFound: - raise exceptions.ObjectNotFound( 'Folder with the id provided ( %s ) was not found' % str( folder_id ) ) - except Exception: - raise exceptions.InternalServerError( 'Error loading from the database.' ) - - current_user_roles = trans.get_current_user_roles() + decoded_folder_id = self.folder_manager.cut_and_decode( trans, folder_id ) + folder = self.folder_manager.get( trans, decoded_folder_id ) # Special level of security on top of libraries. - if trans.app.security_agent.can_access_library( current_user_roles, folder.parent_library ): + if trans.app.security_agent.can_access_library( current_user_roles, folder.parent_library ) or is_admin: pass else: if trans.user: @@ -80,29 +70,6 @@ log.warning( "SECURITY: Anonymous user is trying to load restricted folder with ID of %s" % ( decoded_folder_id ) ) raise exceptions.ObjectNotFound( 'Folder with the id provided ( %s ) was not found' % str( folder_id ) ) - # if not ( trans.user_is_admin() or trans.app.security_agent.can_access_library_item( current_user_roles, folder, trans.user ) ): - # log.debug('folder parent id: ' + str(folder.parent_id)) - # if folder.parent_id is None: - # try: - # library = trans.sa_session.query( trans.app.model.Library ).filter( trans.app.model.Library.table.c.root_folder_id == decoded_folder_id ).one() - # except Exception: - # raise exceptions.InternalServerError( 'Error loading from the database.' ) - # if trans.app.security_agent.library_is_unrestricted( library ): - # pass - # else: - # if trans.user: - # log.warning( "SECURITY: User (id: %s) without proper access rights is trying to load folder with ID of %s" % ( trans.user.id, decoded_folder_id ) ) - # else: - # log.warning( "SECURITY: Anonymous user without proper access rights is trying to load folder with ID of %s" % ( decoded_folder_id ) ) - # raise exceptions.ObjectNotFound( 'Folder with the id provided ( %s ) was not found' % str( folder_id ) ) - # else: - # if trans.user: - # log.warning( "SECURITY: User (id: %s) without proper access rights is trying to load folder with ID of %s" % ( trans.user.id, decoded_folder_id ) ) - # else: - # log.debug('PARENT ID IS NOT NONE') - # log.warning( "SECURITY: Anonymous user without proper access rights is trying to load folder with ID of %s" % ( decoded_folder_id ) ) - # raise exceptions.ObjectNotFound( 'Folder with the id provided ( %s ) was not found' % str( folder_id ) ) - folder_contents = [] update_time = '' create_time = '' @@ -161,9 +128,11 @@ # Check whether user can modify the current folder can_modify_folder = is_admin or trans.app.security_agent.can_modify_library_item( current_user_roles, folder ) + parent_library_id = None if folder.parent_library is not None: parent_library_id = trans.security.encode_id( folder.parent_library.id ) + metadata = dict( full_path=full_path, can_add_library_item=can_add_library_item, can_modify_folder=can_modify_folder, diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/webapps/galaxy/api/ftp_files.py --- a/lib/galaxy/webapps/galaxy/api/ftp_files.py +++ b/lib/galaxy/webapps/galaxy/api/ftp_files.py @@ -1,60 +1,127 @@ """ -API operations on ftp files. +API operations on remote files. """ -import logging -from galaxy.web.base.controller import BaseAPIController, url_for -from galaxy import web -import os.path import os import time +import hashlib +from galaxy import web +from galaxy import exceptions +from galaxy.web import _future_expose_api as expose_api +from galaxy.util import jstree +from galaxy.web.base.controller import BaseAPIController, url_for from operator import itemgetter +import logging log = logging.getLogger( __name__ ) class FTPFilesAPIController( BaseAPIController ): - @web.expose_api + + @expose_api def index( self, trans, **kwd ): """ GET /api/ftp_files/ - Displays local files. + + Displays remote files. + + :param target: target to load available datasets from, defaults to ftp + possible values: ftp, userdir + :type target: str + + :param format: requested format of data, defaults to flat + possible values: flat, jstree, ajax + + :returns: list of available files + :rtype: list """ - - # look for ftp files - try: - # initialize response - response = [] - - # identify ftp directory + target = kwd.get( 'target', None ) + format = kwd.get( 'format', None ) + + if target == 'userdir': + user_login = trans.user.email + user_base_dir = trans.app.config.user_library_import_dir + if user_base_dir is None: + raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from user directories.' ) + full_import_dir = os.path.join( user_base_dir, user_login ) + if full_import_dir is not None: + if format == 'jstree': + disable = kwd.get( 'disable', 'folders') + try: + userdir_jstree = self.__create_jstree( full_import_dir, disable ) + response = userdir_jstree.jsonData() + except Exception, exception: + log.debug(str(exception)) + raise exceptions.InternalServerError( 'Could not create tree representation of the given folder: ' + str( full_import_dir ) ) + elif format == 'ajax': + raise exceptions.NotImplemented( 'Not implemented yet. Sorry.' ) + else: + try: + response = self.__load_all_filenames( full_import_dir ) + except Exception, exception: + log.error( 'Could not get user import files: %s', str( exception ), exc_info=True ) + raise exceptions.InternalServerError( 'Could not get the files from your user directory folder.' ) + else: + raise exceptions.InternalServerError( 'Could not get the files from your user directory folder.' ) + else: user_ftp_base_dir = trans.app.config.ftp_upload_dir if user_ftp_base_dir is None: - return [] - - # identify user sub directory - user_ftp_dir = None - if user_ftp_base_dir is not None and trans is not None and trans.user is not None: + raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from FTP directories.' ) + try: + user_ftp_dir = None identifier = trans.app.config.ftp_upload_dir_identifier user_ftp_dir = os.path.join( user_ftp_base_dir, getattr(trans.user, identifier) ) - if user_ftp_dir is None: - return [] + if user_ftp_dir is not None: + response = self.__load_all_filenames( user_ftp_dir ) + else: + raise exceptions.ConfigDoesNotAllowException( 'You do not have an FTP directory named as your login at this Galaxy instance.' ) + except Exception, exception: + log.error( 'Could not get ftp files: %s', str( exception ), exc_info=True ) + raise exceptions.InternalServerError( 'Could not get the files from your FTP folder.' ) + return response - # read directory - if os.path.exists( user_ftp_dir ): - for ( dirpath, dirnames, filenames ) in os.walk( user_ftp_dir ): - for filename in filenames: - path = os.path.relpath( os.path.join( dirpath, filename ), user_ftp_dir ) - statinfo = os.lstat( os.path.join( dirpath, filename ) ) - response.append( dict( path = path, - size = statinfo.st_size, - ctime = time.strftime( "%m/%d/%Y %I:%M:%S %p", time.localtime( statinfo.st_ctime ) ) ) ) - - # sort by path - response = sorted(response, key=itemgetter("path")) + def __load_all_filenames( self, directory ): + """ + Loads recursively all files within the given folder and its + subfolders and returns a flat list. + """ + response = [] + if os.path.exists( directory ): + for ( dirpath, dirnames, filenames ) in os.walk( directory ): + for filename in filenames: + path = os.path.relpath( os.path.join( dirpath, filename ), directory ) + statinfo = os.lstat( os.path.join( dirpath, filename ) ) + response.append( dict( path = path, + size = statinfo.st_size, + ctime = time.strftime( "%m/%d/%Y %I:%M:%S %p", time.localtime( statinfo.st_ctime ) ) ) ) + else: + raise exceptions.ConfigDoesNotAllowException( 'The given directory does not exist.' ) + # sort by path + response = sorted(response, key=itemgetter("path")) + return response - # return - return response - - except Exception, exception: - log.error( 'could not get ftp files: %s', str( exception ), exc_info=True ) - trans.response.status = 500 - return { 'error': str( exception ) } + def __create_jstree( self, directory, disable='folders' ): + """ + Loads recursively all files and folders within the given folder + and its subfolders and returns jstree representation + of its structure. + """ + userdir_jstree = None + jstree_paths = [] + if os.path.exists( directory ): + for ( dirpath, dirnames, filenames ) in os.walk( directory ): + for dirname in dirnames: + dir_path = os.path.relpath( os.path.join( dirpath, dirname ), directory ) + dir_path_hash = hashlib.sha1( dir_path ).hexdigest() + disabled = True if disable == 'folders' else False + jstree_paths.append( jstree.Path( dir_path, dir_path_hash, { 'type': 'folder', 'state': { 'disabled': disabled }, 'li_attr': { 'full_path': dir_path } } ) ) + + for filename in filenames: + file_path = os.path.relpath( os.path.join( dirpath, filename ), directory ) + file_path_hash = hashlib.sha1( file_path ).hexdigest() + disabled = True if disable == 'files' else False + jstree_paths.append( jstree.Path( file_path, file_path_hash, { 'type': 'file', 'state': { 'disabled': disabled }, 'li_attr': { 'full_path': file_path } } ) ) + else: + raise exceptions.ConfigDoesNotAllowException( 'The given directory does not exist.' ) + + userdir_jstree = jstree.JSTree( jstree_paths ) + return userdir_jstree diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/webapps/galaxy/api/lda_datasets.py --- a/lib/galaxy/webapps/galaxy/api/lda_datasets.py +++ b/lib/galaxy/webapps/galaxy/api/lda_datasets.py @@ -1,5 +1,5 @@ """ -API operations on the datasets from library. +API operations on the library datasets. """ import glob import operator @@ -15,6 +15,7 @@ from galaxy import web from galaxy import util from galaxy import exceptions +from galaxy.managers import folders, roles from galaxy.exceptions import ObjectNotFound from paste.httpexceptions import HTTPBadRequest, HTTPInternalServerError from galaxy.web import _future_expose_api as expose_api @@ -24,6 +25,9 @@ from galaxy.web.base.controller import BaseAPIController, UsesVisualizationMixin from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy.orm.exc import NoResultFound +from galaxy.tools.actions import upload_common +from galaxy.util.json import to_json_string, from_json_string + import logging log = logging.getLogger( __name__ ) @@ -31,6 +35,11 @@ class LibraryDatasetsController( BaseAPIController, UsesVisualizationMixin ): + def __init__( self, app ): + super( LibraryDatasetsController, self ).__init__( app ) + self.folder_manager = folders.FolderManager() + self.role_manager = roles.RoleManager() + @expose_api_anonymous def show( self, trans, id, **kwd ): """ @@ -41,8 +50,8 @@ :param id: the encoded id of the dataset to query :type id: an encoded id string + :returns: detailed dataset information from base controller :rtype: dictionary - :returns: detailed dataset information from base controller .. seealso:: :attr:`galaxy.web.base.controller.UsesLibraryMixinItems.get_library_dataset` """ @@ -144,7 +153,6 @@ raise exceptions.InsufficientPermissionsException( 'You do not have proper permission to access permissions.' ) scope = kwd.get( 'scope', None ) - if scope == 'current' or scope is None: return self._get_current_roles( trans, library_dataset ) @@ -394,6 +402,104 @@ rval[ 'folder_id' ] = 'F' + rval[ 'folder_id' ] return rval + @expose_api + def load( self, trans, **kwd ): + """ + Load dataset from the given source into the library. + + :param encoded_folder_id: the encoded id of the folder to import dataset to + :type encoded_folder_id: an encoded id string + :param source: source of the dataset to be loaded + :type source: str + :param link_data: flag whether to link the dataset to data or copy it to Galaxy + :type link_data: bool + :param preserve_dirs: flag whether to preserver directory structure when importing dir + :type preserve_dirs: bool + """ + + kwd[ 'space_to_tab' ] = 'False' + kwd[ 'to_posix_lines' ] = 'True' + kwd[ 'dbkey' ] = '?' + kwd[ 'file_type' ] = 'auto' + + kwd[' link_data_only' ] = 'link_to_files' if util.string_as_bool( kwd.get( 'link_data', False ) ) else 'copy_files' + encoded_folder_id = kwd.get( 'encoded_folder_id', None ) + if encoded_folder_id is not None: + folder_id = self.folder_manager.cut_and_decode( trans, encoded_folder_id ) + else: + raise exceptions.RequestParameterMissingException( 'The required atribute encoded_folder_id is missing.' ) + path = kwd.get( 'path', None) + if path is None: + raise exceptions.RequestParameterMissingException( 'The required atribute path is missing.' ) + folder = self.folder_manager.get( trans, folder_id ) + link_data = util.string_as_bool( kwd.get( 'link_data', False ) ) + + source = kwd.get( 'source', None ) + if source not in [ 'userdir_file', 'userdir_folder' ]: + raise exceptions.RequestParameterMissingException( 'You have to specify "source" parameter. Possible values are "userdir_file" and "userdir_folder". ') + + user_login = trans.user.email + user_base_dir = trans.app.config.user_library_import_dir + if user_base_dir is None: + raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from user directories.' ) + full_dir = os.path.join( user_base_dir, user_login ) + # path_to_root_import_folder = None + if not path.lower().startswith( full_dir.lower() ): + # path_to_root_import_folder = path + path = os.path.join( full_dir, path ) + if not os.path.exists( path ): + raise exceptions.RequestParameterInvalidException( 'Given path does not exist on the host.' ) + if not self.folder_manager.can_add_item( trans, folder ): + raise exceptions.InsufficientPermissionsException( 'You do not have proper permission to add items to the given folder.' ) + + # Set up the traditional tool state/params + tool_id = 'upload1' + tool = trans.app.toolbox.get_tool( tool_id ) + state = tool.new_state( trans ) + errors = tool.update_state( trans, tool.inputs_by_page[ 0 ], state.inputs, kwd ) + tool_params = state.inputs + dataset_upload_inputs = [] + for input_name, input in tool.inputs.iteritems(): + if input.type == "upload_dataset": + dataset_upload_inputs.append( input ) + library_bunch = upload_common.handle_library_params( trans, {}, trans.security.encode_id( folder.id ) ) + abspath_datasets = [] + kwd[ 'filesystem_paths' ] = path + params = util.Params( kwd ) + # file only + if source == "userdir_file": + file = os.path.abspath( path ) + abspath_datasets.append( trans.webapp.controllers[ 'library_common' ].make_library_uploaded_dataset( + trans, 'api', params, os.path.basename( file ), file, 'server_dir', library_bunch ) ) + # whole folder + if source == "userdir_folder": + # import_folder_root = [next(part for part in path.split(os.path.sep) if part) for path in [os.path.splitdrive(path_to_root_import_folder)[1]]] + # new_folder = self.folder_manager.create( trans, folder_id, import_folder_root[0] ) + + uploaded_datasets_bunch = trans.webapp.controllers[ 'library_common' ].get_path_paste_uploaded_datasets( + trans, 'api', params, library_bunch, 200, '' ) + + uploaded_datasets = uploaded_datasets_bunch[0] + if uploaded_datasets is None: + # TODO no files found - only create folders + return False + + for ud in uploaded_datasets: + ud.path = os.path.abspath( ud.path ) + abspath_datasets.append( ud ) + + json_file_path = upload_common.create_paramfile( trans, abspath_datasets ) + data_list = [ ud.data for ud in abspath_datasets ] + job, output = upload_common.create_job( trans, tool_params, tool, json_file_path, data_list, folder=folder ) + # HACK: Prevent outputs_to_working_directory from overwriting inputs when "linking" + job.add_parameter( 'link_data_only', to_json_string( kwd.get( 'link_data_only', 'copy_files' ) ) ) + job.add_parameter( 'uuid', to_json_string( kwd.get( 'uuid', None ) ) ) + trans.sa_session.add( job ) + trans.sa_session.flush() + job_dict = job.to_dict() + job_dict[ 'id' ] = trans.security.encode_id( job_dict[ 'id' ] ) + return job_dict + @web.expose def download( self, trans, format, **kwd ): """ diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 lib/galaxy/webapps/galaxy/buildapp.py --- a/lib/galaxy/webapps/galaxy/buildapp.py +++ b/lib/galaxy/webapps/galaxy/buildapp.py @@ -258,6 +258,12 @@ action='show', conditions=dict( method=[ "GET" ] ) ) + webapp.mapper.connect( 'load_ld', + '/api/libraries/datasets/', + controller='lda_datasets', + action='load', + conditions=dict( method=[ "POST" ] ) ) + webapp.mapper.connect( 'show_version_of_ld_item', '/api/libraries/datasets/:encoded_dataset_id/versions/:encoded_ldda_id', controller='lda_datasets', diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 static/images/jstree/32px.png Binary file static/images/jstree/32px.png has changed diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 static/images/jstree/40px.png Binary file static/images/jstree/40px.png has changed diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 static/images/jstree/throbber.gif Binary file static/images/jstree/throbber.gif has changed diff -r 02852a8e49e23cd1090f798e99702057fa24bc1d -r cadad49537de2edd2128be108d0d631f35722ab5 static/scripts/galaxy.library.js --- a/static/scripts/galaxy.library.js +++ b/static/scripts/galaxy.library.js @@ -47,7 +47,8 @@ "folders/:folder_id/datasets/:dataset_id" : "dataset_detail", "folders/:folder_id/datasets/:dataset_id/permissions" : "dataset_permissions", "folders/:folder_id/datasets/:dataset_id/versions/:ldda_id" : "dataset_version", - "folders/:folder_id/download/:format" : "download" + "folders/:folder_id/download/:format" : "download", + "folders/:folder_id/import/:source" : "import_datasets" }, back: function() { @@ -147,6 +148,15 @@ } Galaxy.libraries.folderView = new mod_library_folder_view.FolderView({id: folder_id, show_permissions: true}); }); + this.library_router.on('route:import_datasets', function(folder_id, source){ + if (Galaxy.libraries.folderToolbarView && Galaxy.libraries.folderListView){ + Galaxy.libraries.folderToolbarView.showImportModal({source:source}); + } else { + Galaxy.libraries.folderToolbarView = new mod_foldertoolbar_view.FolderToolbarView({id: folder_id}); + Galaxy.libraries.folderListView = new mod_folderlist_view.FolderListView({id: folder_id}); + Galaxy.libraries.folderToolbarView.showImportModal({source: source}); + } + }); Backbone.history.start({pushState: false}); } This diff is so big that we needed to truncate the remainder. https://bitbucket.org/galaxy/galaxy-central/commits/ecf83c3a2d03/ Changeset: ecf83c3a2d03 User: martenson Date: 2014-09-08 18:45:37+00:00 Summary: adding compressed version of jstree jquery plugin Affected #: 1 file diff -r cadad49537de2edd2128be108d0d631f35722ab5 -r ecf83c3a2d0383c74e30dca41b602854326c7ee7 static/scripts/packed/libs/jquery/jstree.js --- /dev/null +++ b/static/scripts/packed/libs/jquery/jstree.js @@ -0,0 +1,60 @@ +(function(a){if(typeof define==="function"&&define.amd){}else{if(typeof exports==="object"){a(require("jquery"))}else{a(jQuery)}}}(function(i,e){ +/* + * jsTree 3.0.3 + * http://jstree.com/ + * + * Copyright (c) 2014 Ivan Bozhanov (http://vakata.com) + * + * Licensed same as jquery - under the terms of the MIT License + * http://www.opensource.org/licenses/mit-license.php + */ +/* + * if using jslint please allow for the jQuery global and use following options: + * jslint: browser: true, ass: true, bitwise: true, continue: true, nomen: true, plusplus: true, regexp: true, unparam: true, todo: true, white: true + */ +if(i.jstree){return}var c=0,d=false,k=false,j=false,m=[],a=i("script:last").attr("src"),l=document,o=l.createElement("LI"),g,f;o.setAttribute("role","treeitem");g=l.createElement("I");g.className="jstree-icon jstree-ocl";o.appendChild(g);g=l.createElement("A");g.className="jstree-anchor";g.setAttribute("href","#");f=l.createElement("I");f.className="jstree-icon jstree-themeicon";g.appendChild(f);o.appendChild(g);g=f=null;i.jstree={version:"3.0.3",defaults:{plugins:[]},plugins:{},path:a&&a.indexOf("/")!==-1?a.replace(/\/[^\/]+$/,""):"",idregex:/[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%]/g};i.jstree.create=function(s,p){var r=new i.jstree.core(++c),q=p;p=i.extend(true,{},i.jstree.defaults,p);if(q&&q.plugins){p.plugins=q.plugins}i.each(p.plugins,function(u,t){if(u!=="core"){r=r.plugin(t,p[t])}});r.init(s,p);return r};i.jstree.core=function(p){this._id=p;this._cnt=0;this._wrk=null;this._data={core:{themes:{name:false,dots:false,icons:false},selected:[],last_error:{},working:false,worker_queue:[]}}};i.jstree.reference=function(r){var p=null,q=null;if(r&&r.id){r=r.id}if(!q||!q.length){try{q=i(r)}catch(s){}}if(!q||!q.length){try{q=i("#"+r.replace(i.jstree.idregex,"\\$&"))}catch(s){}}if(q&&q.length&&(q=q.closest(".jstree")).length&&(q=q.data("jstree"))){p=q}else{i(".jstree").each(function(){var t=i(this).data("jstree");if(t&&t._model.data[r]){p=t;return false}})}return p};i.fn.jstree=function(q){var s=(typeof q==="string"),r=Array.prototype.slice.call(arguments,1),p=null;this.each(function(){var t=i.jstree.reference(this),u=s&&t?t[q]:null;p=s&&u?u.apply(t,r):null;if(!t&&!s&&(q===e||i.isPlainObject(q))){i(this).data("jstree",new i.jstree.create(this,q))}if((t&&!s)||q===true){p=t||false}if(p!==null&&p!==e){return false}});return p!==null&&p!==e?p:this};i.expr[":"].jstree=i.expr.createPseudo(function(p){return function(q){return i(q).hasClass("jstree")&&i(q).data("jstree")!==e}});i.jstree.defaults.core={data:false,strings:false,check_callback:false,error:i.noop,animation:200,multiple:true,themes:{name:false,url:false,dir:false,dots:true,icons:true,stripes:false,variant:false,responsive:false},expand_selected_onload:true,worker:true,force_text:false};i.jstree.core.prototype={plugin:function(r,q){var p=i.jstree.plugins[r];if(p){this._data[r]={};p.prototype=this;return new p(q,this)}return this},init:function(q,p){this._model={data:{"#":{id:"#",parent:null,parents:[],children:[],children_d:[],state:{loaded:false}}},changed:[],force_full_redraw:false,redraw_timeout:false,default_state:{loaded:true,opened:false,selected:false,disabled:false}};this.element=i(q).addClass("jstree jstree-"+this._id);this.settings=p;this.element.bind("destroyed",i.proxy(this.teardown,this));this._data.core.ready=false;this._data.core.loaded=false;this._data.core.rtl=(this.element.css("direction")==="rtl");this.element[this._data.core.rtl?"addClass":"removeClass"]("jstree-rtl");this.element.attr("role","tree");this.bind();this.trigger("init");this._data.core.original_container_html=this.element.find(" > ul > li").clone(true);this._data.core.original_container_html.find("li").addBack().contents().filter(function(){return this.nodeType===3&&(!this.nodeValue||/^\s+$/.test(this.nodeValue))}).remove();this.element.html("<ul class='jstree-container-ul jstree-children'><li class='jstree-initial-node jstree-loading jstree-leaf jstree-last'><i class='jstree-icon jstree-ocl'></i><a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>"+this.get_string("Loading ...")+"</a></li></ul>");this._data.core.li_height=this.get_container_ul().children("li:eq(0)").height()||24;this.trigger("loading");this.load_node("#")},destroy:function(p){if(!p){this.element.empty()}this.element.unbind("destroyed",this.teardown);this.teardown()},teardown:function(){this.unbind();this.element.removeClass("jstree").removeData("jstree").find("[class^='jstree']").addBack().attr("class",function(){return this.className.replace(/jstree[^ ]*|$/ig,"")});this.element=null},bind:function(){this.element.on("dblclick.jstree",function(){if(document.selection&&document.selection.empty){document.selection.empty()}else{if(window.getSelection){var p=window.getSelection();try{p.removeAllRanges();p.collapse()}catch(q){}}}}).on("click.jstree",".jstree-ocl",i.proxy(function(p){this.toggle_node(p.target)},this)).on("click.jstree",".jstree-anchor",i.proxy(function(p){p.preventDefault();i(p.currentTarget).focus();this.activate_node(p.currentTarget,p)},this)).on("keydown.jstree",".jstree-anchor",i.proxy(function(p){if(p.target.tagName==="INPUT"){return true}var q=null;switch(p.which){case 13:case 32:p.type="click";i(p.currentTarget).trigger(p);break;case 37:p.preventDefault();if(this.is_open(p.currentTarget)){this.close_node(p.currentTarget)}else{q=this.get_prev_dom(p.currentTarget);if(q&&q.length){q.children(".jstree-anchor").focus()}}break;case 38:p.preventDefault();q=this.get_prev_dom(p.currentTarget);if(q&&q.length){q.children(".jstree-anchor").focus()}break;case 39:p.preventDefault();if(this.is_closed(p.currentTarget)){this.open_node(p.currentTarget,function(r){this.get_node(r,true).children(".jstree-anchor").focus()})}else{q=this.get_next_dom(p.currentTarget);if(q&&q.length){q.children(".jstree-anchor").focus()}}break;case 40:p.preventDefault();q=this.get_next_dom(p.currentTarget);if(q&&q.length){q.children(".jstree-anchor").focus()}break;case 46:p.preventDefault();q=this.get_node(p.currentTarget);if(q&&q.id&&q.id!=="#"){q=this.is_selected(q)?this.get_selected():q}break;case 113:p.preventDefault();q=this.get_node(p.currentTarget); +/* + if(o && o.id && o.id !== '#') { + // this.edit(o); + } + */ +break;default:break}},this)).on("load_node.jstree",i.proxy(function(t,s){if(s.status){if(s.node.id==="#"&&!this._data.core.loaded){this._data.core.loaded=true;this.trigger("loaded")}if(!this._data.core.ready&&!this.get_container_ul().find(".jstree-loading:eq(0)").length){this._data.core.ready=true;if(this._data.core.selected.length){if(this.settings.core.expand_selected_onload){var r=[],q,p;for(q=0,p=this._data.core.selected.length;q<p;q++){r=r.concat(this._model.data[this._data.core.selected[q]].parents)}r=i.vakata.array_unique(r);for(q=0,p=r.length;q<p;q++){this.open_node(r[q],false,0)}}this.trigger("changed",{action:"ready",selected:this._data.core.selected})}setTimeout(i.proxy(function(){this.trigger("ready")},this),0)}}},this)).on("init.jstree",i.proxy(function(){var p=this.settings.core.themes;this._data.core.themes.dots=p.dots;this._data.core.themes.stripes=p.stripes;this._data.core.themes.icons=p.icons;this.set_theme(p.name||"default",p.url);this.set_theme_variant(p.variant)},this)).on("loading.jstree",i.proxy(function(){this[this._data.core.themes.dots?"show_dots":"hide_dots"]();this[this._data.core.themes.icons?"show_icons":"hide_icons"]();this[this._data.core.themes.stripes?"show_stripes":"hide_stripes"]()},this)).on("blur.jstree",".jstree-anchor",i.proxy(function(p){i(p.currentTarget).filter(".jstree-hovered").mouseleave()},this)).on("focus.jstree",".jstree-anchor",i.proxy(function(p){this.element.find(".jstree-hovered").not(p.currentTarget).mouseleave();i(p.currentTarget).mouseenter()},this)).on("mouseenter.jstree",".jstree-anchor",i.proxy(function(p){this.hover_node(p.currentTarget)},this)).on("mouseleave.jstree",".jstree-anchor",i.proxy(function(p){this.dehover_node(p.currentTarget)},this))},unbind:function(){this.element.off(".jstree");i(document).off(".jstree-"+this._id)},trigger:function(p,q){if(!q){q={}}q.instance=this;this.element.triggerHandler(p.replace(".jstree","")+".jstree",q)},get_container:function(){return this.element},get_container_ul:function(){return this.element.children(".jstree-children:eq(0)")},get_string:function(q){var p=this.settings.core.strings;if(i.isFunction(p)){return p.call(this,q)}if(p&&p[q]){return p[q]}return q},_firstChild:function(p){p=p?p.firstChild:null;while(p!==null&&p.nodeType!==1){p=p.nextSibling}return p},_nextSibling:function(p){p=p?p.nextSibling:null;while(p!==null&&p.nodeType!==1){p=p.nextSibling}return p},_previousSibling:function(p){p=p?p.previousSibling:null;while(p!==null&&p.nodeType!==1){p=p.previousSibling}return p},get_node:function(r,p){if(r&&r.id){r=r.id}var s;try{if(this._model.data[r]){r=this._model.data[r]}else{if(((s=i(r,this.element)).length||(s=i("#"+r.replace(i.jstree.idregex,"\\$&"),this.element)).length)&&this._model.data[s.closest(".jstree-node").attr("id")]){r=this._model.data[s.closest(".jstree-node").attr("id")]}else{if((s=i(r,this.element)).length&&s.hasClass("jstree")){r=this._model.data["#"]}else{return false}}}if(p){r=r.id==="#"?this.element:i("#"+r.id.replace(i.jstree.idregex,"\\$&"),this.element)}return r}catch(q){return false}},get_path:function(v,t,s){v=v.parents?v:this.get_node(v);if(!v||v.id==="#"||!v.parents){return false}var r,q,u=[];u.push(s?v.id:v.text);for(r=0,q=v.parents.length;r<q;r++){u.push(s?v.parents[r]:this.get_text(v.parents[r]))}u=u.reverse().slice(1);return t?u.join(t):u},get_next_dom:function(r,p){var q;r=this.get_node(r,true);if(r[0]===this.element[0]){q=this._firstChild(this.get_container_ul()[0]);return q?i(q):false}if(!r||!r.length){return false}if(p){q=this._nextSibling(r[0]);return q?i(q):false}if(r.hasClass("jstree-open")){q=this._firstChild(r.children(".jstree-children")[0]);return q?i(q):false}if((q=this._nextSibling(r[0]))!==null){return i(q)}return r.parentsUntil(".jstree",".jstree-node").next(".jstree-node").eq(0)},get_prev_dom:function(r,p){var q;r=this.get_node(r,true);if(r[0]===this.element[0]){q=this.get_container_ul()[0].lastChild;return q?i(q):false}if(!r||!r.length){return false}if(p){q=this._previousSibling(r[0]);return q?i(q):false}if((q=this._previousSibling(r[0]))!==null){r=i(q);while(r.hasClass("jstree-open")){r=r.children(".jstree-children:eq(0)").children(".jstree-node:last")}return r}q=r[0].parentNode.parentNode;return q&&q.className&&q.className.indexOf("jstree-node")!==-1?i(q):false},get_parent:function(p){p=this.get_node(p);if(!p||p.id==="#"){return false}return p.parent},get_children_dom:function(p){p=this.get_node(p,true);if(p[0]===this.element[0]){return this.get_container_ul().children(".jstree-node")}if(!p||!p.length){return false}return p.children(".jstree-children").children(".jstree-node")},is_parent:function(p){p=this.get_node(p);return p&&(p.state.loaded===false||p.children.length>0)},is_loaded:function(p){p=this.get_node(p);return p&&p.state.loaded},is_loading:function(p){p=this.get_node(p);return p&&p.state&&p.state.loading},is_open:function(p){p=this.get_node(p);return p&&p.state.opened},is_closed:function(p){p=this.get_node(p);return p&&this.is_parent(p)&&!p.state.opened},is_leaf:function(p){return !this.is_parent(p)},load_node:function(t,v){var q,p,s,r,u;if(i.isArray(t)){this._load_nodes(t.slice(),v);return true}t=this.get_node(t);if(!t){if(v){v.call(this,t,false)}return false}if(t.state.loaded){t.state.loaded=false;for(q=0,p=t.children_d.length;q<p;q++){for(s=0,r=t.parents.length;s<r;s++){this._model.data[t.parents[s]].children_d=i.vakata.array_remove_item(this._model.data[t.parents[s]].children_d,t.children_d[q])}if(this._model.data[t.children_d[q]].state.selected){u=true;this._data.core.selected=i.vakata.array_remove_item(this._data.core.selected,t.children_d[q])}delete this._model.data[t.children_d[q]]}t.children=[];t.children_d=[];if(u){this.trigger("changed",{action:"load_node",node:t,selected:this._data.core.selected})}}t.state.loading=true;this.get_node(t,true).addClass("jstree-loading");this._load_node(t,i.proxy(function(w){t=this._model.data[t.id];t.state.loading=false;t.state.loaded=w;var x=this.get_node(t,true);if(t.state.loaded&&!t.children.length&&x&&x.length&&!x.hasClass("jstree-leaf")){x.removeClass("jstree-closed jstree-open").addClass("jstree-leaf")}x.removeClass("jstree-loading");this.trigger("load_node",{node:t,status:w});if(v){v.call(this,t,w)}},this));return true},_load_nodes:function(q,x,u){var v=true,w=function(){this._load_nodes(q,x,true)},p=this._model.data,t,s;for(t=0,s=q.length;t<s;t++){if(p[q[t]]&&(!p[q[t]].state.loaded||!u)){if(!this.is_loading(q[t])){this.load_node(q[t],w)}v=false}}if(v){if(x&&!x.done){x.call(this,q);x.done=true}}},_load_node:function(r,u){var q=this.settings.core.data,p;if(!q){if(r.id==="#"){return this._append_html_data(r,this._data.core.original_container_html.clone(true),function(s){u.call(this,s)})}else{return u.call(this,false)}}if(i.isFunction(q)){return q.call(this,r,i.proxy(function(s){if(s===false){u.call(this,false)}this[typeof s==="string"?"_append_html_data":"_append_json_data"](r,typeof s==="string"?i(s):s,function(t){u.call(this,t)})},this))}if(typeof q==="object"){if(q.url){q=i.extend(true,{},q);if(i.isFunction(q.url)){q.url=q.url.call(this,r)}if(i.isFunction(q.data)){q.data=q.data.call(this,r)}return i.ajax(q).done(i.proxy(function(y,v,s){var w=s.getResponseHeader("Content-Type");if(w.indexOf("json")!==-1||typeof y==="object"){return this._append_json_data(r,y,function(t){u.call(this,t)})}if(w.indexOf("html")!==-1||typeof y==="string"){return this._append_html_data(r,i(y),function(t){u.call(this,t)})}this._data.core.last_error={error:"ajax",plugin:"core",id:"core_04",reason:"Could not load node",data:JSON.stringify({id:r.id,xhr:s})};this.settings.core.error.call(this,this._data.core.last_error);return u.call(this,false)},this)).fail(i.proxy(function(s){u.call(this,false);this._data.core.last_error={error:"ajax",plugin:"core",id:"core_04",reason:"Could not load node",data:JSON.stringify({id:r.id,xhr:s})};this.settings.core.error.call(this,this._data.core.last_error)},this))}p=(i.isArray(q)||i.isPlainObject(q))?JSON.parse(JSON.stringify(q)):q;if(r.id==="#"){return this._append_json_data(r,p,function(s){u.call(this,s)})}else{this._data.core.last_error={error:"nodata",plugin:"core",id:"core_05",reason:"Could not load node",data:JSON.stringify({id:r.id})};this.settings.core.error.call(this,this._data.core.last_error);return u.call(this,false)}}if(typeof q==="string"){if(r.id==="#"){return this._append_html_data(r,i(q),function(s){u.call(this,s)})}else{this._data.core.last_error={error:"nodata",plugin:"core",id:"core_06",reason:"Could not load node",data:JSON.stringify({id:r.id})};this.settings.core.error.call(this,this._data.core.last_error);return u.call(this,false)}}return u.call(this,false)},_node_changed:function(p){p=this.get_node(p);if(p){this._model.changed.push(p.id)}},_append_html_data:function(v,y,t){v=this.get_node(v);v.children=[];v.children_d=[];var B=y.is("ul")?y.children():y,A=v.id,D=[],z=[],r=this._model.data,q=r[A],C=this._data.core.selected.length,x,w,u;B.each(i.proxy(function(s,p){x=this._parse_model_from_html(i(p),A,q.parents.concat());if(x){D.push(x);z.push(x);if(r[x].children_d.length){z=z.concat(r[x].children_d)}}},this));q.children=D;q.children_d=z;for(w=0,u=q.parents.length;w<u;w++){r[q.parents[w]].children_d=r[q.parents[w]].children_d.concat(z)}this.trigger("model",{nodes:z,parent:A});if(A!=="#"){this._node_changed(A);this.redraw()}else{this.get_container_ul().children(".jstree-initial-node").remove();this.redraw(true)}if(this._data.core.selected.length!==C){this.trigger("changed",{action:"model",selected:this._data.core.selected})}t.call(this,true)},_append_json_data:function(x,u,p){x=this.get_node(x);x.children=[];x.children_d=[];if(u.d){u=u.d;if(typeof u==="string"){u=JSON.parse(u)}}if(!i.isArray(u)){u=[u]}var r=null,s={df:this._model.default_state,dat:u,par:x.id,m:this._model.data,t_id:this._id,t_cnt:this._cnt,sel:this._data.core.selected},t=function(P,y){if(P.data){P=P.data}var K=P.dat,D=P.par,w=[],z=[],E=[],L=P.df,B=P.t_id,C=P.t_cnt,G=P.m,F=G[D],H=P.sel,N,J,I,M,O=function(X,R,Q){if(!Q){Q=[]}else{Q=Q.concat()}if(R){Q.unshift(R)}var S=X.id.toString(),V,T,Y,W,U={id:S,text:X.text||"",icon:X.icon!==y?X.icon:true,parent:R,parents:Q,children:X.children||[],children_d:X.children_d||[],data:X.data,state:{},li_attr:{id:false},a_attr:{href:"#"},original:false};for(V in L){if(L.hasOwnProperty(V)){U.state[V]=L[V]}}if(X&&X.data&&X.data.jstree&&X.data.jstree.icon){U.icon=X.data.jstree.icon}if(X&&X.data){U.data=X.data;if(X.data.jstree){for(V in X.data.jstree){if(X.data.jstree.hasOwnProperty(V)){U.state[V]=X.data.jstree[V]}}}}if(X&&typeof X.state==="object"){for(V in X.state){if(X.state.hasOwnProperty(V)){U.state[V]=X.state[V]}}}if(X&&typeof X.li_attr==="object"){for(V in X.li_attr){if(X.li_attr.hasOwnProperty(V)){U.li_attr[V]=X.li_attr[V]}}}if(!U.li_attr.id){U.li_attr.id=S}if(X&&typeof X.a_attr==="object"){for(V in X.a_attr){if(X.a_attr.hasOwnProperty(V)){U.a_attr[V]=X.a_attr[V]}}}if(X&&X.children&&X.children===true){U.state.loaded=false;U.children=[];U.children_d=[]}G[U.id]=U;for(V=0,T=U.children.length;V<T;V++){Y=O(G[U.children[V]],U.id,Q);W=G[Y];U.children_d.push(Y);if(W.children_d.length){U.children_d=U.children_d.concat(W.children_d)}}delete X.data;delete X.children;G[U.id].original=X;if(U.state.selected){E.push(U.id)}return U.id},A=function(X,R,Q){if(!Q){Q=[]}else{Q=Q.concat()}if(R){Q.unshift(R)}var S=false,V,T,Y,W,U;do{S="j"+B+"_"+(++C)}while(G[S]);U={id:false,text:typeof X==="string"?X:"",icon:typeof X==="object"&&X.icon!==y?X.icon:true,parent:R,parents:Q,children:[],children_d:[],data:null,state:{},li_attr:{id:false},a_attr:{href:"#"},original:false};for(V in L){if(L.hasOwnProperty(V)){U.state[V]=L[V]}}if(X&&X.id){U.id=X.id.toString()}if(X&&X.text){U.text=X.text}if(X&&X.data&&X.data.jstree&&X.data.jstree.icon){U.icon=X.data.jstree.icon}if(X&&X.data){U.data=X.data;if(X.data.jstree){for(V in X.data.jstree){if(X.data.jstree.hasOwnProperty(V)){U.state[V]=X.data.jstree[V]}}}}if(X&&typeof X.state==="object"){for(V in X.state){if(X.state.hasOwnProperty(V)){U.state[V]=X.state[V]}}}if(X&&typeof X.li_attr==="object"){for(V in X.li_attr){if(X.li_attr.hasOwnProperty(V)){U.li_attr[V]=X.li_attr[V]}}}if(U.li_attr.id&&!U.id){U.id=U.li_attr.id.toString()}if(!U.id){U.id=S}if(!U.li_attr.id){U.li_attr.id=U.id}if(X&&typeof X.a_attr==="object"){for(V in X.a_attr){if(X.a_attr.hasOwnProperty(V)){U.a_attr[V]=X.a_attr[V]}}}if(X&&X.children&&X.children.length){for(V=0,T=X.children.length;V<T;V++){Y=A(X.children[V],U.id,Q);W=G[Y];U.children.push(Y);if(W.children_d.length){U.children_d=U.children_d.concat(W.children_d)}}U.children_d=U.children_d.concat(U.children)}if(X&&X.children&&X.children===true){U.state.loaded=false;U.children=[];U.children_d=[]}delete X.data;delete X.children;U.original=X;G[U.id]=U;if(U.state.selected){E.push(U.id)}return U.id};if(K.length&&K[0].id!==y&&K[0].parent!==y){for(J=0,I=K.length;J<I;J++){if(!K[J].children){K[J].children=[]}G[K[J].id.toString()]=K[J]}for(J=0,I=K.length;J<I;J++){G[K[J].parent.toString()].children.push(K[J].id.toString());F.children_d.push(K[J].id.toString())}for(J=0,I=F.children.length;J<I;J++){N=O(G[F.children[J]],D,F.parents.concat());z.push(N);if(G[N].children_d.length){z=z.concat(G[N].children_d)}}for(J=0,I=F.parents.length;J<I;J++){G[F.parents[J]].children_d=G[F.parents[J]].children_d.concat(z)}M={cnt:C,mod:G,sel:H,par:D,dpc:z,add:E}}else{for(J=0,I=K.length;J<I;J++){N=A(K[J],D,F.parents.concat());if(N){w.push(N);z.push(N);if(G[N].children_d.length){z=z.concat(G[N].children_d)}}}F.children=w;F.children_d=z;for(J=0,I=F.parents.length;J<I;J++){G[F.parents[J]].children_d=G[F.parents[J]].children_d.concat(z)}M={cnt:C,mod:G,sel:H,par:D,dpc:z,add:E}}return M},q=function(z,E){this._cnt=z.cnt;this._model.data=z.mod;if(E){var B,A,y=z.add,D=z.sel,C=this._data.core.selected.slice(),w=this._model.data;if(D.length!==C.length||i.vakata.array_unique(D.concat(C)).length!==D.length){for(B=0,A=D.length;B<A;B++){if(i.inArray(D[B],y)===-1&&i.inArray(D[B],C)===-1){w[D[B]].state.selected=false}}for(B=0,A=C.length;B<A;B++){if(i.inArray(C[B],D)===-1){w[C[B]].state.selected=true}}}}if(z.add.length){this._data.core.selected=this._data.core.selected.concat(z.add)}this.trigger("model",{nodes:z.dpc,parent:z.par});if(z.par!=="#"){this._node_changed(z.par);this.redraw()}else{this.redraw(true)}if(z.add.length){this.trigger("changed",{action:"model",selected:this._data.core.selected})}p.call(this,true)};if(this.settings.core.worker&&window.Blob&&window.URL&&window.Worker){try{if(this._wrk===null){this._wrk=window.URL.createObjectURL(new window.Blob(["self.onmessage = "+t.toString().replace(/return ([^;}]+)[\s;}]+$/,"postMessage($1);}")],{type:"text/javascript"}))}r=new window.Worker(this._wrk);r.onmessage=i.proxy(function(w){q.call(this,w.data,true);this._data.core.working=false;if(this._data.core.worker_queue.length){this._append_json_data.apply(this,this._data.core.worker_queue.shift())}},this);if(!this._data.core.working){this._data.core.working=true;r.postMessage(s)}else{this._data.core.worker_queue.push([x,u,p])}}catch(v){q.call(this,t(s),false)}}else{q.call(this,t(s),false)}},_parse_model_from_html:function(y,r,q){if(!q){q=[]}else{q=[].concat(q)}if(r){q.unshift(r)}var z,x,s=this._model.data,v={id:false,text:false,icon:true,parent:r,parents:q,children:[],children_d:[],data:null,state:{},li_attr:{id:false},a_attr:{href:"#"},original:false},w,u,t;for(w in this._model.default_state){if(this._model.default_state.hasOwnProperty(w)){v.state[w]=this._model.default_state[w]}}u=i.vakata.attributes(y,true);i.each(u,function(A,p){p=i.trim(p);if(!p.length){return true}v.li_attr[A]=p;if(A==="id"){v.id=p.toString()}});u=y.children("a").eq(0);if(u.length){u=i.vakata.attributes(u,true);i.each(u,function(A,p){p=i.trim(p);if(p.length){v.a_attr[A]=p}})}u=y.children("a:eq(0)").length?y.children("a:eq(0)").clone():y.clone();u.children("ins, i, ul").remove();u=u.html();u=i("<div />").html(u);v.text=this.settings.core.force_text?u.text():u.html();u=y.data();v.data=u?i.extend(true,{},u):null;v.state.opened=y.hasClass("jstree-open");v.state.selected=y.children("a").hasClass("jstree-clicked");v.state.disabled=y.children("a").hasClass("jstree-disabled");if(v.data&&v.data.jstree){for(w in v.data.jstree){if(v.data.jstree.hasOwnProperty(w)){v.state[w]=v.data.jstree[w]}}}u=y.children("a").children(".jstree-themeicon");if(u.length){v.icon=u.hasClass("jstree-themeicon-hidden")?false:u.attr("rel")}if(v.state.icon){v.icon=v.state.icon}u=y.children("ul").children("li");do{t="j"+this._id+"_"+(++this._cnt)}while(s[t]);v.id=v.li_attr.id?v.li_attr.id.toString():t;if(u.length){u.each(i.proxy(function(A,p){z=this._parse_model_from_html(i(p),v.id,q);x=this._model.data[z];v.children.push(z);if(x.children_d.length){v.children_d=v.children_d.concat(x.children_d)}},this));v.children_d=v.children_d.concat(v.children)}else{if(y.hasClass("jstree-closed")){v.state.loaded=false}}if(v.li_attr["class"]){v.li_attr["class"]=v.li_attr["class"].replace("jstree-closed","").replace("jstree-open","")}if(v.a_attr["class"]){v.a_attr["class"]=v.a_attr["class"].replace("jstree-clicked","").replace("jstree-disabled","")}s[v.id]=v;if(v.state.selected){this._data.core.selected.push(v.id)}return v.id},_parse_model_from_flat_json:function(y,r,q){if(!q){q=[]}else{q=q.concat()}if(r){q.unshift(r)}var t=y.id.toString(),s=this._model.data,A=this._model.default_state,w,u,z,x,v={id:t,text:y.text||"",icon:y.icon!==e?y.icon:true,parent:r,parents:q,children:y.children||[],children_d:y.children_d||[],data:y.data,state:{},li_attr:{id:false},a_attr:{href:"#"},original:false};for(w in A){if(A.hasOwnProperty(w)){v.state[w]=A[w]}}if(y&&y.data&&y.data.jstree&&y.data.jstree.icon){v.icon=y.data.jstree.icon}if(y&&y.data){v.data=y.data;if(y.data.jstree){for(w in y.data.jstree){if(y.data.jstree.hasOwnProperty(w)){v.state[w]=y.data.jstree[w]}}}}if(y&&typeof y.state==="object"){for(w in y.state){if(y.state.hasOwnProperty(w)){v.state[w]=y.state[w]}}}if(y&&typeof y.li_attr==="object"){for(w in y.li_attr){if(y.li_attr.hasOwnProperty(w)){v.li_attr[w]=y.li_attr[w]}}}if(!v.li_attr.id){v.li_attr.id=t}if(y&&typeof y.a_attr==="object"){for(w in y.a_attr){if(y.a_attr.hasOwnProperty(w)){v.a_attr[w]=y.a_attr[w]}}}if(y&&y.children&&y.children===true){v.state.loaded=false;v.children=[];v.children_d=[]}s[v.id]=v;for(w=0,u=v.children.length;w<u;w++){z=this._parse_model_from_flat_json(s[v.children[w]],v.id,q);x=s[z];v.children_d.push(z);if(x.children_d.length){v.children_d=v.children_d.concat(x.children_d)}}delete y.data;delete y.children;s[v.id].original=y;if(v.state.selected){this._data.core.selected.push(v.id)}return v.id},_parse_model_from_json:function(y,r,q){if(!q){q=[]}else{q=q.concat()}if(r){q.unshift(r)}var t=false,w,u,z,x,s=this._model.data,A=this._model.default_state,v;do{t="j"+this._id+"_"+(++this._cnt)}while(s[t]);v={id:false,text:typeof y==="string"?y:"",icon:typeof y==="object"&&y.icon!==e?y.icon:true,parent:r,parents:q,children:[],children_d:[],data:null,state:{},li_attr:{id:false},a_attr:{href:"#"},original:false};for(w in A){if(A.hasOwnProperty(w)){v.state[w]=A[w]}}if(y&&y.id){v.id=y.id.toString()}if(y&&y.text){v.text=y.text}if(y&&y.data&&y.data.jstree&&y.data.jstree.icon){v.icon=y.data.jstree.icon}if(y&&y.data){v.data=y.data;if(y.data.jstree){for(w in y.data.jstree){if(y.data.jstree.hasOwnProperty(w)){v.state[w]=y.data.jstree[w]}}}}if(y&&typeof y.state==="object"){for(w in y.state){if(y.state.hasOwnProperty(w)){v.state[w]=y.state[w]}}}if(y&&typeof y.li_attr==="object"){for(w in y.li_attr){if(y.li_attr.hasOwnProperty(w)){v.li_attr[w]=y.li_attr[w]}}}if(v.li_attr.id&&!v.id){v.id=v.li_attr.id.toString()}if(!v.id){v.id=t}if(!v.li_attr.id){v.li_attr.id=v.id}if(y&&typeof y.a_attr==="object"){for(w in y.a_attr){if(y.a_attr.hasOwnProperty(w)){v.a_attr[w]=y.a_attr[w]}}}if(y&&y.children&&y.children.length){for(w=0,u=y.children.length;w<u;w++){z=this._parse_model_from_json(y.children[w],v.id,q);x=s[z];v.children.push(z);if(x.children_d.length){v.children_d=v.children_d.concat(x.children_d)}}v.children_d=v.children_d.concat(v.children)}if(y&&y.children&&y.children===true){v.state.loaded=false;v.children=[];v.children_d=[]}delete y.data;delete y.children;v.original=y;s[v.id]=v;if(v.state.selected){this._data.core.selected.push(v.id)}return v.id},_redraw:function(){var p=this._model.force_full_redraw?this._model.data["#"].children.concat([]):this._model.changed.concat([]),t=document.createElement("UL"),s,r,q;for(r=0,q=p.length;r<q;r++){s=this.redraw_node(p[r],true,this._model.force_full_redraw);if(s&&this._model.force_full_redraw){t.appendChild(s)}}if(this._model.force_full_redraw){t.className=this.get_container_ul()[0].className;this.element.empty().append(t)}this._model.force_full_redraw=false;this._model.changed=[];this.trigger("redraw",{nodes:p})},redraw:function(p){if(p){this._model.force_full_redraw=true}this._redraw()},redraw_node:function(t,E,D){var x=this.get_node(t),B=false,p=false,q=false,y=false,v=false,u=false,C="",A=document,r=this._model.data,z=false,F=false,w=null;if(!x){return false}if(x.id==="#"){return this.redraw(true)}E=E||x.children.length===0;t=!document.querySelector?document.getElementById(x.id):this.element[0].querySelector("#"+("0123456789".indexOf(x.id[0])!==-1?"\\3"+x.id[0]+" "+x.id.substr(1).replace(i.jstree.idregex,"\\$&"):x.id.replace(i.jstree.idregex,"\\$&")));if(!t){E=true;if(!D){B=x.parent!=="#"?i("#"+x.parent.replace(i.jstree.idregex,"\\$&"),this.element)[0]:null;if(B!==null&&(!B||!r[x.parent].state.opened)){return false}p=i.inArray(x.id,B===null?r["#"].children:r[x.parent].children)}}else{t=i(t);if(!D){B=t.parent().parent()[0];if(B===this.element[0]){B=null}p=t.index()}if(!E&&x.children.length&&!t.children(".jstree-children").length){E=true}if(!E){q=t.children(".jstree-children")[0]}F=t.attr("aria-selected");z=t.children(".jstree-anchor")[0]===document.activeElement;t.remove()}t=o.cloneNode(true);C="jstree-node ";for(y in x.li_attr){if(x.li_attr.hasOwnProperty(y)){if(y==="id"){continue}if(y!=="class"){t.setAttribute(y,x.li_attr[y])}else{C+=x.li_attr[y]}}}if(F&&F!=="false"){t.setAttribute("aria-selected",true)}if(x.state.loaded&&!x.children.length){C+=" jstree-leaf"}else{C+=x.state.opened&&x.state.loaded?" jstree-open":" jstree-closed";t.setAttribute("aria-expanded",(x.state.opened&&x.state.loaded))}if(x.parent!==null&&r[x.parent].children[r[x.parent].children.length-1]===x.id){C+=" jstree-last"}t.id=x.id;t.className=C;C=(x.state.selected?" jstree-clicked":"")+(x.state.disabled?" jstree-disabled":"");for(v in x.a_attr){if(x.a_attr.hasOwnProperty(v)){if(v==="href"&&x.a_attr[v]==="#"){continue}if(v!=="class"){t.childNodes[1].setAttribute(v,x.a_attr[v])}else{C+=" "+x.a_attr[v]}}}if(C.length){t.childNodes[1].className="jstree-anchor "+C}if((x.icon&&x.icon!==true)||x.icon===false){if(x.icon===false){t.childNodes[1].childNodes[0].className+=" jstree-themeicon-hidden"}else{if(x.icon.indexOf("/")===-1&&x.icon.indexOf(".")===-1){t.childNodes[1].childNodes[0].className+=" "+x.icon+" jstree-themeicon-custom"}else{t.childNodes[1].childNodes[0].style.backgroundImage="url("+x.icon+")";t.childNodes[1].childNodes[0].style.backgroundPosition="center center";t.childNodes[1].childNodes[0].style.backgroundSize="auto";t.childNodes[1].childNodes[0].className+=" jstree-themeicon-custom"}}}if(this.settings.core.force_text){t.childNodes[1].appendChild(A.createTextNode(x.text))}else{t.childNodes[1].innerHTML+=x.text}if(E&&x.children.length&&x.state.opened&&x.state.loaded){u=A.createElement("UL");u.setAttribute("role","group");u.className="jstree-children";for(y=0,v=x.children.length;y<v;y++){u.appendChild(this.redraw_node(x.children[y],E,true))}t.appendChild(u)}if(q){t.appendChild(q)}if(!D){if(!B){B=this.element[0]}for(y=0,v=B.childNodes.length;y<v;y++){if(B.childNodes[y]&&B.childNodes[y].className&&B.childNodes[y].className.indexOf("jstree-children")!==-1){w=B.childNodes[y];break}}if(!w){w=A.createElement("UL");w.setAttribute("role","group");w.className="jstree-children";B.appendChild(w)}B=w;if(p<B.childNodes.length){B.insertBefore(t,B.childNodes[p])}else{B.appendChild(t)}if(z){t.childNodes[1].focus()}}if(x.state.opened&&!x.state.loaded){x.state.opened=false;setTimeout(i.proxy(function(){this.open_node(x.id,false,0)},this),0)}return t},open_node:function(u,w,s){var r,q,v,p;if(i.isArray(u)){u=u.slice();for(r=0,q=u.length;r<q;r++){this.open_node(u[r],w,s)}return true}u=this.get_node(u);if(!u||u.id==="#"){return false}s=s===e?this.settings.core.animation:s;if(!this.is_closed(u)){if(w){w.call(this,u,false)}return false}if(!this.is_loaded(u)){if(this.is_loading(u)){return setTimeout(i.proxy(function(){this.open_node(u,w,s)},this),500)}this.load_node(u,function(x,t){return t?this.open_node(x,w,s):(w?w.call(this,x,false):false)})}else{v=this.get_node(u,true);p=this;if(v.length){if(u.children.length&&!this._firstChild(v.children(".jstree-children")[0])){u.state.opened=true;this.redraw_node(u,true);v=this.get_node(u,true)}if(!s){this.trigger("before_open",{node:u});v[0].className=v[0].className.replace("jstree-closed","jstree-open");v[0].setAttribute("aria-expanded",true)}else{this.trigger("before_open",{node:u});v.children(".jstree-children").css("display","none").end().removeClass("jstree-closed").addClass("jstree-open").attr("aria-expanded",true).children(".jstree-children").stop(true,true).slideDown(s,function(){this.style.display="";p.trigger("after_open",{node:u})})}}u.state.opened=true;if(w){w.call(this,u,true)}if(!v.length){this.trigger("before_open",{node:u})}this.trigger("open_node",{node:u});if(!s||!v.length){this.trigger("after_open",{node:u})}}},_open_to:function(t){t=this.get_node(t);if(!t||t.id==="#"){return false}var r,q,s=t.parents;for(r=0,q=s.length;r<q;r+=1){if(r!=="#"){this.open_node(s[r],false,0)}}return i("#"+t.id.replace(i.jstree.idregex,"\\$&"),this.element)},close_node:function(u,s){var r,q,p,v;if(i.isArray(u)){u=u.slice();for(r=0,q=u.length;r<q;r++){this.close_node(u[r],s)}return true}u=this.get_node(u);if(!u||u.id==="#"){return false}if(this.is_closed(u)){return false}s=s===e?this.settings.core.animation:s;p=this;v=this.get_node(u,true);if(v.length){if(!s){v[0].className=v[0].className.replace("jstree-open","jstree-closed");v.attr("aria-expanded",false).children(".jstree-children").remove()}else{v.children(".jstree-children").attr("style","display:block !important").end().removeClass("jstree-open").addClass("jstree-closed").attr("aria-expanded",false).children(".jstree-children").stop(true,true).slideUp(s,function(){this.style.display="";v.children(".jstree-children").remove();p.trigger("after_close",{node:u})})}}u.state.opened=false;this.trigger("close_node",{node:u});if(!s||!v.length){this.trigger("after_close",{node:u})}},toggle_node:function(r){var q,p;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.toggle_node(r[q])}return true}if(this.is_closed(r)){return this.open_node(r)}if(this.is_open(r)){return this.close_node(r)}},open_all:function(t,s,p){if(!t){t="#"}t=this.get_node(t);if(!t){return false}var u=t.id==="#"?this.get_container_ul():this.get_node(t,true),r,q,v;if(!u.length){for(r=0,q=t.children_d.length;r<q;r++){if(this.is_closed(this._model.data[t.children_d[r]])){this._model.data[t.children_d[r]].state.opened=true}}return this.trigger("open_all",{node:t})}p=p||u;v=this;u=this.is_closed(t)?u.find(".jstree-closed").addBack():u.find(".jstree-closed");u.each(function(){v.open_node(this,function(x,w){if(w&&this.is_parent(x)){this.open_all(x,s,p)}},s||0)});if(p.find(".jstree-closed").length===0){this.trigger("open_all",{node:this.get_node(p)})}},close_all:function(s,r){if(!s){s="#"}s=this.get_node(s);if(!s){return false}var t=s.id==="#"?this.get_container_ul():this.get_node(s,true),u=this,q,p;if(!t.length){for(q=0,p=s.children_d.length;q<p;q++){this._model.data[s.children_d[q]].state.opened=false}return this.trigger("close_all",{node:s})}t=this.is_open(s)?t.find(".jstree-open").addBack():t.find(".jstree-open");i(t.get().reverse()).each(function(){u.close_node(this,r||0)});this.trigger("close_all",{node:s})},is_disabled:function(p){p=this.get_node(p);return p&&p.state&&p.state.disabled},enable_node:function(r){var q,p;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.enable_node(r[q])}return true}r=this.get_node(r);if(!r||r.id==="#"){return false}r.state.disabled=false;this.get_node(r,true).children(".jstree-anchor").removeClass("jstree-disabled");this.trigger("enable_node",{node:r})},disable_node:function(r){var q,p;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.disable_node(r[q])}return true}r=this.get_node(r);if(!r||r.id==="#"){return false}r.state.disabled=true;this.get_node(r,true).children(".jstree-anchor").addClass("jstree-disabled");this.trigger("disable_node",{node:r})},activate_node:function(v,u){if(this.is_disabled(v)){return false}this._data.core.last_clicked=this._data.core.last_clicked&&this._data.core.last_clicked.id!==e?this.get_node(this._data.core.last_clicked.id):null;if(this._data.core.last_clicked&&!this._data.core.last_clicked.state.selected){this._data.core.last_clicked=null}if(!this._data.core.last_clicked&&this._data.core.selected.length){this._data.core.last_clicked=this.get_node(this._data.core.selected[this._data.core.selected.length-1])}if(!this.settings.core.multiple||(!u.metaKey&&!u.ctrlKey&&!u.shiftKey)||(u.shiftKey&&(!this._data.core.last_clicked||!this.get_parent(v)||this.get_parent(v)!==this._data.core.last_clicked.parent))){if(!this.settings.core.multiple&&(u.metaKey||u.ctrlKey||u.shiftKey)&&this.is_selected(v)){this.deselect_node(v,false,u)}else{this.deselect_all(true);this.select_node(v,false,false,u);this._data.core.last_clicked=this.get_node(v)}}else{if(u.shiftKey){var w=this.get_node(v).id,q=this._data.core.last_clicked.id,t=this.get_node(this._data.core.last_clicked.parent).children,x=false,s,r;for(s=0,r=t.length;s<r;s+=1){if(t[s]===w){x=!x}if(t[s]===q){x=!x}if(x||t[s]===w||t[s]===q){this.select_node(t[s],false,false,u)}else{this.deselect_node(t[s],false,u)}}}else{if(!this.is_selected(v)){this.select_node(v,false,false,u)}else{this.deselect_node(v,false,u)}}}this.trigger("activate_node",{node:this.get_node(v)})},hover_node:function(q){q=this.get_node(q,true);if(!q||!q.length||q.children(".jstree-hovered").length){return false}var r=this.element.find(".jstree-hovered"),p=this.element;if(r&&r.length){this.dehover_node(r)}q.children(".jstree-anchor").addClass("jstree-hovered");this.trigger("hover_node",{node:this.get_node(q)});setTimeout(function(){p.attr("aria-activedescendant",q[0].id);q.attr("aria-selected",true)},0)},dehover_node:function(p){p=this.get_node(p,true);if(!p||!p.length||!p.children(".jstree-hovered").length){return false}p.attr("aria-selected",false).children(".jstree-anchor").removeClass("jstree-hovered");this.trigger("dehover_node",{node:this.get_node(p)})},select_node:function(u,w,p,t){var v,s,q,r;if(i.isArray(u)){u=u.slice();for(s=0,q=u.length;s<q;s++){this.select_node(u[s],w,p,t)}return true}u=this.get_node(u);if(!u||u.id==="#"){return false}v=this.get_node(u,true);if(!u.state.selected){u.state.selected=true;this._data.core.selected.push(u.id);if(!p){v=this._open_to(u)}if(v&&v.length){v.children(".jstree-anchor").addClass("jstree-clicked")}this.trigger("select_node",{node:u,selected:this._data.core.selected,event:t});if(!w){this.trigger("changed",{action:"select_node",node:u,selected:this._data.core.selected,event:t})}}},deselect_node:function(s,u,r){var q,p,t;if(i.isArray(s)){s=s.slice();for(q=0,p=s.length;q<p;q++){this.deselect_node(s[q],u,r)}return true}s=this.get_node(s);if(!s||s.id==="#"){return false}t=this.get_node(s,true);if(s.state.selected){s.state.selected=false;this._data.core.selected=i.vakata.array_remove_item(this._data.core.selected,s.id);if(t.length){t.children(".jstree-anchor").removeClass("jstree-clicked")}this.trigger("deselect_node",{node:s,selected:this._data.core.selected,event:r});if(!u){this.trigger("changed",{action:"deselect_node",node:s,selected:this._data.core.selected,event:r})}}},select_all:function(s){var r=this._data.core.selected.concat([]),q,p;this._data.core.selected=this._model.data["#"].children_d.concat();for(q=0,p=this._data.core.selected.length;q<p;q++){if(this._model.data[this._data.core.selected[q]]){this._model.data[this._data.core.selected[q]].state.selected=true}}this.redraw(true);this.trigger("select_all",{selected:this._data.core.selected});if(!s){this.trigger("changed",{action:"select_all",selected:this._data.core.selected,old_selection:r})}},deselect_all:function(s){var r=this._data.core.selected.concat([]),q,p;for(q=0,p=this._data.core.selected.length;q<p;q++){if(this._model.data[this._data.core.selected[q]]){this._model.data[this._data.core.selected[q]].state.selected=false}}this._data.core.selected=[];this.element.find(".jstree-clicked").removeClass("jstree-clicked");this.trigger("deselect_all",{selected:this._data.core.selected,node:r});if(!s){this.trigger("changed",{action:"deselect_all",selected:this._data.core.selected,old_selection:r})}},is_selected:function(p){p=this.get_node(p);if(!p||p.id==="#"){return false}return p.state.selected},get_selected:function(p){return p?i.map(this._data.core.selected,i.proxy(function(q){return this.get_node(q)},this)):this._data.core.selected.slice()},get_top_selected:function(u){var t=this.get_selected(true),v={},s,r,q,p;for(s=0,r=t.length;s<r;s++){v[t[s].id]=t[s]}for(s=0,r=t.length;s<r;s++){for(q=0,p=t[s].children_d.length;q<p;q++){if(v[t[s].children_d[q]]){delete v[t[s].children_d[q]]}}}t=[];for(s in v){if(v.hasOwnProperty(s)){t.push(s)}}return u?i.map(t,i.proxy(function(w){return this.get_node(w)},this)):t},get_bottom_selected:function(s){var r=this.get_selected(true),t=[],q,p;for(q=0,p=r.length;q<p;q++){if(!r[q].children.length){t.push(r[q].id)}}return s?i.map(t,i.proxy(function(u){return this.get_node(u)},this)):t},get_state:function(){var q={core:{open:[],scroll:{left:this.element.scrollLeft(),top:this.element.scrollTop()}, +/* + 'themes' : { + 'name' : this.get_theme(), + 'icons' : this._data.core.themes.icons, + 'dots' : this._data.core.themes.dots + }, + */ +selected:[]}},p;for(p in this._model.data){if(this._model.data.hasOwnProperty(p)){if(p!=="#"){if(this._model.data[p].state.opened){q.core.open.push(p)}if(this._model.data[p].state.selected){q.core.selected.push(p)}}}}return q},set_state:function(r,v){if(r){if(r.core){var q,u,p,s;if(r.core.open){if(!i.isArray(r.core.open)){delete r.core.open;this.set_state(r,v);return false}q=true;u=false;p=this;i.each(r.core.open.concat([]),function(w,t){u=p.get_node(t);if(u){if(p.is_loaded(t)){if(p.is_closed(t)){p.open_node(t,false,0)}if(r&&r.core&&r.core.open){i.vakata.array_remove_item(r.core.open,t)}}else{if(!p.is_loading(t)){p.open_node(t,i.proxy(function(y,x){if(!x&&r&&r.core&&r.core.open){i.vakata.array_remove_item(r.core.open,y.id)}this.set_state(r,v)},p),0)}q=false}}});if(q){delete r.core.open;this.set_state(r,v)}return false}if(r.core.scroll){if(r.core.scroll&&r.core.scroll.left!==e){this.element.scrollLeft(r.core.scroll.left)}if(r.core.scroll&&r.core.scroll.top!==e){this.element.scrollTop(r.core.scroll.top)}delete r.core.scroll;this.set_state(r,v);return false; +/* + if(state.core.themes) { + if(state.core.themes.name) { + this.set_theme(state.core.themes.name); + } + if(typeof state.core.themes.dots !== 'undefined') { + this[ state.core.themes.dots ? "show_dots" : "hide_dots" ](); + } + if(typeof state.core.themes.icons !== 'undefined') { + this[ state.core.themes.icons ? "show_icons" : "hide_icons" ](); + } + delete state.core.themes; + delete state.core.open; + this.set_state(state, callback); + return false; + } + */ +}if(r.core.selected){s=this;this.deselect_all();i.each(r.core.selected,function(w,t){s.select_node(t)});delete r.core.selected;this.set_state(r,v);return false}if(i.isEmptyObject(r.core)){delete r.core;this.set_state(r,v);return false}}if(i.isEmptyObject(r)){r=null;if(v){v.call(this)}this.trigger("set_state");return false}return true}return false},refresh:function(q,p){this._data.core.state=p===true?{}:this.get_state();if(p&&i.isFunction(p)){this._data.core.state=p.call(this,this._data.core.state)}this._cnt=0;this._model.data={"#":{id:"#",parent:null,parents:[],children:[],children_d:[],state:{loaded:false}}};var r=this.get_container_ul()[0].className;if(!q){this.element.html("<ul class='"+r+"'><li class='jstree-initial-node jstree-loading jstree-leaf jstree-last'><i class='jstree-icon jstree-ocl'></i><a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>"+this.get_string("Loading ...")+"</a></li></ul>")}this.load_node("#",function(u,t){if(t){this.get_container_ul()[0].className=r;this.set_state(i.extend(true,{},this._data.core.state),function(){this.trigger("refresh")})}this._data.core.state=null})},refresh_node:function(r){r=this.get_node(r);if(!r||r.id==="#"){return false}var t=[],p=[],q=this._data.core.selected.concat([]);p.push(r.id);if(r.state.opened===true){t.push(r.id)}this.get_node(r,true).find(".jstree-open").each(function(){t.push(this.id)});this._load_nodes(p,i.proxy(function(s){this.open_node(t,false,0);this.select_node(this._data.core.selected);this.trigger("refresh_node",{node:r,nodes:s})},this))},set_id:function(s,t){s=this.get_node(s);if(!s||s.id==="#"){return false}var r,q,p=this._model.data;t=t.toString();p[s.parent].children[i.inArray(s.id,p[s.parent].children)]=t;for(r=0,q=s.parents.length;r<q;r++){p[s.parents[r]].children_d[i.inArray(s.id,p[s.parents[r]].children_d)]=t}for(r=0,q=s.children.length;r<q;r++){p[s.children[r]].parent=t}for(r=0,q=s.children_d.length;r<q;r++){p[s.children_d[r]].parents[i.inArray(s.id,p[s.children_d[r]].parents)]=t}r=i.inArray(s.id,this._data.core.selected);if(r!==-1){this._data.core.selected[r]=t}r=this.get_node(s.id,true);if(r){r.attr("id",t)}delete p[s.id];s.id=t;p[t]=s;return true},get_text:function(p){p=this.get_node(p);return(!p||p.id==="#")?false:p.text},set_text:function(r,s){var q,p;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.set_text(r[q],s)}return true}r=this.get_node(r);if(!r||r.id==="#"){return false}r.text=s;if(this.get_node(r,true).length){this.redraw_node(r.id)}this.trigger("set_text",{obj:r,text:s});return true},get_json:function(t,q,u){t=this.get_node(t||"#");if(!t){return false}if(q&&q.flat&&!u){u=[]}var s={id:t.id,text:t.text,icon:this.get_icon(t),li_attr:t.li_attr,a_attr:t.a_attr,state:{},data:q&&q.no_data?false:t.data},r,p;if(q&&q.flat){s.parent=t.parent}else{s.children=[]}if(!q||!q.no_state){for(r in t.state){if(t.state.hasOwnProperty(r)){s.state[r]=t.state[r]}}}if(q&&q.no_id){delete s.id;if(s.li_attr&&s.li_attr.id){delete s.li_attr.id}}if(q&&q.flat&&t.id!=="#"){u.push(s)}if(!q||!q.no_children){for(r=0,p=t.children.length;r<p;r++){if(q&&q.flat){this.get_json(t.children[r],q,u)}else{s.children.push(this.get_json(t.children[r],q))}}}return q&&q.flat?u:(t.id==="#"?s.children:s)},create_node:function(u,p,w,x,v){if(u===null){u="#"}u=this.get_node(u);if(!u){return false}w=w===e?"last":w;if(!w.toString().match(/^(before|after)$/)&&!v&&!this.is_loaded(u)){return this.load_node(u,function(){this.create_node(u,p,w,x,true)})}if(!p){p={text:this.get_string("New node")}}if(p.text===e){p.text=this.get_string("New node")}var r,t,s,q;if(u.id==="#"){if(w==="before"){w="first"}if(w==="after"){w="last"}}switch(w){case"before":r=this.get_node(u.parent);w=i.inArray(u.id,r.children);u=r;break;case"after":r=this.get_node(u.parent);w=i.inArray(u.id,r.children)+1;u=r;break;case"inside":case"first":w=0;break;case"last":w=u.children.length;break;default:if(!w){w=0}break}if(w>u.children.length){w=u.children.length}if(!p.id){p.id=true}if(!this.check("create_node",p,u,w)){this.settings.core.error.call(this,this._data.core.last_error);return false}if(p.id===true){delete p.id}p=this._parse_model_from_json(p,u.id,u.parents.concat());if(!p){return false}r=this.get_node(p);t=[];t.push(p);t=t.concat(r.children_d);this.trigger("model",{nodes:t,parent:u.id});u.children_d=u.children_d.concat(t);for(s=0,q=u.parents.length;s<q;s++){this._model.data[u.parents[s]].children_d=this._model.data[u.parents[s]].children_d.concat(t)}p=r;r=[];for(s=0,q=u.children.length;s<q;s++){r[s>=w?s+1:s]=u.children[s]}r[w]=p.id;u.children=r;this.redraw_node(u,true);if(x){x.call(this,this.get_node(p))}this.trigger("create_node",{node:this.get_node(p),parent:u.id,position:w});return p.id},rename_node:function(s,t){var r,q,p;if(i.isArray(s)){s=s.slice();for(r=0,q=s.length;r<q;r++){this.rename_node(s[r],t)}return true}s=this.get_node(s);if(!s||s.id==="#"){return false}p=s.text;if(!this.check("rename_node",s,this.get_parent(s),t)){this.settings.core.error.call(this,this._data.core.last_error);return false}this.set_text(s,t);this.trigger("rename_node",{node:s,text:t,old:p});return true},delete_node:function(s){var w,v,x,z,t,u,r,q,p,y;if(i.isArray(s)){s=s.slice();for(w=0,v=s.length;w<v;w++){this.delete_node(s[w])}return true}s=this.get_node(s);if(!s||s.id==="#"){return false}x=this.get_node(s.parent);z=i.inArray(s.id,x.children);y=false;if(!this.check("delete_node",s,x,z)){this.settings.core.error.call(this,this._data.core.last_error);return false}if(z!==-1){x.children=i.vakata.array_remove(x.children,z)}t=s.children_d.concat([]);t.push(s.id);for(q=0,p=t.length;q<p;q++){for(u=0,r=s.parents.length;u<r;u++){z=i.inArray(t[q],this._model.data[s.parents[u]].children_d);if(z!==-1){this._model.data[s.parents[u]].children_d=i.vakata.array_remove(this._model.data[s.parents[u]].children_d,z)}}if(this._model.data[t[q]].state.selected){y=true;z=i.inArray(t[q],this._data.core.selected);if(z!==-1){this._data.core.selected=i.vakata.array_remove(this._data.core.selected,z)}}}this.trigger("delete_node",{node:s,parent:x.id});if(y){this.trigger("changed",{action:"delete_node",node:s,selected:this._data.core.selected,parent:x.id})}for(q=0,p=t.length;q<p;q++){delete this._model.data[t[q]]}this.redraw_node(x,true);return true},check:function(p,t,s,v,r){t=t&&t.id?t:this.get_node(t);s=s&&s.id?s:this.get_node(s);var q=p.match(/^move_node|copy_node|create_node$/i)?s:t,u=this.settings.core.check_callback;if(p==="move_node"||p==="copy_node"){if((!r||!r.is_multi)&&(t.id===s.id||i.inArray(t.id,s.children)===v||i.inArray(s.id,t.children_d)!==-1)){this._data.core.last_error={error:"check",plugin:"core",id:"core_01",reason:"Moving parent inside child",data:JSON.stringify({chk:p,pos:v,obj:t&&t.id?t.id:false,par:s&&s.id?s.id:false})};return false}}if(q&&q.data){q=q.data}if(q&&q.functions&&(q.functions[p]===false||q.functions[p]===true)){if(q.functions[p]===false){this._data.core.last_error={error:"check",plugin:"core",id:"core_02",reason:"Node data prevents function: "+p,data:JSON.stringify({chk:p,pos:v,obj:t&&t.id?t.id:false,par:s&&s.id?s.id:false})}}return q.functions[p]}if(u===false||(i.isFunction(u)&&u.call(this,p,t,s,v,r)===false)||(u&&u[p]===false)){this._data.core.last_error={error:"check",plugin:"core",id:"core_03",reason:"User config for core.check_callback prevents function: "+p,data:JSON.stringify({chk:p,pos:v,obj:t&&t.id?t.id:false,par:s&&s.id?s.id:false})};return false}return true},last_error:function(){return this._data.core.last_error},move_node:function(y,A,t,r,z){var w,v,x,q,H,I,s,u,G,F,E,D,C,B;A=this.get_node(A);t=t===e?0:t;if(!A){return false}if(!t.toString().match(/^(before|after)$/)&&!z&&!this.is_loaded(A)){return this.load_node(A,function(){this.move_node(y,A,t,r,true)})}if(i.isArray(y)){y=y.reverse().slice();for(w=0,v=y.length;w<v;w++){this.move_node(y[w],A,t,r,z)}return true}y=y&&y.id?y:this.get_node(y);if(!y||y.id==="#"){return false}x=(y.parent||"#").toString();H=(!t.toString().match(/^(before|after)$/)||A.id==="#")?A:this.get_node(A.parent);I=y.instance?y.instance:(this._model.data[y.id]?this:i.jstree.reference(y.id));s=!I||!I._id||(this._id!==I._id);q=I&&I._id&&x&&I._model.data[x]&&I._model.data[x].children?i.inArray(y.id,I._model.data[x].children):-1;if(s){if(this.copy_node(y,A,t,r,z)){if(I){I.delete_node(y)}return true}return false}if(H.id==="#"){if(t==="before"){t="first"}if(t==="after"){t="last"}}switch(t){case"before":t=i.inArray(A.id,H.children);break;case"after":t=i.inArray(A.id,H.children)+1;break;case"inside":case"first":t=0;break;case"last":t=H.children.length;break;default:if(!t){t=0}break}if(t>H.children.length){t=H.children.length}if(!this.check("move_node",y,H,t,{core:true,is_multi:(I&&I._id&&I._id!==this._id),is_foreign:(!I||!I._id)})){this.settings.core.error.call(this,this._data.core.last_error);return false}if(y.parent===H.id){u=H.children.concat();G=i.inArray(y.id,u);if(G!==-1){u=i.vakata.array_remove(u,G);if(t>G){t--}}G=[];for(F=0,E=u.length;F<E;F++){G[F>=t?F+1:F]=u[F]}G[t]=y.id;H.children=G;this._node_changed(H.id);this.redraw(H.id==="#")}else{G=y.children_d.concat();G.push(y.id);for(F=0,E=y.parents.length;F<E;F++){u=[];B=I._model.data[y.parents[F]].children_d;for(D=0,C=B.length;D<C;D++){if(i.inArray(B[D],G)===-1){u.push(B[D])}}I._model.data[y.parents[F]].children_d=u}I._model.data[x].children=i.vakata.array_remove_item(I._model.data[x].children,y.id);for(F=0,E=H.parents.length;F<E;F++){this._model.data[H.parents[F]].children_d=this._model.data[H.parents[F]].children_d.concat(G)}u=[];for(F=0,E=H.children.length;F<E;F++){u[F>=t?F+1:F]=H.children[F]}u[t]=y.id;H.children=u;H.children_d.push(y.id);H.children_d=H.children_d.concat(y.children_d);y.parent=H.id;G=H.parents.concat();G.unshift(H.id);B=y.parents.length;y.parents=G;G=G.concat();for(F=0,E=y.children_d.length;F<E;F++){this._model.data[y.children_d[F]].parents=this._model.data[y.children_d[F]].parents.slice(0,B*-1);Array.prototype.push.apply(this._model.data[y.children_d[F]].parents,G)}this._node_changed(x);this._node_changed(H.id);this.redraw(x==="#"||H.id==="#")}if(r){r.call(this,y,H,t)}this.trigger("move_node",{node:y,parent:H.id,position:t,old_parent:x,old_position:q,is_multi:(I&&I._id&&I._id!==this._id),is_foreign:(!I||!I._id),old_instance:I,new_instance:this});return true},copy_node:function(v,B,D,E,C){var z,y,x,u,t,s,q,A,p,w,r;B=this.get_node(B);D=D===e?0:D;if(!B){return false}if(!D.toString().match(/^(before|after)$/)&&!C&&!this.is_loaded(B)){return this.load_node(B,function(){this.copy_node(v,B,D,E,true)})}if(i.isArray(v)){v=v.reverse().slice();for(z=0,y=v.length;z<y;z++){this.copy_node(v[z],B,D,E,C)}return true}v=v&&v.id?v:this.get_node(v);if(!v||v.id==="#"){return false}A=(v.parent||"#").toString();p=(!D.toString().match(/^(before|after)$/)||B.id==="#")?B:this.get_node(B.parent);w=v.instance?v.instance:(this._model.data[v.id]?this:i.jstree.reference(v.id));r=!w||!w._id||(this._id!==w._id);if(p.id==="#"){if(D==="before"){D="first"}if(D==="after"){D="last"}}switch(D){case"before":D=i.inArray(B.id,p.children);break;case"after":D=i.inArray(B.id,p.children)+1;break;case"inside":case"first":D=0;break;case"last":D=p.children.length;break;default:if(!D){D=0}break}if(D>p.children.length){D=p.children.length}if(!this.check("copy_node",v,p,D,{core:true,is_multi:(w&&w._id&&w._id!==this._id),is_foreign:(!w||!w._id)})){this.settings.core.error.call(this,this._data.core.last_error);return false}q=w?w.get_json(v,{no_id:true,no_data:true,no_state:true}):v;if(!q){return false}if(q.id===true){delete q.id}q=this._parse_model_from_json(q,p.id,p.parents.concat());if(!q){return false}u=this.get_node(q);if(v&&v.state&&v.state.loaded===false){u.state.loaded=false}x=[];x.push(q);x=x.concat(u.children_d);this.trigger("model",{nodes:x,parent:p.id});for(t=0,s=p.parents.length;t<s;t++){this._model.data[p.parents[t]].children_d=this._model.data[p.parents[t]].children_d.concat(x)}x=[];for(t=0,s=p.children.length;t<s;t++){x[t>=D?t+1:t]=p.children[t]}x[D]=u.id;p.children=x;p.children_d.push(u.id);p.children_d=p.children_d.concat(u.children_d);this._node_changed(p.id);this.redraw(p.id==="#");if(E){E.call(this,u,p,D)}this.trigger("copy_node",{node:u,original:v,parent:p.id,position:D,old_parent:A,old_position:w&&w._id&&A&&w._model.data[A]&&w._model.data[A].children?i.inArray(v.id,w._model.data[A].children):-1,is_multi:(w&&w._id&&w._id!==this._id),is_foreign:(!w||!w._id),old_instance:w,new_instance:this});return u.id},cut:function(s){if(!s){s=this._data.core.selected.concat()}if(!i.isArray(s)){s=[s]}if(!s.length){return false}var p=[],t,r,q;for(r=0,q=s.length;r<q;r++){t=this.get_node(s[r]);if(t&&t.id&&t.id!=="#"){p.push(t)}}if(!p.length){return false}d=p;j=this;k="move_node";this.trigger("cut",{node:s})},copy:function(s){if(!s){s=this._data.core.selected.concat()}if(!i.isArray(s)){s=[s]}if(!s.length){return false}var p=[],t,r,q;for(r=0,q=s.length;r<q;r++){t=this.get_node(s[r]);if(t&&t.id&&t.id!=="#"){p.push(t)}}if(!p.length){return false}d=p;j=this;k="copy_node";this.trigger("copy",{node:s})},get_buffer:function(){return{mode:k,node:d,inst:j}},can_paste:function(){return k!==false&&d!==false},paste:function(p,q){p=this.get_node(p);if(!p||!k||!k.match(/^(copy_node|move_node)$/)||!d){return false}if(this[k](d,p,q)){this.trigger("paste",{parent:p.id,node:d,mode:k})}d=false;k=false;j=false},edit:function(p,x){p=this.get_node(p);if(!p){return false}if(this.settings.core.check_callback===false){this._data.core.last_error={error:"check",plugin:"core",id:"core_07",reason:"Could not edit node because of check_callback"};this.settings.core.error.call(this,this._data.core.last_error);return false}x=typeof x==="string"?x:p.text;this.set_text(p,"");p=this._open_to(p);var v=this._data.core.rtl,z=this.element.width(),y=p.children(".jstree-anchor"),B=i("<span>") +/* + oi = obj.children("i:visible"), + ai = a.children("i:visible"), + w1 = oi.width() * oi.length, + w2 = ai.width() * ai.length, + */ +,A=x,r=i("<div />",{css:{position:"absolute",top:"-200px",left:(v?"0px":"-1000px"),visibility:"hidden"}}).appendTo("body"),q=i("<input />",{value:A,"class":"jstree-rename-input",css:{padding:"0",border:"1px solid silver","box-sizing":"border-box",display:"inline-block",height:(this._data.core.li_height)+"px",lineHeight:(this._data.core.li_height)+"px",width:"150px"},blur:i.proxy(function(){var t=B.children(".jstree-rename-input"),s=t.val();if(s===""){s=A}r.remove();B.replaceWith(y);B.remove();this.set_text(p,A);if(this.rename_node(p,i("<div></div>").text(s)[this.settings.core.force_text?"text":"html"]())===false){this.set_text(p,A)}},this),keydown:function(t){var s=t.which;if(s===27){this.value=A}if(s===27||s===13||s===37||s===38||s===39||s===40||s===32){t.stopImmediatePropagation()}if(s===27||s===13){t.preventDefault();this.blur()}},click:function(s){s.stopImmediatePropagation()},mousedown:function(s){s.stopImmediatePropagation()},keyup:function(s){q.width(Math.min(r.text("pW"+this.value).width(),z))},keypress:function(s){if(s.which===13){return false}}}),u={fontFamily:y.css("fontFamily")||"",fontSize:y.css("fontSize")||"",fontWeight:y.css("fontWeight")||"",fontStyle:y.css("fontStyle")||"",fontStretch:y.css("fontStretch")||"",fontVariant:y.css("fontVariant")||"",letterSpacing:y.css("letterSpacing")||"",wordSpacing:y.css("wordSpacing")||""};B.attr("class",y.attr("class")).append(y.contents().clone()).append(q);y.replaceWith(B);r.css(u);q.css(u).width(Math.min(r.text("pW"+q[0].value).width(),z))[0].select()},set_theme:function(r,p){if(!r){return false}if(p===true){var q=this.settings.core.themes.dir;if(!q){q=i.jstree.path+"/themes"}p=q+"/"+r+"/style.css"}if(p&&i.inArray(p,m)===-1){i("head").append('<link rel="stylesheet" href="'+p+'" type="text/css" />');m.push(p)}if(this._data.core.themes.name){this.element.removeClass("jstree-"+this._data.core.themes.name)}this._data.core.themes.name=r;this.element.addClass("jstree-"+r);this.element[this.settings.core.themes.responsive?"addClass":"removeClass"]("jstree-"+r+"-responsive");this.trigger("set_theme",{theme:r})},get_theme:function(){return this._data.core.themes.name},set_theme_variant:function(p){if(this._data.core.themes.variant){this.element.removeClass("jstree-"+this._data.core.themes.name+"-"+this._data.core.themes.variant)}this._data.core.themes.variant=p;if(p){this.element.addClass("jstree-"+this._data.core.themes.name+"-"+this._data.core.themes.variant)}},get_theme_variant:function(){return this._data.core.themes.variant},show_stripes:function(){this._data.core.themes.stripes=true;this.get_container_ul().addClass("jstree-striped")},hide_stripes:function(){this._data.core.themes.stripes=false;this.get_container_ul().removeClass("jstree-striped")},toggle_stripes:function(){if(this._data.core.themes.stripes){this.hide_stripes()}else{this.show_stripes()}},show_dots:function(){this._data.core.themes.dots=true;this.get_container_ul().removeClass("jstree-no-dots")},hide_dots:function(){this._data.core.themes.dots=false;this.get_container_ul().addClass("jstree-no-dots")},toggle_dots:function(){if(this._data.core.themes.dots){this.hide_dots()}else{this.show_dots()}},show_icons:function(){this._data.core.themes.icons=true;this.get_container_ul().removeClass("jstree-no-icons")},hide_icons:function(){this._data.core.themes.icons=false;this.get_container_ul().addClass("jstree-no-icons")},toggle_icons:function(){if(this._data.core.themes.icons){this.hide_icons()}else{this.show_icons()}},set_icon:function(t,r){var s,q,u,p;if(i.isArray(t)){t=t.slice();for(s=0,q=t.length;s<q;s++){this.set_icon(t[s],r)}return true}t=this.get_node(t);if(!t||t.id==="#"){return false}p=t.icon;t.icon=r;u=this.get_node(t,true).children(".jstree-anchor").children(".jstree-themeicon");if(r===false){this.hide_icon(t)}else{if(r===true){u.removeClass("jstree-themeicon-custom "+p).css("background","").removeAttr("rel")}else{if(r.indexOf("/")===-1&&r.indexOf(".")===-1){u.removeClass(p).css("background","");u.addClass(r+" jstree-themeicon-custom").attr("rel",r)}else{u.removeClass(p).css("background","");u.addClass("jstree-themeicon-custom").css("background","url('"+r+"') center center no-repeat").attr("rel",r)}}}return true},get_icon:function(p){p=this.get_node(p);return(!p||p.id==="#")?false:p.icon},hide_icon:function(r){var q,p;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.hide_icon(r[q])}return true}r=this.get_node(r);if(!r||r==="#"){return false}r.icon=false;this.get_node(r,true).children(".jstree-anchor").children(".jstree-themeicon").addClass("jstree-themeicon-hidden");return true},show_icon:function(r){var q,p,s;if(i.isArray(r)){r=r.slice();for(q=0,p=r.length;q<p;q++){this.show_icon(r[q])}return true}r=this.get_node(r);if(!r||r==="#"){return false}s=this.get_node(r,true);r.icon=s.length?s.children(".jstree-anchor").children(".jstree-themeicon").attr("rel"):true;if(!r.icon){r.icon=true}s.children(".jstree-anchor").children(".jstree-themeicon").removeClass("jstree-themeicon-hidden");return true}};i.vakata={};i.vakata.attributes=function(q,r){q=i(q)[0];var p=r?{}:[];if(q&&q.attributes){i.each(q.attributes,function(t,s){if(i.inArray(s.nodeName.toLowerCase(),["style","contenteditable","hasfocus","tabindex"])!==-1){return}if(s.nodeValue!==null&&i.trim(s.nodeValue)!==""){if(r){p[s.nodeName]=s.nodeValue}else{p.push(s.nodeName)}}})}return p};i.vakata.array_unique=function(t){var q=[],s,r,p;for(s=0,p=t.length;s<p;s++){for(r=0;r<=s;r++){if(t[s]===t[r]){break}}if(r===s){q.push(t[s])}}return q};i.vakata.array_remove=function(s,r,q){var p=s.slice((q||r)+1||s.length);s.length=r<0?s.length+r:r;s.push.apply(s,p);return s};i.vakata.array_remove_item=function(r,q){var p=i.inArray(q,r);return p!==-1?i.vakata.array_remove(r,p):r};var h=document.createElement("I");h.className="jstree-icon jstree-checkbox";i.jstree.defaults.checkbox={visible:true,three_state:true,whole_node:true,keep_selected_style:true,cascade:"",tie_selection:true};i.jstree.plugins.checkbox=function(p,q){this.bind=function(){q.bind.call(this);this._data.checkbox.uto=false;this._data.checkbox.selected=[];if(this.settings.checkbox.three_state){this.settings.checkbox.cascade="up+down+undetermined"}this.element.on("init.jstree",i.proxy(function(){this._data.checkbox.visible=this.settings.checkbox.visible;if(!this.settings.checkbox.keep_selected_style){this.element.addClass("jstree-checkbox-no-clicked")}if(this.settings.checkbox.tie_selection){this.element.addClass("jstree-checkbox-selection")}},this)).on("loading.jstree",i.proxy(function(){this[this._data.checkbox.visible?"show_checkboxes":"hide_checkboxes"]()},this));if(this.settings.checkbox.cascade.indexOf("undetermined")!==-1){this.element.on("changed.jstree uncheck_node.jstree check_node.jstree uncheck_all.jstree check_all.jstree move_node.jstree copy_node.jstree redraw.jstree open_node.jstree",i.proxy(function(){if(this._data.checkbox.uto){clearTimeout(this._data.checkbox.uto)}this._data.checkbox.uto=setTimeout(i.proxy(this._undetermined,this),50)},this))}if(!this.settings.checkbox.tie_selection){this.element.on("model.jstree",i.proxy(function(w,u){var r=this._model.data,v=r[u.parent],x=u.nodes,t,s;for(t=0,s=x.length;t<s;t++){r[x[t]].state.checked=(r[x[t]].original&&r[x[t]].original.state&&r[x[t]].original.state.checked);if(r[x[t]].state.checked){this._data.checkbox.selected.push(x[t])}}},this))}if(this.settings.checkbox.cascade.indexOf("up")!==-1||this.settings.checkbox.cascade.indexOf("down")!==-1){this.element.on("model.jstree",i.proxy(function(C,z){var u=this._model.data,r=u[z.parent],B=z.nodes,G=[],D,A,x,w,v,y,F=this.settings.checkbox.cascade,E=this.settings.checkbox.tie_selection;if(F.indexOf("down")!==-1){if(r.state[E?"selected":"checked"]){for(A=0,x=B.length;A<x;A++){u[B[A]].state[E?"selected":"checked"]=true}this._data[E?"core":"checkbox"].selected=this._data[E?"core":"checkbox"].selected.concat(B)}else{for(A=0,x=B.length;A<x;A++){if(u[B[A]].state[E?"selected":"checked"]){for(w=0,v=u[B[A]].children_d.length;w<v;w++){u[u[B[A]].children_d[w]].state[E?"selected":"checked"]=true}this._data[E?"core":"checkbox"].selected=this._data[E?"core":"checkbox"].selected.concat(u[B[A]].children_d)}}}}if(F.indexOf("up")!==-1){for(A=0,x=r.children_d.length;A<x;A++){if(!u[r.children_d[A]].children.length){G.push(u[r.children_d[A]].parent)}}G=i.vakata.array_unique(G);for(w=0,v=G.length;w<v;w++){r=u[G[w]];while(r&&r.id!=="#"){D=0;for(A=0,x=r.children.length;A<x;A++){D+=u[r.children[A]].state[E?"selected":"checked"]}if(D===x){r.state[E?"selected":"checked"]=true;this._data[E?"core":"checkbox"].selected.push(r.id);y=this.get_node(r,true);if(y&&y.length){y.children(".jstree-anchor").addClass(E?"jstree-clicked":"jstree-checked")}}else{break}r=this.get_node(r.parent)}}}this._data[E?"core":"checkbox"].selected=i.vakata.array_unique(this._data[E?"core":"checkbox"].selected)},this)).on(this.settings.checkbox.tie_selection?"select_node.jstree":"check_node.jstree",i.proxy(function(A,y){var x=y.node,r=this._model.data,B=this.get_node(x.parent),u=this.get_node(x,true),z,v,C,w,E=this.settings.checkbox.cascade,D=this.settings.checkbox.tie_selection;if(E.indexOf("down")!==-1){this._data[D?"core":"checkbox"].selected=i.vakata.array_unique(this._data[D?"core":"checkbox"].selected.concat(x.children_d));for(z=0,v=x.children_d.length;z<v;z++){w=r[x.children_d[z]];w.state[D?"selected":"checked"]=true;if(w&&w.original&&w.original.state&&w.original.state.undetermined){w.original.state.undetermined=false}}}if(E.indexOf("up")!==-1){while(B&&B.id!=="#"){C=0;for(z=0,v=B.children.length;z<v;z++){C+=r[B.children[z]].state[D?"selected":"checked"]}if(C===v){B.state[D?"selected":"checked"]=true;this._data[D?"core":"checkbox"].selected.push(B.id);w=this.get_node(B,true);if(w&&w.length){w.children(".jstree-anchor").addClass(D?"jstree-clicked":"jstree-checked")}}else{break}B=this.get_node(B.parent)}}if(E.indexOf("down")!==-1&&u.length){u.find(".jstree-anchor").addClass(D?"jstree-clicked":"jstree-checked")}},this)).on(this.settings.checkbox.tie_selection?"deselect_all.jstree":"uncheck_all.jstree",i.proxy(function(x,v){var w=this.get_node("#"),r=this._model.data,u,s,t;for(u=0,s=w.children_d.length;u<s;u++){t=r[w.children_d[u]];if(t&&t.original&&t.original.state&&t.original.state.undetermined){t.original.state.undetermined=false}}},this)).on(this.settings.checkbox.tie_selection?"deselect_node.jstree":"uncheck_node.jstree",i.proxy(function(z,w){var v=w.node,r=this.get_node(v,true),x,u,y,B=this.settings.checkbox.cascade,A=this.settings.checkbox.tie_selection;if(v&&v.original&&v.original.state&&v.original.state.undetermined){v.original.state.undetermined=false}if(B.indexOf("down")!==-1){for(x=0,u=v.children_d.length;x<u;x++){y=this._model.data[v.children_d[x]];y.state[A?"selected":"checked"]=false;if(y&&y.original&&y.original.state&&y.original.state.undetermined){y.original.state.undetermined=false}}}if(B.indexOf("up")!==-1){for(x=0,u=v.parents.length;x<u;x++){y=this._model.data[v.parents[x]];y.state[A?"selected":"checked"]=false;if(y&&y.original&&y.original.state&&y.original.state.undetermined){y.original.state.undetermined=false}y=this.get_node(v.parents[x],true);if(y&&y.length){y.children(".jstree-anchor").removeClass(A?"jstree-clicked":"jstree-checked")}}}y=[];for(x=0,u=this._data[A?"core":"checkbox"].selected.length;x<u;x++){if((B.indexOf("down")===-1||i.inArray(this._data[A?"core":"checkbox"].selected[x],v.children_d)===-1)&&(B.indexOf("up")===-1||i.inArray(this._data[A?"core":"checkbox"].selected[x],v.parents)===-1)){y.push(this._data[A?"core":"checkbox"].selected[x])}}this._data[A?"core":"checkbox"].selected=i.vakata.array_unique(y);if(B.indexOf("down")!==-1&&r.length){r.find(".jstree-anchor").removeClass(A?"jstree-clicked":"jstree-checked")}},this))}if(this.settings.checkbox.cascade.indexOf("up")!==-1){this.element.on("delete_node.jstree",i.proxy(function(y,v){var r=this.get_node(v.parent),s=this._model.data,w,u,z,x,A=this.settings.checkbox.tie_selection;while(r&&r.id!=="#"){z=0;for(w=0,u=r.children.length;w<u;w++){z+=s[r.children[w]].state[A?"selected":"checked"]}if(z===u){r.state[A?"selected":"checked"]=true;this._data[A?"core":"checkbox"].selected.push(r.id);x=this.get_node(r,true);if(x&&x.length){x.children(".jstree-anchor").addClass(A?"jstree-clicked":"jstree-checked")}}else{break}r=this.get_node(r.parent)}},this)).on("move_node.jstree",i.proxy(function(B,z){var v=z.is_multi,A=z.old_parent,r=this.get_node(z.parent),u=this._model.data,s,C,y,w,x,D=this.settings.checkbox.tie_selection;if(!v){s=this.get_node(A);while(s&&s.id!=="#"){C=0;for(y=0,w=s.children.length;y<w;y++){C+=u[s.children[y]].state[D?"selected":"checked"]}if(C===w){s.state[D?"selected":"checked"]=true;this._data[D?"core":"checkbox"].selected.push(s.id);x=this.get_node(s,true);if(x&&x.length){x.children(".jstree-anchor").addClass(D?"jstree-clicked":"jstree-checked")}}else{break}s=this.get_node(s.parent)}}s=r;while(s&&s.id!=="#"){C=0;for(y=0,w=s.children.length;y<w;y++){C+=u[s.children[y]].state[D?"selected":"checked"]}if(C===w){if(!s.state[D?"selected":"checked"]){s.state[D?"selected":"checked"]=true;this._data[D?"core":"checkbox"].selected.push(s.id);x=this.get_node(s,true);if(x&&x.length){x.children(".jstree-anchor").addClass(D?"jstree-clicked":"jstree-checked")}}}else{if(s.state[D?"selected":"checked"]){s.state[D?"selected":"checked"]=false;this._data[D?"core":"checkbox"].selected=i.vakata.array_remove_item(this._data[D?"core":"checkbox"].selected,s.id);x=this.get_node(s,true);if(x&&x.length){x.children(".jstree-anchor").removeClass(D?"jstree-clicked":"jstree-checked")}}else{break}}s=this.get_node(s.parent)}},this))}};this._undetermined=function(){var w,u,r=this._model.data,v=this.settings.checkbox.tie_selection,y=this._data[v?"core":"checkbox"].selected,z=[],x=this;for(w=0,u=y.length;w<u;w++){if(r[y[w]]&&r[y[w]].parents){z=z.concat(r[y[w]].parents)}}this.element.find(".jstree-closed").not(":has(.jstree-children)").each(function(){var s=x.get_node(this),t;if(!s.state.loaded){if(s.original&&s.original.state&&s.original.state.undetermined&&s.original.state.undetermined===true){z.push(s.id);z=z.concat(s.parents)}}else{for(w=0,u=s.children_d.length;w<u;w++){t=r[s.children_d[w]];if(!t.state.loaded&&t.original&&t.original.state&&t.original.state.undetermined&&t.original.state.undetermined===true){z.push(t.id);z=z.concat(t.parents)}}}});z=i.vakata.array_unique(z);z=i.vakata.array_remove_item(z,"#");this.element.find(".jstree-undetermined").removeClass("jstree-undetermined");for(w=0,u=z.length;w<u;w++){if(!r[z[w]].state[v?"selected":"checked"]){y=this.get_node(z[w],true);if(y&&y.length){y.children(".jstree-anchor").children(".jstree-checkbox").addClass("jstree-undetermined")}}}};this.redraw_node=function(w,r,v){w=q.redraw_node.call(this,w,r,v);if(w){var u,s,t=null;for(u=0,s=w.childNodes.length;u<s;u++){if(w.childNodes[u]&&w.childNodes[u].className&&w.childNodes[u].className.indexOf("jstree-anchor")!==-1){t=w.childNodes[u];break}}if(t){if(!this.settings.checkbox.tie_selection&&this._model.data[w.id].state.checked){t.className+=" jstree-checked"}t.insertBefore(h.cloneNode(false),t.childNodes[0])}}if(!v&&this.settings.checkbox.cascade.indexOf("undetermined")!==-1){if(this._data.checkbox.uto){clearTimeout(this._data.checkbox.uto)}this._data.checkbox.uto=setTimeout(i.proxy(this._undetermined,this),50)}return w};this.show_checkboxes=function(){this._data.core.themes.checkboxes=true;this.get_container_ul().removeClass("jstree-no-checkboxes")};this.hide_checkboxes=function(){this._data.core.themes.checkboxes=false;this.get_container_ul().addClass("jstree-no-checkboxes")};this.toggle_checkboxes=function(){if(this._data.core.themes.checkboxes){this.hide_checkboxes()}else{this.show_checkboxes()}};this.is_undetermined=function(y){y=this.get_node(y);var x=this.settings.checkbox.cascade,w,u,v=this.settings.checkbox.tie_selection,z=this._data[v?"core":"checkbox"].selected,r=this._model.data;if(!y||y.state[v?"selected":"checked"]===true||x.indexOf("undetermined")===-1||(x.indexOf("down")===-1&&x.indexOf("up")===-1)){return false}if(!y.state.loaded&&y.original.state.undetermined===true){return true}for(w=0,u=y.children_d.length;w<u;w++){if(i.inArray(y.children_d[w],z)!==-1||(!r[y.children_d[w]].state.loaded&&r[y.children_d[w]].original.state.undetermined)){return true}}return false};this.activate_node=function(s,r){if(this.settings.checkbox.tie_selection&&(this.settings.checkbox.whole_node||i(r.target).hasClass("jstree-checkbox"))){r.ctrlKey=true}if(this.settings.checkbox.tie_selection||(!this.settings.checkbox.whole_node&&!i(r.target).hasClass("jstree-checkbox"))){return q.activate_node.call(this,s,r)}if(this.is_checked(s)){this.uncheck_node(s,r)}else{this.check_node(s,r)}this.trigger("activate_node",{node:this.get_node(s)})};this.check_node=function(v,u){if(this.settings.checkbox.tie_selection){return this.select_node(v,false,true,u)}var w,t,r,s;if(i.isArray(v)){v=v.slice();for(t=0,r=v.length;t<r;t++){this.check_node(v[t],u)}return true}v=this.get_node(v);if(!v||v.id==="#"){return false}w=this.get_node(v,true);if(!v.state.checked){v.state.checked=true;this._data.checkbox.selected.push(v.id);if(w&&w.length){w.children(".jstree-anchor").addClass("jstree-checked")}this.trigger("check_node",{node:v,selected:this._data.checkbox.selected,event:u})}};this.uncheck_node=function(u,t){if(this.settings.checkbox.tie_selection){return this.deselect_node(u,false,t)}var s,r,v;if(i.isArray(u)){u=u.slice();for(s=0,r=u.length;s<r;s++){this.uncheck_node(u[s],t)}return true}u=this.get_node(u);if(!u||u.id==="#"){return false}v=this.get_node(u,true);if(u.state.checked){u.state.checked=false;this._data.checkbox.selected=i.vakata.array_remove_item(this._data.checkbox.selected,u.id);if(v.length){v.children(".jstree-anchor").removeClass("jstree-checked")}this.trigger("uncheck_node",{node:u,selected:this._data.checkbox.selected,event:t})}};this.check_all=function(){if(this.settings.checkbox.tie_selection){return this.select_all()}var t=this._data.checkbox.selected.concat([]),s,r;this._data.checkbox.selected=this._model.data["#"].children_d.concat();for(s=0,r=this._data.checkbox.selected.length;s<r;s++){if(this._model.data[this._data.checkbox.selected[s]]){this._model.data[this._data.checkbox.selected[s]].state.checked=true}}this.redraw(true);this.trigger("check_all",{selected:this._data.checkbox.selected})};this.uncheck_all=function(){if(this.settings.checkbox.tie_selection){return this.deselect_all()}var t=this._data.checkbox.selected.concat([]),s,r;for(s=0,r=this._data.checkbox.selected.length;s<r;s++){if(this._model.data[this._data.checkbox.selected[s]]){this._model.data[this._data.checkbox.selected[s]].state.checked=false}}this._data.checkbox.selected=[];this.element.find(".jstree-checked").removeClass("jstree-checked");this.trigger("uncheck_all",{selected:this._data.checkbox.selected,node:t})};this.is_checked=function(r){if(this.settings.checkbox.tie_selection){return this.is_selected(r)}r=this.get_node(r);if(!r||r.id==="#"){return false}return r.state.checked};this.get_checked=function(r){if(this.settings.checkbox.tie_selection){return this.get_selected(r)}return r?i.map(this._data.checkbox.selected,i.proxy(function(s){return this.get_node(s)},this)):this._data.checkbox.selected};this.get_top_checked=function(w){if(this.settings.checkbox.tie_selection){return this.get_top_selected(w)}var v=this.get_checked(true),x={},u,t,s,r;for(u=0,t=v.length;u<t;u++){x[v[u].id]=v[u]}for(u=0,t=v.length;u<t;u++){for(s=0,r=v[u].children_d.length;s<r;s++){if(x[v[u].children_d[s]]){delete x[v[u].children_d[s]]}}}v=[];for(u in x){if(x.hasOwnProperty(u)){v.push(u)}}return w?i.map(v,i.proxy(function(y){return this.get_node(y)},this)):v};this.get_bottom_checked=function(u){if(this.settings.checkbox.tie_selection){return this.get_bottom_selected(u)}var t=this.get_checked(true),v=[],s,r;for(s=0,r=t.length;s<r;s++){if(!t[s].children.length){v.push(t[s].id)}}return u?i.map(v,i.proxy(function(w){return this.get_node(w)},this)):v}};i.jstree.defaults.contextmenu={select_node:true,show_at_node:true,items:function(q,p){return{create:{separator_before:false,separator_after:true,_disabled:false,label:"Create",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);r.create_node(t,{},"last",function(u){setTimeout(function(){r.edit(u)},0)})}},rename:{separator_before:false,separator_after:false,_disabled:false,label:"Rename",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);r.edit(t)}},remove:{separator_before:false,icon:false,separator_after:false,_disabled:false,label:"Delete",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);if(r.is_selected(t)){r.delete_node(r.get_selected())}else{r.delete_node(t)}}},ccp:{separator_before:true,icon:false,separator_after:false,label:"Edit",action:false,submenu:{cut:{separator_before:false,separator_after:false,label:"Cut",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);if(r.is_selected(t)){r.cut(r.get_selected())}else{r.cut(t)}}},copy:{separator_before:false,icon:false,separator_after:false,label:"Copy",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);if(r.is_selected(t)){r.copy(r.get_selected())}else{r.copy(t)}}},paste:{separator_before:false,icon:false,_disabled:function(r){return !i.jstree.reference(r.reference).can_paste()},separator_after:false,label:"Paste",action:function(s){var r=i.jstree.reference(s.reference),t=r.get_node(s.reference);r.paste(t)}}}}}}};i.jstree.plugins.contextmenu=function(p,q){this.bind=function(){q.bind.call(this);var r=0;this.element.on("contextmenu.jstree",".jstree-anchor",i.proxy(function(s){s.preventDefault();r=s.ctrlKey?s.timeStamp:0;if(!this.is_loading(s.currentTarget)){this.show_contextmenu(s.currentTarget,s.pageX,s.pageY,s)}},this)).on("click.jstree",".jstree-anchor",i.proxy(function(s){if(this._data.contextmenu.visible&&(!r||s.timeStamp-r>250)){i.vakata.context.hide()}},this));i(document).on("context_hide.vakata",i.proxy(function(){this._data.contextmenu.visible=false},this))};this.teardown=function(){if(this._data.contextmenu.visible){i.vakata.context.hide()}q.teardown.call(this)};this.show_contextmenu=function(u,B,z,v){u=this.get_node(u);if(!u||u.id==="#"){return false}var C=this.settings.contextmenu,w=this.get_node(u,true),A=w.children(".jstree-anchor"),r=false,t=false;if(C.show_at_node||B===e||z===e){r=A.offset();B=r.left;z=r.top+this._data.core.li_height}if(this.settings.contextmenu.select_node&&!this.is_selected(u)){this.activate_node(u,v)}t=C.items;if(i.isFunction(t)){t=t.call(this,u,i.proxy(function(s){this._show_contextmenu(u,B,z,s)},this))}if(i.isPlainObject(t)){this._show_contextmenu(u,B,z,t)}};this._show_contextmenu=function(u,r,w,t){var v=this.get_node(u,true),s=v.children(".jstree-anchor");i(document).one("context_show.vakata",i.proxy(function(z,y){var x="jstree-contextmenu jstree-"+this.get_theme()+"-contextmenu";i(y.element).addClass(x)},this));this._data.contextmenu.visible=true;i.vakata.context.show(s,{x:r,y:w},t);this.trigger("show_contextmenu",{node:u,x:r,y:w})}};(function(q){var r=false,p={element:false,reference:false,position_x:0,position_y:0,items:[],html:"",is_visible:false};q.vakata.context={settings:{hide_onmouseleave:0,icons:true},_trigger:function(s){q(document).triggerHandler("context_"+s+".vakata",{reference:p.reference,element:p.element,position:{x:p.position_x,y:p.position_y}})},_execute:function(s){s=p.items[s];return s&&(!s._disabled||(q.isFunction(s._disabled)&&!s._disabled({item:s,reference:p.reference,element:p.element})))&&s.action?s.action.call(null,{item:s,reference:p.reference,element:p.element,position:{x:p.position_x,y:p.position_y}}):false},_parse:function(w,u){if(!w){return false}if(!u){p.html="";p.items=[]}var v="",s=false,t;if(u){v+="<ul>"}q.each(w,function(x,y){if(!y){return true}p.items.push(y);if(!s&&y.separator_before){v+="<li class='vakata-context-separator'><a href='#' "+(q.vakata.context.settings.icons?"":'style="margin-left:0px;"')+"> </a></li>"}s=false;v+="<li class='"+(y._class||"")+(y._disabled===true||(q.isFunction(y._disabled)&&y._disabled({item:y,reference:p.reference,element:p.element}))?" vakata-contextmenu-disabled ":"")+"' "+(y.shortcut?" data-shortcut='"+y.shortcut+"' ":"")+">";v+="<a href='#' rel='"+(p.items.length-1)+"'>";if(q.vakata.context.settings.icons){v+="<i ";if(y.icon){if(y.icon.indexOf("/")!==-1||y.icon.indexOf(".")!==-1){v+=" style='background:url(\""+y.icon+"\") center center no-repeat' "}else{v+=" class='"+y.icon+"' "}}v+="></i><span class='vakata-contextmenu-sep'> </span>"}v+=(q.isFunction(y.label)?y.label({item:x,reference:p.reference,element:p.element}):y.label)+(y.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+y.shortcut+'">'+(y.shortcut_label||"")+"</span>":"")+"</a>";if(y.submenu){t=q.vakata.context._parse(y.submenu,true);if(t){v+=t}}v+="</li>";if(y.separator_after){v+="<li class='vakata-context-separator'><a href='#' "+(q.vakata.context.settings.icons?"":'style="margin-left:0px;"')+"> </a></li>";s=true}});v=v.replace(/<li class\='vakata-context-separator'\><\/li\>$/,"");if(u){v+="</ul>"}if(!u){p.html=v;q.vakata.context._trigger("parse")}return v.length>10?v:false},_show_submenu:function(B){B=q(B);if(!B.length||!B.children("ul").length){return}var A=B.children("ul"),s=B.offset().left+B.outerWidth(),C=B.offset().top,t=A.width(),v=A.height(),u=q(window).width()+q(window).scrollLeft(),z=q(window).height()+q(window).scrollTop();if(r){B[s-(t+10+B.outerWidth())<0?"addClass":"removeClass"]("vakata-context-left")}else{B[s+t+10>u?"addClass":"removeClass"]("vakata-context-right")}if(C+v+10>z){A.css("bottom","-1px")}A.show()},show:function(u,A,v){var t,B,F,E,G,z,s,D,C=true;if(p.element&&p.element.length){p.element.width("")}switch(C){case (!A&&!u):return false;case (!!A&&!!u):p.reference=u;p.position_x=A.x;p.position_y=A.y;break;case (!A&&!!u):p.reference=u;t=u.offset();p.position_x=t.left+u.outerHeight();p.position_y=t.top;break;case (!!A&&!u):p.position_x=A.x;p.position_y=A.y;break}if(!!u&&!v&&q(u).data("vakata_contextmenu")){v=q(u).data("vakata_contextmenu")}if(q.vakata.context._parse(v)){p.element.html(p.html)}if(p.items.length){B=p.element;F=p.position_x;E=p.position_y;G=B.width();z=B.height();s=q(window).width()+q(window).scrollLeft();D=q(window).height()+q(window).scrollTop();if(r){F-=B.outerWidth();if(F<q(window).scrollLeft()+20){F=q(window).scrollLeft()+20}}if(F+G+20>s){F=s-(G+20)}if(E+z+20>D){E=D-(z+20)}p.element.css({left:F,top:E}).show().find("a:eq(0)").focus().parent().addClass("vakata-context-hover");p.is_visible=true;q.vakata.context._trigger("show")}},hide:function(){if(p.is_visible){p.element.hide().find("ul").hide().end().find(":focus").blur();p.is_visible=false;q.vakata.context._trigger("hide")}}};q(function(){r=q("body").css("direction")==="rtl";var s=false;p.element=q("<ul class='vakata-context'></ul>");p.element.on("mouseenter","li",function(t){t.stopImmediatePropagation();if(q.contains(this,t.relatedTarget)){return}if(s){clearTimeout(s)}p.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end();q(this).siblings().find("ul").hide().end().end().parentsUntil(".vakata-context","li").addBack().addClass("vakata-context-hover");q.vakata.context._show_submenu(this)}).on("mouseleave","li",function(t){if(q.contains(this,t.relatedTarget)){return}q(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover")}).on("mouseleave",function(t){q(this).find(".vakata-context-hover").removeClass("vakata-context-hover");if(q.vakata.context.settings.hide_onmouseleave){s=setTimeout((function(u){return function(){q.vakata.context.hide()}}(this)),q.vakata.context.settings.hide_onmouseleave)}}).on("click","a",function(t){t.preventDefault();if(!q(this).blur().parent().hasClass("vakata-context-disabled")&&q.vakata.context._execute(q(this).attr("rel"))!==false){q.vakata.context.hide()}}).on("keydown","a",function(t){var u=null;switch(t.which){case 13:case 32:t.type="mouseup";t.preventDefault();q(t.currentTarget).trigger(t);break;case 37:if(p.is_visible){p.element.find(".vakata-context-hover").last().parents("li:eq(0)").find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children("a").focus();t.stopImmediatePropagation();t.preventDefault()}break;case 38:if(p.is_visible){u=p.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first();if(!u.length){u=p.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last()}u.addClass("vakata-context-hover").children("a").focus();t.stopImmediatePropagation();t.preventDefault()}break;case 39:if(p.is_visible){p.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children("a").focus();t.stopImmediatePropagation();t.preventDefault()}break;case 40:if(p.is_visible){u=p.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first();if(!u.length){u=p.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first()}u.addClass("vakata-context-hover").children("a").focus();t.stopImmediatePropagation();t.preventDefault()}break;case 27:q.vakata.context.hide();t.preventDefault();break;default:break}}).on("keydown",function(u){u.preventDefault();var t=p.element.find(".vakata-contextmenu-shortcut-"+u.which).parent();if(t.parent().not(".vakata-context-disabled")){t.mouseup()}}).appendTo("body");q(document).on("mousedown",function(t){if(p.is_visible&&!q.contains(p.element[0],t.target)){q.vakata.context.hide()}}).on("context_show.vakata",function(u,t){p.element.find("li:has(ul)").children("a").addClass("vakata-context-parent");if(r){p.element.addClass("vakata-context-rtl").css("direction","rtl")}p.element.find("ul").hide().end()})})}(i));i.jstree.defaults.dnd={copy:true,open_timeout:500,is_draggable:true,check_while_dragging:true,always_copy:false,inside_pos:0};i.jstree.plugins.dnd=function(p,q){this.bind=function(){q.bind.call(this);this.element.on("mousedown.jstree touchstart.jstree",".jstree-anchor",i.proxy(function(t){var s=this.get_node(t.target),r=this.is_selected(s)?this.get_selected().length:1;if(s&&s.id&&s.id!=="#"&&(t.which===1||t.type==="touchstart")&&(this.settings.dnd.is_draggable===true||(i.isFunction(this.settings.dnd.is_draggable)&&this.settings.dnd.is_draggable.call(this,(r>1?this.get_selected(true):[s]))))){this.element.trigger("mousedown.jstree");return i.vakata.dnd.start(t,{jstree:true,origin:this,obj:this.get_node(s,true),nodes:r>1?this.get_selected():[s.id]},'<div id="jstree-dnd" class="jstree-'+this.get_theme()+(this.settings.core.themes.responsive?" jstree-dnd-responsive":"")+'"><i class="jstree-icon jstree-er"></i>'+(r>1?r+" "+this.get_string("nodes"):this.get_text(t.currentTarget,true))+'<ins class="jstree-copy" style="display:none;">+</ins></div>')}},this))}};i(function(){var s=false,r=false,q=false,p=i('<div id="jstree-marker"> </div>').hide().appendTo("body");i(document).bind("dnd_start.vakata",function(u,t){s=false}).bind("dnd_move.vakata",function(L,N){if(q){clearTimeout(q)}if(!N||!N.data||!N.data.jstree){return}if(N.event.target.id&&N.event.target.id==="jstree-marker"){return}var u=i.jstree.reference(N.event.target),x=false,M=false,v=false,I,D,K,E,J,F,C,B,A,z,G,H,y,w;if(u&&u._data&&u._data.dnd){p.attr("class","jstree-"+u.get_theme()+(u.settings.core.themes.responsive?" jstree-dnd-responsive":""));N.helper.children().attr("class","jstree-"+u.get_theme()+(u.settings.core.themes.responsive?" jstree-dnd-responsive":"")).find(".jstree-copy:eq(0)")[N.data.origin&&(N.data.origin.settings.dnd.always_copy||(N.data.origin.settings.dnd.copy&&(N.event.metaKey||N.event.ctrlKey)))?"show":"hide"]();if((N.event.target===u.element[0]||N.event.target===u.get_container_ul()[0])&&u.get_container_ul().children().length===0){C=true;for(B=0,A=N.data.nodes.length;B<A;B++){C=C&&u.check((N.data.origin&&(N.data.origin.settings.dnd.always_copy||(N.data.origin.settings.dnd.copy&&(N.event.metaKey||N.event.ctrlKey)))?"copy_node":"move_node"),(N.data.origin&&N.data.origin!==u?N.data.origin.get_node(N.data.nodes[B]):N.data.nodes[B]),"#","last",{dnd:true,ref:u.get_node("#"),pos:"i",is_multi:(N.data.origin&&N.data.origin!==u),is_foreign:(!N.data.origin)});if(!C){break}}if(C){s={ins:u,par:"#",pos:"last"};p.hide();N.helper.find(".jstree-icon:eq(0)").removeClass("jstree-er").addClass("jstree-ok");return}}else{x=i(N.event.target).closest(".jstree-anchor");if(x&&x.length&&x.parent().is(".jstree-closed, .jstree-open, .jstree-leaf")){M=x.offset();v=N.event.pageY-M.top;K=x.height();if(v<K/3){F=["b","i","a"]}else{if(v>K-K/3){F=["a","i","b"]}else{F=v>K/2?["i","a","b"]:["i","b","a"]}}i.each(F,function(O,t){switch(t){case"b":I=M.left-6;D=M.top;E=u.get_parent(x);J=x.parent().index();break;case"i":y=u.settings.dnd.inside_pos;w=u.get_node(x.parent());I=M.left-2;D=M.top+K/2+1;E=w.id;J=y==="first"?0:(y==="last"?w.children.length:Math.min(y,w.children.length));break;case"a":I=M.left-6;D=M.top+K;E=u.get_parent(x);J=x.parent().index()+1;break} +/* + // TODO: moving inside, but the node is not yet loaded? + // the check will work anyway, as when moving the node will be loaded first and checked again + if(v === 'i' && !ins.is_loaded(p)) { } + */ +C=true;for(B=0,A=N.data.nodes.length;B<A;B++){z=N.data.origin&&(N.data.origin.settings.dnd.always_copy||(N.data.origin.settings.dnd.copy&&(N.event.metaKey||N.event.ctrlKey)))?"copy_node":"move_node";G=J;if(z==="move_node"&&t==="a"&&(N.data.origin&&N.data.origin===u)&&E===u.get_parent(N.data.nodes[B])){H=u.get_node(E);if(G>i.inArray(N.data.nodes[B],H.children)){G-=1}}C=C&&((u&&u.settings&&u.settings.dnd&&u.settings.dnd.check_while_dragging===false)||u.check(z,(N.data.origin&&N.data.origin!==u?N.data.origin.get_node(N.data.nodes[B]):N.data.nodes[B]),E,G,{dnd:true,ref:u.get_node(x.parent()),pos:t,is_multi:(N.data.origin&&N.data.origin!==u),is_foreign:(!N.data.origin)}));if(!C){if(u&&u.last_error){r=u.last_error()}break}}if(C){if(t==="i"&&x.parent().is(".jstree-closed")&&u.settings.dnd.open_timeout){q=setTimeout((function(P,Q){return function(){P.open_node(Q)}}(u,x)),u.settings.dnd.open_timeout)}s={ins:u,par:E,pos:t==="i"&&y==="last"&&J===0&&!u.is_loaded(w)?"last":J};p.css({left:I+"px",top:D+"px"}).show();N.helper.find(".jstree-icon:eq(0)").removeClass("jstree-er").addClass("jstree-ok");r={};F=true;return false}});if(F===true){return}}}}s=false;N.helper.find(".jstree-icon").removeClass("jstree-ok").addClass("jstree-er");p.hide()}).bind("dnd_scroll.vakata",function(u,t){if(!t||!t.data||!t.data.jstree){return}p.hide();s=false;t.helper.find(".jstree-icon:eq(0)").removeClass("jstree-ok").addClass("jstree-er")}).bind("dnd_stop.vakata",function(x,w){if(q){clearTimeout(q)}if(!w||!w.data||!w.data.jstree){return}p.hide();var v,u,t=[];if(s){for(v=0,u=w.data.nodes.length;v<u;v++){t[v]=w.data.origin?w.data.origin.get_node(w.data.nodes[v]):w.data.nodes[v];if(w.data.origin){t[v].instance=w.data.origin}}s.ins[w.data.origin&&(w.data.origin.settings.dnd.always_copy||(w.data.origin.settings.dnd.copy&&(w.event.metaKey||w.event.ctrlKey)))?"copy_node":"move_node"](t,s.par,s.pos)}else{v=i(w.event.target).closest(".jstree");if(v.length&&r&&r.error&&r.error==="check"){v=v.jstree(true);if(v){v.settings.core.error.call(this,r)}}}}).bind("keyup keydown",function(u,t){t=i.vakata.dnd._get();if(t&&t.data&&t.data.jstree){t.helper.find(".jstree-copy:eq(0)")[t.data.origin&&(t.data.origin.settings.dnd.always_copy||(t.data.origin.settings.dnd.copy&&(u.metaKey||u.ctrlKey)))?"show":"hide"]()}})});(function(q){var p={element:false,target:false,is_down:false,is_drag:false,helper:false,helper_w:0,data:false,init_x:0,init_y:0,scroll_l:0,scroll_t:0,scroll_e:false,scroll_i:false,is_touch:false};q.vakata.dnd={settings:{scroll_speed:10,scroll_proximity:20,helper_left:5,helper_top:10,threshold:5,threshold_touch:50},_trigger:function(t,s){var r=q.vakata.dnd._get();r.event=s;q(document).triggerHandler("dnd_"+t+".vakata",r)},_get:function(){return{data:p.data,element:p.element,helper:p.helper}},_clean:function(){if(p.helper){p.helper.remove()}if(p.scroll_i){clearInterval(p.scroll_i);p.scroll_i=false}p={element:false,target:false,is_down:false,is_drag:false,helper:false,helper_w:0,data:false,init_x:0,init_y:0,scroll_l:0,scroll_t:0,scroll_e:false,scroll_i:false,is_touch:false};q(document).off("mousemove touchmove",q.vakata.dnd.drag);q(document).off("mouseup touchend",q.vakata.dnd.stop)},_scroll:function(t){if(!p.scroll_e||(!p.scroll_l&&!p.scroll_t)){if(p.scroll_i){clearInterval(p.scroll_i);p.scroll_i=false}return false}if(!p.scroll_i){p.scroll_i=setInterval(q.vakata.dnd._scroll,100);return false}if(t===true){return false}var s=p.scroll_e.scrollTop(),r=p.scroll_e.scrollLeft();p.scroll_e.scrollTop(s+p.scroll_t*q.vakata.dnd.settings.scroll_speed);p.scroll_e.scrollLeft(r+p.scroll_l*q.vakata.dnd.settings.scroll_speed);if(s!==p.scroll_e.scrollTop()||r!==p.scroll_e.scrollLeft()){q.vakata.dnd._trigger("scroll",p.scroll_e)}},start:function(t,s,r){if(t.type==="touchstart"&&t.originalEvent&&t.originalEvent.changedTouches&&t.originalEvent.changedTouches[0]){t.pageX=t.originalEvent.changedTouches[0].pageX;t.pageY=t.originalEvent.changedTouches[0].pageY;t.target=document.elementFromPoint(t.originalEvent.changedTouches[0].pageX-window.pageXOffset,t.originalEvent.changedTouches[0].pageY-window.pageYOffset)}if(p.is_drag){q.vakata.dnd.stop({})}try{t.currentTarget.unselectable="on";t.currentTarget.onselectstart=function(){return false};if(t.currentTarget.style){t.currentTarget.style.MozUserSelect="none"}}catch(u){}p.init_x=t.pageX;p.init_y=t.pageY;p.data=s;p.is_down=true;p.element=t.currentTarget;p.target=t.target;p.is_touch=t.type==="touchstart";if(r!==false){p.helper=q("<div id='vakata-dnd'></div>").html(r).css({display:"block",margin:"0",padding:"0",position:"absolute",top:"-2000px",lineHeight:"16px",zIndex:"10000"})}q(document).bind("mousemove touchmove",q.vakata.dnd.drag);q(document).bind("mouseup touchend",q.vakata.dnd.stop);return false},drag:function(y){if(y.type==="touchmove"&&y.originalEvent&&y.originalEvent.changedTouches&&y.originalEvent.changedTouches[0]){y.pageX=y.originalEvent.changedTouches[0].pageX;y.pageY=y.originalEvent.changedTouches[0].pageY;y.target=document.elementFromPoint(y.originalEvent.changedTouches[0].pageX-window.pageXOffset,y.originalEvent.changedTouches[0].pageY-window.pageYOffset)}if(!p.is_down){return}if(!p.is_drag){if(Math.abs(y.pageX-p.init_x)>(p.is_touch?q.vakata.dnd.settings.threshold_touch:q.vakata.dnd.settings.threshold)||Math.abs(y.pageY-p.init_y)>(p.is_touch?q.vakata.dnd.settings.threshold_touch:q.vakata.dnd.settings.threshold)){if(p.helper){p.helper.appendTo("body");p.helper_w=p.helper.outerWidth()}p.is_drag=true;q.vakata.dnd._trigger("start",y)}else{return}}var z=false,C=false,A=false,s=false,r=false,v=false,u=false,x=false,B=false,t=false;p.scroll_t=0;p.scroll_l=0;p.scroll_e=false;q(q(y.target).parentsUntil("body").addBack().get().reverse()).filter(function(){return(/^auto|scroll$/).test(q(this).css("overflow"))&&(this.scrollHeight>this.offsetHeight||this.scrollWidth>this.offsetWidth)}).each(function(){var w=q(this),D=w.offset();if(this.scrollHeight>this.offsetHeight){if(D.top+w.height()-y.pageY<q.vakata.dnd.settings.scroll_proximity){p.scroll_t=1}if(y.pageY-D.top<q.vakata.dnd.settings.scroll_proximity){p.scroll_t=-1}}if(this.scrollWidth>this.offsetWidth){if(D.left+w.width()-y.pageX<q.vakata.dnd.settings.scroll_proximity){p.scroll_l=1}if(y.pageX-D.left<q.vakata.dnd.settings.scroll_proximity){p.scroll_l=-1}}if(p.scroll_t||p.scroll_l){p.scroll_e=q(this);return false}});if(!p.scroll_e){z=q(document);C=q(window);A=z.height();s=C.height();r=z.width();v=C.width();u=z.scrollTop();x=z.scrollLeft();if(A>s&&y.pageY-u<q.vakata.dnd.settings.scroll_proximity){p.scroll_t=-1}if(A>s&&s-(y.pageY-u)<q.vakata.dnd.settings.scroll_proximity){p.scroll_t=1}if(r>v&&y.pageX-x<q.vakata.dnd.settings.scroll_proximity){p.scroll_l=-1}if(r>v&&v-(y.pageX-x)<q.vakata.dnd.settings.scroll_proximity){p.scroll_l=1}if(p.scroll_t||p.scroll_l){p.scroll_e=z}}if(p.scroll_e){q.vakata.dnd._scroll(true)}if(p.helper){B=parseInt(y.pageY+q.vakata.dnd.settings.helper_top,10);t=parseInt(y.pageX+q.vakata.dnd.settings.helper_left,10);if(A&&B+25>A){B=A-50}if(r&&t+p.helper_w>r){t=r-(p.helper_w+2)}p.helper.css({left:t+"px",top:B+"px"})}q.vakata.dnd._trigger("move",y);return false},stop:function(r){if(r.type==="touchend"&&r.originalEvent&&r.originalEvent.changedTouches&&r.originalEvent.changedTouches[0]){r.pageX=r.originalEvent.changedTouches[0].pageX;r.pageY=r.originalEvent.changedTouches[0].pageY;r.target=document.elementFromPoint(r.originalEvent.changedTouches[0].pageX-window.pageXOffset,r.originalEvent.changedTouches[0].pageY-window.pageYOffset)}if(p.is_drag){q.vakata.dnd._trigger("stop",r)}else{if(r.type==="touchend"&&r.target===p.target){var s=setTimeout(function(){q(r.target).click()},100);q(r.target).one("click",function(){if(s){clearTimeout(s)}})}}q.vakata.dnd._clean();return false}}}(i));i.jstree.defaults.search={ajax:false,fuzzy:false,case_sensitive:false,show_only_matches:false,close_opened_onclear:true,search_leaves_only:false,search_callback:false};i.jstree.plugins.search=function(p,q){this.bind=function(){q.bind.call(this);this._data.search.str="";this._data.search.dom=i();this._data.search.res=[];this._data.search.opn=[];this.element.on("before_open.jstree",i.proxy(function(z,y){var u,t,x,w=this._data.search.res,v=[],A=i();if(w&&w.length){this._data.search.dom=i(this.element[0].querySelectorAll("#"+i.map(w,function(r){return"0123456789".indexOf(r[0])!==-1?"\\3"+r[0]+" "+r.substr(1).replace(i.jstree.idregex,"\\$&"):r.replace(i.jstree.idregex,"\\$&")}).join(", #")));this._data.search.dom.children(".jstree-anchor").addClass("jstree-search");if(this.settings.search.show_only_matches&&this._data.search.res.length){for(u=0,t=w.length;u<t;u++){v=v.concat(this.get_node(w[u]).parents)}v=i.vakata.array_remove_item(i.vakata.array_unique(v),"#");A=v.length?i(this.element[0].querySelectorAll("#"+i.map(v,function(r){return"0123456789".indexOf(r[0])!==-1?"\\3"+r[0]+" "+r.substr(1).replace(i.jstree.idregex,"\\$&"):r.replace(i.jstree.idregex,"\\$&")}).join(", #"))):i();this.element.find(".jstree-node").hide().filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last");A=A.add(this._data.search.dom);A.parentsUntil(".jstree").addBack().show().filter(".jstree-children").each(function(){i(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last")})}}},this));if(this.settings.search.show_only_matches){this.element.on("search.jstree",function(s,r){if(r.nodes.length){i(this).find(".jstree-node").hide().filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last");r.nodes.parentsUntil(".jstree").addBack().show().filter(".jstree-children").each(function(){i(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last")})}}).on("clear_search.jstree",function(s,r){if(r.nodes.length){i(this).find(".jstree-node").css("display","").filter(".jstree-last").filter(function(){return this.nextSibling}).removeClass("jstree-last")}})}};this.search=function(y,A){if(y===false||i.trim(y.toString())===""){return this.clear_search()}y=y.toString();var B=this.settings.search,z=B.ajax?B.ajax:false,x=null,t=[],u=[],w,v;if(this._data.search.res.length){this.clear_search()}if(!A&&z!==false){if(i.isFunction(z)){return z.call(this,y,i.proxy(function(r){if(r&&r.d){r=r.d}this._load_nodes(!i.isArray(r)?[]:i.vakata.array_unique(r),function(){this.search(y,true)},true)},this))}else{z=i.extend({},z);if(!z.data){z.data={}}z.data.str=y;return i.ajax(z).fail(i.proxy(function(){this._data.core.last_error={error:"ajax",plugin:"search",id:"search_01",reason:"Could not load search parents",data:JSON.stringify(z)};this.settings.core.error.call(this,this._data.core.last_error)},this)).done(i.proxy(function(r){if(r&&r.d){r=r.d}this._load_nodes(!i.isArray(r)?[]:i.vakata.array_unique(r),function(){this.search(y,true)},true)},this))}}this._data.search.str=y;this._data.search.dom=i();this._data.search.res=[];this._data.search.opn=[];x=new i.vakata.search(y,true,{caseSensitive:B.case_sensitive,fuzzy:B.fuzzy});i.each(this._model.data,function(s,r){if(r.text&&((B.search_callback&&B.search_callback.call(this,y,r))||(!B.search_callback&&x.search(r.text).isMatch))&&(!B.search_leaves_only||(r.state.loaded&&r.children.length===0))){t.push(s);u=u.concat(r.parents)}});if(t.length){u=i.vakata.array_unique(u);this._search_open(u);this._data.search.dom=i(this.element[0].querySelectorAll("#"+i.map(t,function(r){return"0123456789".indexOf(r[0])!==-1?"\\3"+r[0]+" "+r.substr(1).replace(i.jstree.idregex,"\\$&"):r.replace(i.jstree.idregex,"\\$&")}).join(", #")));this._data.search.res=t;this._data.search.dom.children(".jstree-anchor").addClass("jstree-search")}this.trigger("search",{nodes:this._data.search.dom,str:y,res:this._data.search.res})};this.clear_search=function(){this._data.search.dom.children(".jstree-anchor").removeClass("jstree-search");if(this.settings.search.close_opened_onclear){this.close_node(this._data.search.opn,0)}this.trigger("clear_search",{nodes:this._data.search.dom,str:this._data.search.str,res:this._data.search.res});this._data.search.str="";this._data.search.res=[];this._data.search.opn=[];this._data.search.dom=i()};this._search_open=function(s){var r=this;i.each(s.concat([]),function(u,t){if(t==="#"){return true}try{t=i("#"+t.replace(i.jstree.idregex,"\\$&"),r.element)}catch(w){}if(t&&t.length){if(r.is_closed(t)){r._data.search.opn.push(t[0].id);r.open_node(t,function(){r._search_open(s)},0)}}})}};(function(p){p.vakata.search=function(v,t,A){A=A||{};if(A.fuzzy!==false){A.fuzzy=true}v=A.caseSensitive?v:v.toLowerCase();var x=A.location||0,y=A.distance||100,w=A.threshold||0.6,q=v.length,r,s,u,z;if(q>32){A.fuzzy=false}if(A.fuzzy){r=1<<(q-1);s=(function(){var B={},C=0;for(C=0;C<q;C++){B[v.charAt(C)]=0}for(C=0;C<q;C++){B[v.charAt(C)]|=1<<(q-C-1)}return B}());u=function(E,B){var D=E/q,C=Math.abs(x-B);if(!y){return C?1:D}return D+(C/y)}}z=function(O){O=A.caseSensitive?O:O.toLowerCase();if(v===O||O.indexOf(v)!==-1){return{isMatch:true,score:0}}if(!A.fuzzy){return{isMatch:false,score:1}}var J,I,N=O.length,F=w,H=O.indexOf(v,x),L,E,C=q+N,B,D,M,Q,P,G=1,K=[];if(H!==-1){F=Math.min(u(0,H),F);H=O.lastIndexOf(v,x+q);if(H!==-1){F=Math.min(u(0,H),F)}}H=-1;for(J=0;J<q;J++){L=0;E=C;while(L<E){if(u(J,x+E)<=F){L=E}else{C=E}E=Math.floor((C-L)/2+L)}C=E;D=Math.max(1,x-E+1);M=Math.min(x+E,N)+q;Q=new Array(M+2);Q[M+1]=(1<<J)-1;for(I=M;I>=D;I--){P=s[O.charAt(I-1)];if(J===0){Q[I]=((Q[I+1]<<1)|1)&P}else{Q[I]=((Q[I+1]<<1)|1)&P|(((B[I+1]|B[I])<<1)|1)|B[I+1]}if(Q[I]&r){G=u(J,I-1);if(G<=F){F=G;H=I-1;K.push(H);if(H>x){D=Math.max(1,2*x-H)}else{break}}}}if(u(J+1,x)>F){break}B=Q}return{isMatch:H>=0,score:G}};return t===true?{search:z}:z(t)}}(i));i.jstree.defaults.sort=function(q,p){return this.get_text(q)>this.get_text(p)?1:-1};i.jstree.plugins.sort=function(p,q){this.bind=function(){q.bind.call(this);this.element.on("model.jstree",i.proxy(function(s,r){this.sort(r.parent,true)},this)).on("rename_node.jstree create_node.jstree",i.proxy(function(s,r){this.sort(r.parent||r.node.parent,false);this.redraw_node(r.parent||r.node.parent,true)},this)).on("move_node.jstree copy_node.jstree",i.proxy(function(s,r){this.sort(r.parent,false);this.redraw_node(r.parent,true)},this))};this.sort=function(u,r){var t,s;u=this.get_node(u);if(u&&u.children&&u.children.length){u.children.sort(i.proxy(this.settings.sort,this));if(r){for(t=0,s=u.children_d.length;t<s;t++){this.sort(u.children_d[t],false)}}}}};var n=false;i.jstree.defaults.state={key:"jstree",events:"changed.jstree open_node.jstree close_node.jstree",ttl:false,filter:false};i.jstree.plugins.state=function(p,q){this.bind=function(){q.bind.call(this);var r=i.proxy(function(){this.element.on(this.settings.state.events,i.proxy(function(){if(n){clearTimeout(n)}n=setTimeout(i.proxy(function(){this.save_state()},this),100)},this))},this);this.element.on("ready.jstree",i.proxy(function(t,s){this.element.one("restore_state.jstree",r);if(!this.restore_state()){r()}},this))};this.save_state=function(){var r={state:this.get_state(),ttl:this.settings.state.ttl,sec:+(new Date())};i.vakata.storage.set(this.settings.state.key,JSON.stringify(r))};this.restore_state=function(){var r=i.vakata.storage.get(this.settings.state.key);if(!!r){try{r=JSON.parse(r)}catch(s){return false}}if(!!r&&r.ttl&&r.sec&&+(new Date())-r.sec>r.ttl){return false}if(!!r&&r.state){r=r.state}if(!!r&&i.isFunction(this.settings.state.filter)){r=this.settings.state.filter.call(this,r)}if(!!r){this.element.one("set_state.jstree",function(u,t){t.instance.trigger("restore_state",{state:i.extend(true,{},r)})});this.set_state(r);return true}return false};this.clear_state=function(){return i.vakata.storage.del(this.settings.state.key)}};(function(p,q){p.vakata.storage={set:function(r,s){return window.localStorage.setItem(r,s)},get:function(r){return window.localStorage.getItem(r)},del:function(r){return window.localStorage.removeItem(r)}}}(i));i.jstree.defaults.types={"#":{},"default":{}};i.jstree.plugins.types=function(p,q){this.init=function(u,s){var t,r;if(s&&s.types&&s.types["default"]){for(t in s.types){if(t!=="default"&&t!=="#"&&s.types.hasOwnProperty(t)){for(r in s.types["default"]){if(s.types["default"].hasOwnProperty(r)&&s.types[t][r]===e){s.types[t][r]=s.types["default"][r]}}}}}q.init.call(this,u,s);this._model.data["#"].type="#"};this.refresh=function(s,r){q.refresh.call(this,s,r);this._model.data["#"].type="#"};this.bind=function(){this.element.on("model.jstree",i.proxy(function(x,w){var r=this._model.data,z=w.nodes,v=this.settings.types,u,s,y="default";for(u=0,s=z.length;u<s;u++){y="default";if(r[z[u]].original&&r[z[u]].original.type&&v[r[z[u]].original.type]){y=r[z[u]].original.type}if(r[z[u]].data&&r[z[u]].data.jstree&&r[z[u]].data.jstree.type&&v[r[z[u]].data.jstree.type]){y=r[z[u]].data.jstree.type}r[z[u]].type=y;if(r[z[u]].icon===true&&v[y].icon!==e){r[z[u]].icon=v[y].icon}}r["#"].type="#"},this));q.bind.call(this)};this.get_json=function(x,t,y){var w,s,r=this._model.data,v=t?i.extend(true,{},t,{no_id:false}):{},u=q.get_json.call(this,x,v,y);if(u===false){return false}if(i.isArray(u)){for(w=0,s=u.length;w<s;w++){u[w].type=u[w].id&&r[u[w].id]&&r[u[w].id].type?r[u[w].id].type:"default";if(t&&t.no_id){delete u[w].id;if(u[w].li_attr&&u[w].li_attr.id){delete u[w].li_attr.id}}}}else{u.type=u.id&&r[u.id]&&r[u.id].type?r[u.id].type:"default";if(t&&t.no_id){u=this._delete_ids(u)}}return u};this._delete_ids=function(t){if(i.isArray(t)){for(var s=0,r=t.length;s<r;s++){t[s]=this._delete_ids(t[s])}return t}delete t.id;if(t.li_attr&&t.li_attr.id){delete t.li_attr.id}if(t.children&&i.isArray(t.children)){t.children=this._delete_ids(t.children)}return t};this.check=function(z,u,x,A,y){if(q.check.call(this,z,u,x,A,y)===false){return false}u=u&&u.id?u:this.get_node(u);x=x&&x.id?x:this.get_node(x);var r=u&&u.id?i.jstree.reference(u.id):null,v,w,t,s;r=r&&r._model&&r._model.data?r._model.data:null;switch(z){case"create_node":case"move_node":case"copy_node":if(z!=="move_node"||i.inArray(u.id,x.children)===-1){v=this.get_rules(x);if(v.max_children!==e&&v.max_children!==-1&&v.max_children===x.children.length){this._data.core.last_error={error:"check",plugin:"types",id:"types_01",reason:"max_children prevents function: "+z,data:JSON.stringify({chk:z,pos:A,obj:u&&u.id?u.id:false,par:x&&x.id?x.id:false})};return false}if(v.valid_children!==e&&v.valid_children!==-1&&i.inArray(u.type,v.valid_children)===-1){this._data.core.last_error={error:"check",plugin:"types",id:"types_02",reason:"valid_children prevents function: "+z,data:JSON.stringify({chk:z,pos:A,obj:u&&u.id?u.id:false,par:x&&x.id?x.id:false})};return false}if(r&&u.children_d&&u.parents){w=0;for(t=0,s=u.children_d.length;t<s;t++){w=Math.max(w,r[u.children_d[t]].parents.length)}w=w-u.parents.length+1}if(w<=0||w===e){w=1}do{if(v.max_depth!==e&&v.max_depth!==-1&&v.max_depth<w){this._data.core.last_error={error:"check",plugin:"types",id:"types_03",reason:"max_depth prevents function: "+z,data:JSON.stringify({chk:z,pos:A,obj:u&&u.id?u.id:false,par:x&&x.id?x.id:false})};return false}x=this.get_node(x.parent);v=this.get_rules(x);w++}while(x)}break}return true};this.get_rules=function(s){s=this.get_node(s);if(!s){return false}var r=this.get_type(s,true);if(r.max_depth===e){r.max_depth=-1}if(r.max_children===e){r.max_children=-1}if(r.valid_children===e){r.valid_children=-1}return r};this.get_type=function(r,s){r=this.get_node(r);return(!r)?false:(s?i.extend({type:r.type},this.settings.types[r.type]):r.type)};this.set_type=function(y,w){var u,x,v,s,r;if(i.isArray(y)){y=y.slice();for(x=0,v=y.length;x<v;x++){this.set_type(y[x],w)}return true}u=this.settings.types;y=this.get_node(y);if(!u[w]||!y){return false}s=y.type;r=this.get_icon(y);y.type=w;if(r===true||(u[s]&&u[s].icon&&r===u[s].icon)){this.set_icon(y,u[w].icon!==e?u[w].icon:true)}return true}};i.jstree.defaults.unique={case_sensitive:false,duplicate:function(q,p){return q+" ("+p+")"}};i.jstree.plugins.unique=function(p,q){this.check=function(A,w,x,B,y){if(q.check.call(this,A,w,x,B,y)===false){return false}w=w&&w.id?w:this.get_node(w);x=x&&x.id?x:this.get_node(x);if(!x||!x.children){return true}var r=A==="rename_node"?B:w.text,z=[],C=this.settings.unique.case_sensitive,t=this._model.data,v,u;for(v=0,u=x.children.length;v<u;v++){z.push(C?t[x.children[v]].text:t[x.children[v]].text.toLowerCase())}if(!C){r=r.toLowerCase()}switch(A){case"delete_node":return true;case"rename_node":v=(i.inArray(r,z)===-1||(w.text&&w.text[C?"toString":"toLowerCase"]()===r));if(!v){this._data.core.last_error={error:"check",plugin:"unique",id:"unique_01",reason:"Child with name "+r+" already exists. Preventing: "+A,data:JSON.stringify({chk:A,pos:B,obj:w&&w.id?w.id:false,par:x&&x.id?x.id:false})}}return v;case"create_node":v=(i.inArray(r,z)===-1);if(!v){this._data.core.last_error={error:"check",plugin:"unique",id:"unique_04",reason:"Child with name "+r+" already exists. Preventing: "+A,data:JSON.stringify({chk:A,pos:B,obj:w&&w.id?w.id:false,par:x&&x.id?x.id:false})}}return v;case"copy_node":v=(i.inArray(r,z)===-1);if(!v){this._data.core.last_error={error:"check",plugin:"unique",id:"unique_02",reason:"Child with name "+r+" already exists. Preventing: "+A,data:JSON.stringify({chk:A,pos:B,obj:w&&w.id?w.id:false,par:x&&x.id?x.id:false})}}return v;case"move_node":v=(w.parent===x.id||i.inArray(r,z)===-1);if(!v){this._data.core.last_error={error:"check",plugin:"unique",id:"unique_03",reason:"Child with name "+r+" already exists. Preventing: "+A,data:JSON.stringify({chk:A,pos:B,obj:w&&w.id?w.id:false,par:x&&x.id?x.id:false})}}return v}return true};this.create_node=function(A,u,C,D,B){if(!u||u.text===e){if(A===null){A="#"}A=this.get_node(A);if(!A){return q.create_node.call(this,A,u,C,D,B)}C=C===e?"last":C;if(!C.toString().match(/^(before|after)$/)&&!B&&!this.is_loaded(A)){return q.create_node.call(this,A,u,C,D,B)}if(!u){u={}}var y,r,z,x,w,t=this._model.data,E=this.settings.unique.case_sensitive,v=this.settings.unique.duplicate;r=y=this.get_string("New node");z=[];for(x=0,w=A.children.length;x<w;x++){z.push(E?t[A.children[x]].text:t[A.children[x]].text.toLowerCase())}x=1;while(i.inArray(E?r:r.toLowerCase(),z)!==-1){r=v.call(this,y,(++x)).toString()}u.text=r}return q.create_node.call(this,A,u,C,D,B)}};var b=document.createElement("DIV");b.setAttribute("unselectable","on");b.className="jstree-wholerow";b.innerHTML=" ";i.jstree.plugins.wholerow=function(p,q){this.bind=function(){q.bind.call(this);this.element.on("ready.jstree set_state.jstree",i.proxy(function(){this.hide_dots()},this)).on("init.jstree loading.jstree ready.jstree",i.proxy(function(){this.get_container_ul().addClass("jstree-wholerow-ul")},this)).on("deselect_all.jstree",i.proxy(function(s,r){this.element.find(".jstree-wholerow-clicked").removeClass("jstree-wholerow-clicked")},this)).on("changed.jstree",i.proxy(function(v,u){this.element.find(".jstree-wholerow-clicked").removeClass("jstree-wholerow-clicked");var t=false,s,r;for(s=0,r=u.selected.length;s<r;s++){t=this.get_node(u.selected[s],true);if(t&&t.length){t.children(".jstree-wholerow").addClass("jstree-wholerow-clicked")}}},this)).on("open_node.jstree",i.proxy(function(s,r){this.get_node(r.node,true).find(".jstree-clicked").parent().children(".jstree-wholerow").addClass("jstree-wholerow-clicked")},this)).on("hover_node.jstree dehover_node.jstree",i.proxy(function(s,r){this.get_node(r.node,true).children(".jstree-wholerow")[s.type==="hover_node"?"addClass":"removeClass"]("jstree-wholerow-hovered")},this)).on("contextmenu.jstree",".jstree-wholerow",i.proxy(function(s){s.preventDefault();var r=i.Event("contextmenu",{metaKey:s.metaKey,ctrlKey:s.ctrlKey,altKey:s.altKey,shiftKey:s.shiftKey,pageX:s.pageX,pageY:s.pageY});i(s.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(r)},this)).on("click.jstree",".jstree-wholerow",function(s){s.stopImmediatePropagation();var r=i.Event("click",{metaKey:s.metaKey,ctrlKey:s.ctrlKey,altKey:s.altKey,shiftKey:s.shiftKey});i(s.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(r).focus()}).on("click.jstree",".jstree-leaf > .jstree-ocl",i.proxy(function(s){s.stopImmediatePropagation();var r=i.Event("click",{metaKey:s.metaKey,ctrlKey:s.ctrlKey,altKey:s.altKey,shiftKey:s.shiftKey});i(s.currentTarget).closest(".jstree-node").children(".jstree-anchor:eq(0)").trigger(r).focus()},this)).on("mouseover.jstree",".jstree-wholerow, .jstree-icon",i.proxy(function(r){r.stopImmediatePropagation();this.hover_node(r.currentTarget);return false},this)).on("mouseleave.jstree",".jstree-node",i.proxy(function(r){this.dehover_node(r.currentTarget)},this))};this.teardown=function(){if(this.settings.wholerow){this.element.find(".jstree-wholerow").remove()}q.teardown.call(this)};this.redraw_node=function(t,r,u){t=q.redraw_node.call(this,t,r,u);if(t){var s=b.cloneNode(true);if(i.inArray(t.id,this._data.core.selected)!==-1){s.className+=" jstree-wholerow-clicked"}t.insertBefore(s,t.childNodes[0])}return t}}})); \ No newline at end of file https://bitbucket.org/galaxy/galaxy-central/commits/a5b5351b4cf3/ Changeset: a5b5351b4cf3 User: martenson Date: 2014-09-08 18:59:10+00:00 Summary: attributions Affected #: 2 files diff -r ecf83c3a2d0383c74e30dca41b602854326c7ee7 -r a5b5351b4cf3bf74ccc841d7b8ffe9c859f5d03e lib/galaxy/util/dictobj.py --- a/lib/galaxy/util/dictobj.py +++ b/lib/galaxy/util/dictobj.py @@ -2,6 +2,10 @@ class DictionaryObject(object): """ + Helper class written by William Grim - grimwm + Original repo: https://github.com/grimwm/py-dictobj + Thank you! + ************************ A class that has all the functionality of a normal Python dictionary, except for the fact it is itself immutable. It also has the added feature of being able to lookup values by using keys as attributes. diff -r ecf83c3a2d0383c74e30dca41b602854326c7ee7 -r a5b5351b4cf3bf74ccc841d7b8ffe9c859f5d03e lib/galaxy/util/jstree.py --- a/lib/galaxy/util/jstree.py +++ b/lib/galaxy/util/jstree.py @@ -8,6 +8,11 @@ class Node(dictobj.DictionaryObject): """ + Helper class written by William Grim - grimwm + Original repo: https://github.com/grimwm/py-jstree + Code adjusted according to the idea of Frank Blechschmidt - FraBle + Thank you! + ************************ This class exists as a helper to the JSTree. Its "jsonData" method can generate sub-tree JSON without putting the logic directly into the JSTree. https://bitbucket.org/galaxy/galaxy-central/commits/a4a6834f4b2f/ Changeset: a4a6834f4b2f User: martenson Date: 2014-09-08 19:03:47+00:00 Summary: more attributions Affected #: 2 files diff -r a5b5351b4cf3bf74ccc841d7b8ffe9c859f5d03e -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 lib/galaxy/util/dictobj.py --- a/lib/galaxy/util/dictobj.py +++ b/lib/galaxy/util/dictobj.py @@ -2,6 +2,20 @@ class DictionaryObject(object): """ + Copyright 2012 "Grim Apps" + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Helper class written by William Grim - grimwm Original repo: https://github.com/grimwm/py-dictobj Thank you! diff -r a5b5351b4cf3bf74ccc841d7b8ffe9c859f5d03e -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 lib/galaxy/util/jstree.py --- a/lib/galaxy/util/jstree.py +++ b/lib/galaxy/util/jstree.py @@ -8,6 +8,20 @@ class Node(dictobj.DictionaryObject): """ + Copyright 2012 "Grim Apps" + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Helper class written by William Grim - grimwm Original repo: https://github.com/grimwm/py-jstree Code adjusted according to the idea of Frank Blechschmidt - FraBle https://bitbucket.org/galaxy/galaxy-central/commits/858c12951cfa/ Changeset: 858c12951cfa User: martenson Date: 2014-09-16 15:39:17+00:00 Summary: allow admins to paste paths, pack scripts Affected #: 6 files diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b lib/galaxy/webapps/galaxy/api/lda_datasets.py --- a/lib/galaxy/webapps/galaxy/api/lda_datasets.py +++ b/lib/galaxy/webapps/galaxy/api/lda_datasets.py @@ -435,22 +435,28 @@ link_data = util.string_as_bool( kwd.get( 'link_data', False ) ) source = kwd.get( 'source', None ) - if source not in [ 'userdir_file', 'userdir_folder' ]: - raise exceptions.RequestParameterMissingException( 'You have to specify "source" parameter. Possible values are "userdir_file" and "userdir_folder". ') + if source not in [ 'userdir_file', 'userdir_folder', 'admin_path' ]: + raise exceptions.RequestParameterMissingException( 'You have to specify "source" parameter. Possible values are "userdir_file", "userdir_folder" and "admin_path". ') - user_login = trans.user.email - user_base_dir = trans.app.config.user_library_import_dir - if user_base_dir is None: - raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from user directories.' ) - full_dir = os.path.join( user_base_dir, user_login ) - # path_to_root_import_folder = None - if not path.lower().startswith( full_dir.lower() ): - # path_to_root_import_folder = path - path = os.path.join( full_dir, path ) - if not os.path.exists( path ): - raise exceptions.RequestParameterInvalidException( 'Given path does not exist on the host.' ) - if not self.folder_manager.can_add_item( trans, folder ): - raise exceptions.InsufficientPermissionsException( 'You do not have proper permission to add items to the given folder.' ) + if source in [ 'userdir_file', 'userdir_folder' ]: + user_login = trans.user.email + user_base_dir = trans.app.config.user_library_import_dir + if user_base_dir is None: + raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow upload from user directories.' ) + full_dir = os.path.join( user_base_dir, user_login ) + # path_to_root_import_folder = None + if not path.lower().startswith( full_dir.lower() ): + # path_to_root_import_folder = path + path = os.path.join( full_dir, path ) + if not os.path.exists( path ): + raise exceptions.RequestParameterInvalidException( 'Given path does not exist on the host.' ) + if not self.folder_manager.can_add_item( trans, folder ): + raise exceptions.InsufficientPermissionsException( 'You do not have proper permission to add items to the given folder.' ) + if source == 'admin_path': + if not trans.app.config.allow_library_path_paste: + raise exceptions.ConfigDoesNotAllowException( 'The configuration of this Galaxy instance does not allow admins to import into library from path.' ) + if not trans.user_is_admin: + raise exceptions.AdminRequiredException( 'Only admins can import from path.' ) # Set up the traditional tool state/params tool_id = 'upload1' @@ -466,24 +472,32 @@ abspath_datasets = [] kwd[ 'filesystem_paths' ] = path params = util.Params( kwd ) - # file only + # user wants to import one file only if source == "userdir_file": file = os.path.abspath( path ) abspath_datasets.append( trans.webapp.controllers[ 'library_common' ].make_library_uploaded_dataset( trans, 'api', params, os.path.basename( file ), file, 'server_dir', library_bunch ) ) - # whole folder + # user wants to import whole folder if source == "userdir_folder": # import_folder_root = [next(part for part in path.split(os.path.sep) if part) for path in [os.path.splitdrive(path_to_root_import_folder)[1]]] # new_folder = self.folder_manager.create( trans, folder_id, import_folder_root[0] ) uploaded_datasets_bunch = trans.webapp.controllers[ 'library_common' ].get_path_paste_uploaded_datasets( trans, 'api', params, library_bunch, 200, '' ) - uploaded_datasets = uploaded_datasets_bunch[0] if uploaded_datasets is None: - # TODO no files found - only create folders - return False - + raise exceptions.ObjectNotFound( 'Given folder does not contain any datasets.' ) + for ud in uploaded_datasets: + ud.path = os.path.abspath( ud.path ) + abspath_datasets.append( ud ) + # user wants to import from path (admins only) + if source == "admin_path": + # validate the path is within root + uploaded_datasets_bunch = trans.webapp.controllers[ 'library_common' ].get_path_paste_uploaded_datasets( + trans, 'api', params, library_bunch, 200, '' ) + uploaded_datasets = uploaded_datasets_bunch[0] + if uploaded_datasets is None: + raise exceptions.ObjectNotFound( 'Given folder does not contain any datasets.' ) for ud in uploaded_datasets: ud.path = os.path.abspath( ud.path ) abspath_datasets.append( ud ) diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b static/scripts/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/mvc/library/library-foldertoolbar-view.js @@ -199,10 +199,9 @@ }, /** - * import all selected datasets into history + * Import all selected datasets into history. */ importAllIntoHistory : function (){ - // disable the button to prevent multiple submission this.modal.disableButton('Import'); // init the control counters @@ -288,7 +287,11 @@ $('.completion_span').text(txt_representation); }, - // download selected datasets + /** + * download selected datasets + * @param {str} folder_id id of the current folder + * @param {str} format requested archive format + */ download : function(folder_id, format){ var dataset_ids = []; $('#folder_table').find(':checked').each(function(){ @@ -296,29 +299,34 @@ dataset_ids.push(this.parentElement.parentElement.id); } }); - var url = '/api/libraries/datasets/download/' + format; var data = {'ldda_ids' : dataset_ids}; this.processDownload(url, data, 'get'); }, - // create hidden form and submit through POST to initialize download + /** + * Create hidden form and submit it through POST + * to initialize the download. + * @param {str} url url to call + * @param {obj} data data to include in the request + * @param {str} method method of the request + */ processDownload: function(url, data, method){ - //url and data options required - if( url && data ){ - //data can be string of parameters or array/object - data = typeof data === 'string' ? data : $.param(data); - //split params into form inputs - var inputs = ''; - $.each(data.split('&'), function(){ - var pair = this.split('='); - inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; - }); - //send request - $('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>') - .appendTo('body').submit().remove(); - - mod_toastr.info('Your download will begin soon'); + if ( url && data ){ + // data can be string of parameters or array/object + data = typeof data === 'string' ? data : $.param(data); + // split params into form inputs + var inputs = ''; + $.each(data.split('&'), function(){ + var pair = this.split('='); + inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; + }); + // send request + $('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>') + .appendTo('body').submit().remove(); + mod_toastr.info('Your download will begin soon'); + } else { + mod_toastr.error('An error occurred :('); } }, @@ -352,6 +360,33 @@ }); }, + /** + * Create modal for importing from Galaxy path. + * This feature is admin-only. + */ + importFilesFromPathModal: function(){ + var that = this; + this.modal = Galaxy.modal; + var template_modal = this.templateImportPathModal(); + this.modal.show({ + closing_events : true, + title : 'Enter paths relative to Galaxy root', + body : template_modal({}), + buttons : { + 'Import' : function() {that.importFromPathsClicked(that);}, + 'Close' : function() {Galaxy.modal.hide();} + }, + closing_callback: function(){ + // TODO: should not trigger routes outside of the router + Galaxy.libraries.library_router.navigate('folders/' + that.id, {trigger: true}); + } + }); + }, + + /** + * Create modal for importing form user's directory + * on Galaxy. Bind jQuery events. + */ importFilesFromUserdirModal: function(){ var that = this; this.modal = Galaxy.modal; @@ -373,23 +408,28 @@ $('input[type=radio]').change(function(event){ if (event.target.value ==='jstree-disable-folders') { + that.renderJstree({disabled_jstree_element: 'folders'}); $('.jstree-folders-message').hide(); $('.jstree-preserve-structure').hide(); $('.jstree-link-files').hide(); $('.jstree-files-message').show(); - - that.renderJstree({disabled_jstree_element: 'folders'}); } else if (event.target.value ==='jstree-disable-files'){ - that.renderJstree({disabled_jstree_element: 'files'}); $('.jstree-files-message').hide(); $('.jstree-folders-message').show(); $('.jstree-link-files').show(); $('.jstree-preserve-structure').show(); + that.renderJstree({disabled_jstree_element: 'files'}); } } ); }, + /** + * Fetch the contents of user directory on Galaxy + * and render jstree component based on received + * data. + * @param {[type]} options [description] + */ renderJstree: function(options){ var that = this; this.options = _.extend(this.options, options); @@ -427,13 +467,51 @@ }) }, - importFoldersFromUserdir: function(){ - + /** + * Take the paths from the textarea, split it, create + * a request queue and call a function that starts sending + * one by one to be imported on the server. + */ + importFromPathsClicked: function(){ + var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); + var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); + var paths = $('textarea#import_paths').val(); + if (!paths){ + mod_toastr.info('Please enter a path relative to Galaxy root'); + } else { + this.modal.disableButton('Import'); + paths = paths.split('\n'); + var valid_paths = []; + for (var i = paths.length - 1; i >= 0; i--) { + trimmed = paths[i].trim(); + if (trimmed.length!==0){ + valid_paths.push(trimmed); + } + }; + this.initChainCallControl(valid_paths.length); + this.chainCallImportingFolders(valid_paths, preserve_dirs, link_data, 'admin_path'); + } }, + /** + * Initialize the control of chaining requests + * in the current modal. + */ + initChainCallControl: function(length){ + var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); + this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); + this.progress = 0; + this.progressStep = 100 / length; + this.options.chain_call_control.total_number = length; + this.options.chain_call_control.failed_number = 0; + }, - // add all selected datasets from user directory into current folder - importFromUserdirClicked : function (that){ + /** + * Take the selected items from the jstree, create a request queue + * and send them one by one to the server for importing into + * the current folder. + */ + importFromUserdirClicked: function (that){ var selected_nodes = $('#jstree_browser').jstree().get_selected(true); var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); @@ -443,7 +521,7 @@ } else { // disable the button to prevent multiple submission this.modal.disableButton('Import'); - // init the control counters + // init the chain control counters this.options.chain_call_control.total_number = 0; this.options.chain_call_control.failed_number = 0; @@ -452,9 +530,8 @@ paths.push(selected_nodes[i].li_attr.full_path); } } - var folder_name = this.options.folder_name; var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : folder_name })); + this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); // init the progress bar this.progressStep = 100 / paths.length; @@ -464,13 +541,18 @@ var selection_type = selected_nodes[0].type; // call the recursive function to call ajax one after each other (request FIFO queue) if (selection_type === 'folder'){ - this.chainCallImportingUserdirFolders(paths, preserve_dirs, link_data); + this.chainCallImportingFolders(paths, preserve_dirs, link_data, 'userdir_folder'); } else if (selection_type === 'file'){ this.chainCallImportingUserdirFiles(paths); } } }, + /** + * Take the array of paths and createa request for each of them + * calling them in chain. Update the progress bar in between each. + * @param {array} paths paths relative to user folder on Galaxy + */ chainCallImportingUserdirFiles: function(paths){ var that = this; var popped_item = paths.pop(); @@ -483,21 +565,30 @@ } return true; } - var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + '&source=userdir_file&path=' + popped_item)) + var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + + '&source=userdir_file' + + '&path=' + popped_item)) promise.done(function(response){ - // we are fine that.updateProgress(); that.chainCallImportingUserdirFiles(paths); }) .fail(function(){ - // we have a problem that.options.chain_call_control.failed_number += 1; that.updateProgress(); that.chainCallImportingUserdirFiles(paths); }); }, - chainCallImportingUserdirFolders: function(paths, preserve_dirs, link_data){ + /** + * Take the array of paths and createa request for each of them + * calling them in chain. Update the progress bar in between each. + * @param {array} paths paths relative to Galaxy root folder + * @param {boolean} preserve_dirs indicates whether to preserve folder structure + * @param {boolean} link_data copy files to Galaxy or link instead + * @param {str} source string representing what type of folder + * is the source of import + */ + chainCallImportingFolders: function(paths, preserve_dirs, link_data, source){ // need to check which paths to call var that = this; var popped_item = paths.pop(); @@ -508,23 +599,20 @@ } else { mod_toastr.error('Something went wrong :('); } - return true; } var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + - '&source=userdir_folder' + + '&source=' + source + '&path=' + popped_item + '&preserve_dirs=' + preserve_dirs + - '&link_data=' + link_data )) + '&link_data=' + link_data)) promise.done(function(response){ - // we are fine that.updateProgress(); - that.chainCallImportingUserdirFolders(paths); + that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); }) .fail(function(){ - // we have a problem that.options.chain_call_control.failed_number += 1; that.updateProgress(); - that.chainCallImportingUserdirFolders(paths); + that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); }); }, @@ -566,9 +654,8 @@ history_dataset_ids.push(hid); } }); - var folder_name = this.options.folder_name; var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : folder_name })); + this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); // init the progress bar this.progressStep = 100 / history_dataset_ids.length; @@ -759,7 +846,7 @@ case "importdir": break; case "path": - mod_toastr.info('Coming soon.'); + this.importFilesFromPathModal(); break; case "userdir": this.importFilesFromUserdirModal(); @@ -961,6 +1048,30 @@ return _.template(tmpl_array.join('')); }, + templateImportPathModal: function(){ + var tmpl_array = []; + + tmpl_array.push('<div id="file_browser_modal">'); + + tmpl_array.push('<label class="checkbox-inline jstree-preserve-structure">'); + tmpl_array.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">'); + tmpl_array.push('Preserve directory structure'); + tmpl_array.push(' </label>'); + + tmpl_array.push('<label class="checkbox-inline jstree-link-files">'); + tmpl_array.push(' <input class="link-checkbox" type="checkbox" value="link_files">'); + tmpl_array.push('Link files instead of copying'); + tmpl_array.push(' </label>'); + tmpl_array.push('</div>'); + + tmpl_array.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>'); + + tmpl_array.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>'); + tmpl_array.push('</div>'); + + return _.template(tmpl_array.join('')); + }, + templateAddFilesFromHistory: function (){ var tmpl_array = []; diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b static/scripts/packed/galaxy.library.js --- a/static/scripts/packed/galaxy.library.js +++ b/static/scripts/packed/galaxy.library.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr","mvc/base-mvc","mvc/library/library-model","mvc/library/library-folderlist-view","mvc/library/library-librarylist-view","mvc/library/library-librarytoolbar-view","mvc/library/library-foldertoolbar-view","mvc/library/library-dataset-view","mvc/library/library-library-view","mvc/library/library-folder-view"],function(h,e,j,n,k,c,i,g,l,f,b,a){var o=Backbone.Router.extend({initialize:function(){this.routesHit=0;Backbone.history.on("route",function(){this.routesHit++},this)},routes:{"":"libraries","library/:library_id/permissions":"library_permissions","folders/:folder_id/permissions":"folder_permissions","folders/:id":"folder_content","folders/:folder_id/datasets/:dataset_id":"dataset_detail","folders/:folder_id/datasets/:dataset_id/permissions":"dataset_permissions","folders/:folder_id/datasets/:dataset_id/versions/:ldda_id":"dataset_version","folders/:folder_id/download/:format":"download"},back:function(){if(this.routesHit>1){window.history.back()}else{this.navigate("#",{trigger:true,replace:true})}}});var m=n.SessionStorageModel.extend({defaults:{with_deleted:false,sort_order:"asc",sort_by:"name"}});var d=Backbone.View.extend({libraryToolbarView:null,libraryListView:null,library_router:null,libraryView:null,folderToolbarView:null,folderListView:null,datasetView:null,initialize:function(){Galaxy.libraries=this;this.preferences=new m({id:"global-lib-prefs"});this.library_router=new o();this.library_router.on("route:libraries",function(){Galaxy.libraries.libraryToolbarView=new g.LibraryToolbarView();Galaxy.libraries.libraryListView=new i.LibraryListView()});this.library_router.on("route:folder_content",function(p){if(Galaxy.libraries.folderToolbarView){Galaxy.libraries.folderToolbarView.$el.unbind("click")}Galaxy.libraries.folderToolbarView=new l.FolderToolbarView({id:p});Galaxy.libraries.folderListView=new c.FolderListView({id:p})});this.library_router.on("route:download",function(p,q){if($("#folder_list_body").find(":checked").length===0){j.info("You have to select some datasets to download");Galaxy.libraries.library_router.navigate("folders/"+p,{trigger:true,replace:true})}else{Galaxy.libraries.folderToolbarView.download(p,q);Galaxy.libraries.library_router.navigate("folders/"+p,{trigger:false,replace:true})}});this.library_router.on("route:dataset_detail",function(q,p){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p})});this.library_router.on("route:dataset_version",function(q,p,r){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p,ldda_id:r,show_version:true})});this.library_router.on("route:dataset_permissions",function(q,p){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p,show_permissions:true})});this.library_router.on("route:library_permissions",function(p){if(Galaxy.libraries.libraryView){Galaxy.libraries.libraryView.$el.unbind("click")}Galaxy.libraries.libraryView=new b.LibraryView({id:p,show_permissions:true})});this.library_router.on("route:folder_permissions",function(p){if(Galaxy.libraries.folderView){Galaxy.libraries.folderView.$el.unbind("click")}Galaxy.libraries.folderView=new a.FolderView({id:p,show_permissions:true})});Backbone.history.start({pushState:false})}});return{GalaxyApp:d}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr","mvc/base-mvc","mvc/library/library-model","mvc/library/library-folderlist-view","mvc/library/library-librarylist-view","mvc/library/library-librarytoolbar-view","mvc/library/library-foldertoolbar-view","mvc/library/library-dataset-view","mvc/library/library-library-view","mvc/library/library-folder-view"],function(h,e,j,n,k,c,i,g,l,f,b,a){var o=Backbone.Router.extend({initialize:function(){this.routesHit=0;Backbone.history.on("route",function(){this.routesHit++},this)},routes:{"":"libraries","library/:library_id/permissions":"library_permissions","folders/:folder_id/permissions":"folder_permissions","folders/:id":"folder_content","folders/:folder_id/datasets/:dataset_id":"dataset_detail","folders/:folder_id/datasets/:dataset_id/permissions":"dataset_permissions","folders/:folder_id/datasets/:dataset_id/versions/:ldda_id":"dataset_version","folders/:folder_id/download/:format":"download","folders/:folder_id/import/:source":"import_datasets"},back:function(){if(this.routesHit>1){window.history.back()}else{this.navigate("#",{trigger:true,replace:true})}}});var m=n.SessionStorageModel.extend({defaults:{with_deleted:false,sort_order:"asc",sort_by:"name"}});var d=Backbone.View.extend({libraryToolbarView:null,libraryListView:null,library_router:null,libraryView:null,folderToolbarView:null,folderListView:null,datasetView:null,initialize:function(){Galaxy.libraries=this;this.preferences=new m({id:"global-lib-prefs"});this.library_router=new o();this.library_router.on("route:libraries",function(){Galaxy.libraries.libraryToolbarView=new g.LibraryToolbarView();Galaxy.libraries.libraryListView=new i.LibraryListView()});this.library_router.on("route:folder_content",function(p){if(Galaxy.libraries.folderToolbarView){Galaxy.libraries.folderToolbarView.$el.unbind("click")}Galaxy.libraries.folderToolbarView=new l.FolderToolbarView({id:p});Galaxy.libraries.folderListView=new c.FolderListView({id:p})});this.library_router.on("route:download",function(p,q){if($("#folder_list_body").find(":checked").length===0){j.info("You have to select some datasets to download");Galaxy.libraries.library_router.navigate("folders/"+p,{trigger:true,replace:true})}else{Galaxy.libraries.folderToolbarView.download(p,q);Galaxy.libraries.library_router.navigate("folders/"+p,{trigger:false,replace:true})}});this.library_router.on("route:dataset_detail",function(q,p){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p})});this.library_router.on("route:dataset_version",function(q,p,r){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p,ldda_id:r,show_version:true})});this.library_router.on("route:dataset_permissions",function(q,p){if(Galaxy.libraries.datasetView){Galaxy.libraries.datasetView.$el.unbind("click")}Galaxy.libraries.datasetView=new f.LibraryDatasetView({id:p,show_permissions:true})});this.library_router.on("route:library_permissions",function(p){if(Galaxy.libraries.libraryView){Galaxy.libraries.libraryView.$el.unbind("click")}Galaxy.libraries.libraryView=new b.LibraryView({id:p,show_permissions:true})});this.library_router.on("route:folder_permissions",function(p){if(Galaxy.libraries.folderView){Galaxy.libraries.folderView.$el.unbind("click")}Galaxy.libraries.folderView=new a.FolderView({id:p,show_permissions:true})});this.library_router.on("route:import_datasets",function(p,q){if(Galaxy.libraries.folderToolbarView&&Galaxy.libraries.folderListView){Galaxy.libraries.folderToolbarView.showImportModal({source:q})}else{Galaxy.libraries.folderToolbarView=new l.FolderToolbarView({id:p});Galaxy.libraries.folderListView=new c.FolderListView({id:p});Galaxy.libraries.folderToolbarView.showImportModal({source:q})}});Backbone.history.start({pushState:false})}});return{GalaxyApp:d}}); \ No newline at end of file diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b static/scripts/packed/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/packed/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/packed/mvc/library/library-foldertoolbar-view.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr","mvc/library/library-model"],function(b,d,e,c){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click .toolbtn_add_files":"addFilesToFolderModal","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0}},modal:null,histories:null,initialize:function(f){this.options=_.defaults(f||{},this.defaults);this.render()},render:function(g){this.options=_.extend(this.options,g);var i=false;var f=true;if(Galaxy.currUser){i=Galaxy.currUser.isAdmin();f=Galaxy.currUser.isAnonymous()}var h=this.templateToolBar();this.$el.html(h({id:this.options.id,admin_user:i,anonym:f}))},configureElements:function(f){this.options=_.extend(this.options,f);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(h){h.preventDefault();h.stopPropagation();var f=this;var g=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:g(),buttons:{Create:function(){f.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var f=this.serialize_new_folder();if(this.validate_new_folder(f)){var g=new c.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];g.url=g.urlRoot+"/"+current_folder_id;g.save(f,{success:function(h){Galaxy.modal.hide();e.success("Folder created");h.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(h)},error:function(i,h){Galaxy.modal.hide();if(typeof h.responseJSON!=="undefined"){e.error(h.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})}else{e.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(f){return f.name!==""},modalBulkImport:function(){var f=$("#folder_table").find(":checked");if(f.length===0){e.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(g){var h=g.templateBulkImportInModal();g.modal=Galaxy.modal;g.modal.show({closing_events:true,title:"Import into History",body:h({histories:g.histories.models}),buttons:{Import:function(){g.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(g){var f=this;this.histories=new c.GalaxyHistories();this.histories.fetch({success:function(){g(f)},error:function(i,h){if(typeof h.responseJSON!=="undefined"){e.error(h.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var j=$("select[name=dataset_import_bulk] option:selected").val();this.options.last_used_history_id=j;var m=$("select[name=dataset_import_bulk] option:selected").text();var o=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){o.push(this.parentElement.parentElement.id)}});var n=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(n({history_name:m}));var k=100/o.length;this.initProgress(k);var f=[];for(var g=o.length-1;g>=0;g--){var h=o[g];var l=new c.HistoryItem();l.url=l.urlRoot+j+"/contents";l.content=h;l.source="library";f.push(l)}this.options.chain_call_control.total_number=f.length;jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+historyId);this.chainCall(f,m)},chainCall:function(g,j){var f=this;var h=g.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return}var i=$.when(h.save({content:h.content,source:h.source}));i.done(function(){f.updateProgress();f.chainCall(g,j)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCall(g,j)})},initProgress:function(f){this.progress=0;this.progressStep=f},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(f,j){var h=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});var g="/api/libraries/datasets/download/"+j;var i={ldda_ids:h};this.processDownload(g,i,"get")},processDownload:function(g,h,i){if(g&&h){h=typeof h==="string"?h:$.param(h);var f="";$.each(h.split("&"),function(){var j=this.split("=");f+='<input type="hidden" name="'+j[0]+'" value="'+j[1]+'" />'});$('<form action="'+g+'" method="'+(i||"post")+'">'+f+"</form>").appendTo("body").submit().remove();e.info("Your download will begin soon")}},addFilesToFolderModal:function(){this.refreshUserHistoriesList(function(f){f.modal=Galaxy.modal;var g=f.templateAddFilesInModal();var h=f.options.full_path[f.options.full_path.length-1][1];f.modal.show({closing_events:true,title:"Add datasets from history to "+h,body:g({histories:f.histories.models}),buttons:{Add:function(){f.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}}});if(f.histories.models.length>0){f.fetchAndDisplayHistoryContents(f.histories.models[0].id);$("#dataset_add_bulk").change(function(i){f.fetchAndDisplayHistoryContents(i.target.value)})}else{e.error("An error ocurred :(")}})},fetchAndDisplayHistoryContents:function(h){var g=new c.HistoryContents({id:h});var f=this;g.fetch({success:function(j){var i=f.templateHistoryContents();f.histories.get(h).set({contents:j});f.modal.$el.find("#selected_history_content").html(i({history_contents:j.models.reverse()}))},error:function(j,i){if(typeof i.responseJSON!=="undefined"){e.error(i.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){this.modal.disableButton("Add");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var f=[];this.modal.$el.find("#selected_history_content").find(":checked").each(function(){var i=$(this.parentElement).data("id");if(i){f.push(i)}});var l=this.options.folder_name;var k=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(k({folder_name:l}));this.progressStep=100/f.length;this.progress=0;var j=[];for(var h=f.length-1;h>=0;h--){history_dataset_id=f[h];var g=new c.Item();g.url="/api/folders/"+this.options.id+"/contents";g.set({from_hda_id:history_dataset_id});j.push(g)}this.options.chain_call_control.total_number=j.length;this.chainCallAddingHdas(j)},chainCallAddingHdas:function(g){var f=this;this.added_hdas=new c.Folder();var h=g.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var i=$.when(h.save({from_hda_id:h.get("from_hda_id")}));i.done(function(j){Galaxy.libraries.folderListView.collection.add(j);f.updateProgress();f.chainCallAddingHdas(g)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallAddingHdas(g)})},checkIncludeDeleted:function(f){if(f.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var f=$("#folder_table").find(":checked");if(f.length===0){e.info("You have to select some datasets first")}else{var j=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:j({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];f.each(function(){if(this.parentElement.parentElement.id!==""){g.push(this.parentElement.parentElement.id)}});this.progressStep=100/g.length;this.progress=0;var l=[];for(var h=g.length-1;h>=0;h--){var k=new c.Item({id:g[h]});l.push(k)}this.options.chain_call_control.total_number=g.length;this.chainCallDeletingHdas(l)}},chainCallDeletingHdas:function(g){var f=this;this.deleted_lddas=new c.Folder();var h=g.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var i=$.when(h.destroy());i.done(function(k){Galaxy.libraries.folderListView.collection.remove(h.id);f.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var j=new c.Item(k);Galaxy.libraries.folderListView.collection.add(j)}f.chainCallDeletingHdas(g)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallDeletingHdas(g)})},showLibInfo:function(){var g=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var f=null;var h=this;if(Galaxy.libraries.libraryListView!==null){f=Galaxy.libraries.libraryListView.collection.get(g)}else{f=new c.Library({id:g});f.fetch({success:function(){var i=h.templateLibInfoInModal();h.modal=Galaxy.modal;h.modal.show({closing_events:true,title:"Library Information",body:i({library:f}),buttons:{Close:function(){Galaxy.modal.hide()}}})},error:function(j,i){if(typeof i.responseJSON!=="undefined"){e.error(i.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li id="download_archive"><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li id="download_archive"><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li id="download_archive"><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var f=[];f.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');f.push("Select history: ");f.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');f.push(" <% _.each(histories, function(history) { %>");f.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');f.push(" <% }); %>");f.push("</select>");f.push("</span>");return _.template(f.join(""))},templateImportIntoHistoryProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateAddingDatasetsProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>");f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateDeletingDatasetsProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-delete" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateAddFilesInModal:function(){var f=[];f.push('<div id="add_files_modal">');f.push('<div id="history_modal_combo_bulk">');f.push("Select history: ");f.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');f.push(" <% _.each(histories, function(history) { %>");f.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');f.push(" <% }); %>");f.push("</select>");f.push("</div>");f.push('<div id="selected_history_content">');f.push("</div>");f.push("</div>");return _.template(f.join(""))},templateHistoryContents:function(){var f=[];f.push("Choose the datasets to import:");f.push("<ul>");f.push(" <% _.each(history_contents, function(history_item) { %>");f.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');f.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');f.push(" </li>");f.push(" <% }); %>");f.push("</ul>");return _.template(f.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr","libs/jquery/jstree","mvc/library/library-model"],function(c,e,f,b,d){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0},disabled_jstree_element:"folders"},modal:null,jstree:null,histories:null,initialize:function(g){this.options=_.defaults(g||{},this.defaults);this.render()},render:function(g){this.options=_.extend(this.options,g);var i=this.templateToolBar();var h={id:this.options.id,is_admin:false,is_anonym:true,user_library_import_dir:Galaxy.config.user_library_import_dir,allow_library_path_paste:Galaxy.config.allow_library_path_paste,library_import_dir:Galaxy.config.library_import_dir,mutiple_add_dataset_options:false};if(Galaxy.currUser){h.is_admin=Galaxy.currUser.isAdmin();h.is_anonym=Galaxy.currUser.isAnonymous();if(h.user_library_import_dir!==null||h.allow_library_path_paste!==false||h.library_import_dir!==null){h.mutiple_add_dataset_options=true}}this.$el.html(i(h))},configureElements:function(g){this.options=_.extend(this.options,g);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(i){i.preventDefault();i.stopPropagation();var g=this;var h=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:h(),buttons:{Create:function(){g.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var g=this.serialize_new_folder();if(this.validate_new_folder(g)){var h=new d.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];h.url=h.urlRoot+"/"+current_folder_id;h.save(g,{success:function(i){Galaxy.modal.hide();f.success("Folder created");i.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(i)},error:function(j,i){Galaxy.modal.hide();if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}else{f.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(g){return g.name!==""},modalBulkImport:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(i){var h=i.templateBulkImportInModal();i.modal=Galaxy.modal;i.modal.show({closing_events:true,title:"Import into History",body:h({histories:i.histories.models}),buttons:{Import:function(){i.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(h){var g=this;this.histories=new d.GalaxyHistories();this.histories.fetch({success:function(){h(g)},error:function(j,i){if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var k=$("select[name=dataset_import_bulk] option:selected").val();this.options.last_used_history_id=k;var n=$("select[name=dataset_import_bulk] option:selected").text();var p=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){p.push(this.parentElement.parentElement.id)}});var o=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(o({history_name:n}));var l=100/p.length;this.initProgress(l);var g=[];for(var h=p.length-1;h>=0;h--){var j=p[h];var m=new d.HistoryItem();m.url=m.urlRoot+k+"/contents";m.content=j;m.source="library";g.push(m)}this.options.chain_call_control.total_number=g.length;jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+k);this.chainCall(g,n)},chainCall:function(h,k){var g=this;var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return}var j=$.when(i.save({content:i.content,source:i.source}));j.done(function(){g.updateProgress();g.chainCall(h,k)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCall(h,k)})},initProgress:function(g){this.progress=0;this.progressStep=g},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(g,k){var i=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){i.push(this.parentElement.parentElement.id)}});var h="/api/libraries/datasets/download/"+k;var j={ldda_ids:i};this.processDownload(h,j,"get")},processDownload:function(h,i,j){if(h&&i){i=typeof i==="string"?i:$.param(i);var g="";$.each(i.split("&"),function(){var k=this.split("=");g+='<input type="hidden" name="'+k[0]+'" value="'+k[1]+'" />'});$('<form action="'+h+'" method="'+(j||"post")+'">'+g+"</form>").appendTo("body").submit().remove();f.info("Your download will begin soon")}else{f.error("An error occurred :(")}},addFilesFromHistoryModal:function(){this.refreshUserHistoriesList(function(g){g.modal=Galaxy.modal;var h=g.templateAddFilesFromHistory();var i=g.options.full_path[g.options.full_path.length-1][1];g.modal.show({closing_events:true,title:"Adding datasets from your history to folder "+i,body:h({histories:g.histories.models}),buttons:{Add:function(){g.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.back()}});if(g.histories.models.length>0){g.fetchAndDisplayHistoryContents(g.histories.models[0].id);$("#dataset_add_bulk").change(function(j){g.fetchAndDisplayHistoryContents(j.target.value)})}else{f.error("An error ocurred :(")}})},importFilesFromPathModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateImportPathModal();this.modal.show({closing_events:true,title:"Enter paths relative to Galaxy root",body:g({}),buttons:{Import:function(){h.importFromPathsClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}})},importFilesFromUserdirModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateBrowserModal();this.modal.show({closing_events:true,title:"Select folders or files to import",body:g({}),buttons:{Import:function(){h.importFromUserdirClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}});this.renderJstree({disabled_jstree_element:"folders"});$("input[type=radio]").change(function(i){if(i.target.value==="jstree-disable-folders"){h.renderJstree({disabled_jstree_element:"folders"});$(".jstree-folders-message").hide();$(".jstree-preserve-structure").hide();$(".jstree-link-files").hide();$(".jstree-files-message").show()}else{if(i.target.value==="jstree-disable-files"){$(".jstree-files-message").hide();$(".jstree-folders-message").show();$(".jstree-link-files").show();$(".jstree-preserve-structure").show();h.renderJstree({disabled_jstree_element:"files"})}}})},renderJstree:function(g){var i=this;this.options=_.extend(this.options,g);var h=this.options.disabled_jstree_element;this.jstree=new d.Jstree();this.jstree.url=this.jstree.urlRoot+"?target=userdir&format=jstree&disable="+h;this.jstree.fetch({success:function(k,j){$("#jstree_browser").jstree("destroy");var l=$("#jstree_browser").jstree({core:{data:k},plugins:["types","checkbox"],types:{folder:{icon:"jstree-folder"},file:{icon:"jstree-file"}},checkbox:{three_state:false}})},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importFromPathsClicked:function(){var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var l=this.modal.$el.find(".link-checkbox").is(":checked");var k=$("textarea#import_paths").val();if(!k){f.info("Please enter a path relative to Galaxy root")}else{this.modal.disableButton("Import");k=k.split("\n");var j=[];for(var h=k.length-1;h>=0;h--){trimmed=k[h].trim();if(trimmed.length!==0){j.push(trimmed)}}this.initChainCallControl(j.length);this.chainCallImportingFolders(j,g,l,"admin_path")}},initChainCallControl:function(g){var h=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(h({folder_name:this.options.folder_name}));this.progress=0;this.progressStep=100/g;this.options.chain_call_control.total_number=g;this.options.chain_call_control.failed_number=0},importFromUserdirClicked:function(l){var h=$("#jstree_browser").jstree().get_selected(true);var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var o=this.modal.$el.find(".link-checkbox").is(":checked");var n=[];if(h.length<1){f.info("You have to select some items first")}else{this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;for(var j=h.length-1;j>=0;j--){if(h[j].li_attr.full_path!==undefined){n.push(h[j].li_attr.full_path)}}var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/n.length;this.progress=0;this.options.chain_call_control.total_number=n.length;var k=h[0].type;if(k==="folder"){this.chainCallImportingFolders(n,g,o,"userdir_folder")}else{if(k==="file"){this.chainCallImportingUserdirFiles(n)}}}},chainCallImportingUserdirFiles:function(j){var g=this;var h=j.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected files imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var i=$.when($.post("/api/libraries/datasets?encoded_folder_id="+g.id+"&source=userdir_file&path="+h));i.done(function(k){g.updateProgress();g.chainCallImportingUserdirFiles(j)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallImportingUserdirFiles(j)})},chainCallImportingFolders:function(l,g,m,j){var h=this;var i=l.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected folders and their contents imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}}var k=$.when($.post("/api/libraries/datasets?encoded_folder_id="+h.id+"&source="+j+"&path="+i+"&preserve_dirs="+g+"&link_data="+m));k.done(function(n){h.updateProgress();h.chainCallImportingFolders(l,g,m,j)}).fail(function(){h.options.chain_call_control.failed_number+=1;h.updateProgress();h.chainCallImportingFolders(l,g,m,j)})},fetchAndDisplayHistoryContents:function(i){var h=new d.HistoryContents({id:i});var g=this;h.fetch({success:function(k){var j=g.templateHistoryContents();g.histories.get(i).set({contents:k});g.modal.$el.find("#selected_history_content").html(j({history_contents:k.models.reverse()}))},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){var l=this.modal.$el.find("#selected_history_content").find(":checked");if(l.length<1){f.info("You have to select some datasets first")}else{this.modal.disableButton("Add");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];l.each(function(){var i=$(this.parentElement).data("id");if(i){g.push(i)}});var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/g.length;this.progress=0;var k=[];for(var j=g.length-1;j>=0;j--){history_dataset_id=g[j];var h=new d.Item();h.url="/api/folders/"+this.options.id+"/contents";h.set({from_hda_id:history_dataset_id});k.push(h)}this.options.chain_call_control.total_number=k.length;this.chainCallAddingHdas(k)}},chainCallAddingHdas:function(h){var g=this;this.added_hdas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var j=$.when(i.save({from_hda_id:i.get("from_hda_id")}));j.done(function(k){Galaxy.libraries.folderListView.collection.add(k);g.updateProgress();g.chainCallAddingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallAddingHdas(h)})},checkIncludeDeleted:function(g){if(g.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{var k=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:k({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var h=[];g.each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});this.progressStep=100/h.length;this.progress=0;var m=[];for(var j=h.length-1;j>=0;j--){var l=new d.Item({id:h[j]});m.push(l)}this.options.chain_call_control.total_number=h.length;this.chainCallDeletingHdas(m)}},chainCallDeletingHdas:function(h){var g=this;this.deleted_lddas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var j=$.when(i.destroy());j.done(function(l){Galaxy.libraries.folderListView.collection.remove(i.id);g.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var k=new d.Item(l);Galaxy.libraries.folderListView.collection.add(k)}g.chainCallDeletingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallDeletingHdas(h)})},showLibInfo:function(){var h=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var g=null;var i=this;if(Galaxy.libraries.libraryListView!==null){g=Galaxy.libraries.libraryListView.collection.get(h);this.showLibInfoModal(g)}else{g=new d.Library({id:h});g.fetch({success:function(){i.showLibInfoModal(g)},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}},showLibInfoModal:function(g){var h=this.templateLibInfoInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Library Information",body:h({library:g}),buttons:{Close:function(){Galaxy.modal.hide()}}})},showImportModal:function(g){switch(g.source){case"history":this.addFilesFromHistoryModal();break;case"importdir":break;case"path":this.importFilesFromPathModal();break;case"userdir":this.importFilesFromUserdirModal();break;default:Galaxy.libraries.library_router.back();f.error("Invalid import source.");break}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push("<% if(mutiple_add_dataset_options) { %>");tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button title="Add Datasets to Current Folder" id="" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-plus"></span><span class="fa fa-file"></span><span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#folders/<%= id %>/import/history"> from History</a></li>');tmpl_array.push("<% if(user_library_import_dir !== null) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/userdir"> from User Directory</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li class="divider"></li>');tmpl_array.push(' <li class="dropdown-header">Admins only</li>');tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/path">from Path</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% } %>");tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push("<% } else { %>");tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push("<% } %>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var g=[];g.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');g.push("Select history: ");g.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</span>");return _.template(g.join(""))},templateImportIntoHistoryProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateAddingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateDeletingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateBrowserModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<div style="margin-bottom:1em;">');g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting files" type="radio" name="jstree-radio" value="jstree-disable-folders" checked="checked"> Files');g.push("</label>");g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting folders" type="radio" name="jstree-radio" value="jstree-disable-files"> Folders');g.push("</label>");g.push('<label class="checkbox-inline jstree-preserve-structure" style="display:none;">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files" style="display:none;">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-files-message">All files you select will be imported into the current folder.</div>');g.push('<div class="alert alert-info jstree-folders-message" style="display:none;">All files within the selected folders and their subfolders will be imported into the current folder.</div>');g.push('<div id="jstree_browser">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateImportPathModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<label class="checkbox-inline jstree-preserve-structure">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>');g.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>');g.push("</div>");return _.template(g.join(""))},templateAddFilesFromHistory:function(){var g=[];g.push('<div id="add_files_modal">');g.push('<div id="history_modal_combo_bulk">');g.push("Select history: ");g.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</div>");g.push("<br/>");g.push('<div id="selected_history_content">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateHistoryContents:function(){var g=[];g.push("<strong>Choose the datasets to import:</strong>");g.push("<ul>");g.push(" <% _.each(history_contents, function(history_item) { %>");g.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');g.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');g.push(" </li>");g.push(" <% }); %>");g.push("</ul>");return _.template(g.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b static/scripts/packed/mvc/library/library-libraryrow-view.js --- a/static/scripts/packed/mvc/library/library-libraryrow-view.js +++ b/static/scripts/packed/mvc/library/library-libraryrow-view.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr"],function(b,c,d){var a=Backbone.View.extend({events:{"click .edit_library_btn":"edit_button_clicked","click .cancel_library_btn":"cancel_library_modification","click .save_library_btn":"save_library_modification","click .delete_library_btn":"delete_library","click .undelete_library_btn":"undelete_library","click .permission_library_btn":"permissions_on_library"},edit_mode:false,element_visibility_config:{upload_library_btn:false,edit_library_btn:false,permission_library_btn:false,save_library_btn:false,cancel_library_btn:false,delete_library_btn:false,undelete_library_btn:false},initialize:function(e){this.render(e)},render:function(f){if(typeof f==="undefined"){f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"))}this.prepareButtons(f);var e=this.templateRow();this.setElement(e({library:f,button_config:this.element_visibility_config,edit_mode:this.edit_mode}));this.$el.show();return this},repaint:function(e){$(".tooltip").hide();var f=this.$el;this.render(e);f.replaceWith(this.$el);this.$el.find("[data-toggle]").tooltip()},prepareButtons:function(e){vis_config=this.element_visibility_config;if(this.edit_mode===false){vis_config.save_library_btn=false;vis_config.cancel_library_btn=false;vis_config.delete_library_btn=false;if(e.get("deleted")===true){vis_config.undelete_library_btn=true;vis_config.upload_library_btn=false;vis_config.edit_library_btn=false;vis_config.permission_library_btn=false}else{if(e.get("deleted")===false){vis_config.save_library_btn=false;vis_config.cancel_library_btn=false;vis_config.undelete_library_btn=false;if(e.get("can_user_add")===true){vis_config.upload_library_btn=true}if(e.get("can_user_modify")===true){vis_config.edit_library_btn=true}if(e.get("can_user_manage")===true){vis_config.permission_library_btn=true}}}}else{if(this.edit_mode===true){vis_config.upload_library_btn=false;vis_config.edit_library_btn=false;vis_config.permission_library_btn=false;vis_config.save_library_btn=true;vis_config.cancel_library_btn=true;vis_config.delete_library_btn=true;vis_config.undelete_library_btn=false}}this.element_visibility_config=vis_config},permissions_on_library:function(e){this.options=_.extend(this.options,e);$(".tooltip").remove()},edit_button_clicked:function(){this.edit_mode=true;this.repaint()},cancel_library_modification:function(){this.edit_mode=false;this.repaint()},save_library_modification:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var g=false;var i=this.$el.find(".input_library_name").val();if(typeof i!=="undefined"&&i!==f.get("name")){if(i.length>2){f.set("name",i);g=true}else{d.warning("Library name has to be at least 3 characters long");return}}var h=this.$el.find(".input_library_description").val();if(typeof h!=="undefined"&&h!==f.get("description")){f.set("description",h);g=true}var j=this.$el.find(".input_library_synopsis").val();if(typeof j!=="undefined"&&j!==f.get("synopsis")){f.set("synopsis",j);g=true}if(g){var e=this;f.save(null,{patch:true,success:function(k){e.edit_mode=false;e.repaint(k);d.success("Changes to library saved")},error:function(l,k){if(typeof k.responseJSON!=="undefined"){d.error(k.responseJSON.err_msg)}else{d.error("An error occured during updating the library :(")}}})}else{this.edit_mode=false;this.repaint(f);d.info("Nothing has changed")}},delete_library:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var e=this;f.destroy({success:function(g){g.set("deleted",true);Galaxy.libraries.libraryListView.collection.add(g);e.edit_mode=false;if(Galaxy.libraries.preferences.get("with_deleted")===false){$(".tooltip").hide();e.repaint(g);e.$el.remove()}else{if(Galaxy.libraries.preferences.get("with_deleted")===true){e.repaint(g)}}d.success("Library has been marked deleted")},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg)}else{d.error("An error occured during deleting the library :(")}}})},undelete_library:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var e=this;f.url=f.urlRoot+f.id+"?undelete=true";f.destroy({success:function(g){g.set("deleted",false);Galaxy.libraries.libraryListView.collection.add(g);e.edit_mode=false;e.repaint(g);d.success("Library has been undeleted")},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg)}else{d.error("An error occured while undeleting the library :(")}}})},templateRow:function(){tmpl_array=[];tmpl_array.push(' <tr class="<% if(library.get("deleted") === true) { print("active") } %>" style="display:none;" data-id="<%- library.get("id") %>">');tmpl_array.push(" <% if(!edit_mode) { %>");tmpl_array.push(' <% if(library.get("deleted")) { %>');tmpl_array.push(' <td style="color:grey;"><span data-toggle="tooltip" data-placement="top" title="Marked deleted" style="color:grey;" class="fa fa-ban fa-lg deleted_lib_ico"></span><%- library.get("name") %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><a href="#folders/<%- library.get("root_folder_id") %>"><%- library.get("name") %></a></td>');tmpl_array.push(" <% } %>");tmpl_array.push(' <% if(library.get("description")) { %>');tmpl_array.push(' <% if( (library.get("description")).length> 80 ) { %>');tmpl_array.push(' <td data-toggle="tooltip" data-placement="bottom" title="<%= _.escape(library.get("description")) %>"><%= _.escape(library.get("description")).substring(0, 80) + "..." %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><%= _.escape(library.get("description"))%></td>');tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else { %>");tmpl_array.push(" <td></td>");tmpl_array.push(" <% } %>");tmpl_array.push(' <% if(library.get("synopsis")) { %>');tmpl_array.push(' <% if( (library.get("synopsis")).length> 120 ) { %>');tmpl_array.push(' <td data-toggle="tooltip" data-placement="bottom" title="<%= _.escape(library.get("synopsis")) %>"><%= _.escape(library.get("synopsis")).substring(0, 120) + "..." %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><%= _.escape(library.get("synopsis"))%></td>');tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else { %>");tmpl_array.push(" <td></td>");tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else if(edit_mode){ %>");tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_name" placeholder="name" ><%- library.get("name") %></textarea></td>');tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_description" placeholder="description" ><%- library.get("description") %></textarea></td>');tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_synopsis" placeholder="synopsis" ><%- library.get("synopsis") %></textarea></td>');tmpl_array.push(" <% } %>");tmpl_array.push(' <td class="right-center">');tmpl_array.push(' <% if( (library.get("public")) && (library.get("deleted") === false) ) { %>');tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" title="Unrestricted library" style="color:grey;" class="fa fa-globe fa-lg public_lib_ico"></span>');tmpl_array.push(" <% }%>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Modify <%- library.get("name") %>" class="primary-button btn-xs edit_library_btn" type="button" style="<% if(button_config.edit_library_btn === false) { print("display:none;") } %>"><span class="fa fa-pencil"></span></button>');tmpl_array.push(' <a href="#library/<%- library.get("id") %>/permissions"><button data-toggle="tooltip" data-placement="top" title="Modify permissions" class="primary-button btn-xs permission_library_btn" type="button" style="<% if(button_config.permission_library_btn === false) { print("display:none;") } %>"><span class="fa fa-group"></span></button></a>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Save changes" class="primary-button btn-xs save_library_btn" type="button" style="<% if(button_config.save_library_btn === false) { print("display:none;") } %>"><span class="fa fa-floppy-o"> Save</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Discard changes" class="primary-button btn-xs cancel_library_btn" type="button" style="<% if(button_config.cancel_library_btn === false) { print("display:none;") } %>"><span class="fa fa-times"> Cancel</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Delete <%- library.get("name") %>" class="primary-button btn-xs delete_library_btn" type="button" style="<% if(button_config.delete_library_btn === false) { print("display:none;") } %>"><span class="fa fa-trash-o"> Delete</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Undelete <%- library.get("name") %> " class="primary-button btn-xs undelete_library_btn" type="button" style="<% if(button_config.undelete_library_btn === false) { print("display:none;") } %>"><span class="fa fa-unlock"> Undelete</span></button>');tmpl_array.push(" </td>");tmpl_array.push(" </tr>");return _.template(tmpl_array.join(""))}});return{LibraryRowView:a}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr"],function(b,c,d){var a=Backbone.View.extend({events:{"click .edit_library_btn":"edit_button_clicked","click .cancel_library_btn":"cancel_library_modification","click .save_library_btn":"save_library_modification","click .delete_library_btn":"delete_library","click .undelete_library_btn":"undelete_library"},edit_mode:false,element_visibility_config:{upload_library_btn:false,edit_library_btn:false,permission_library_btn:false,save_library_btn:false,cancel_library_btn:false,delete_library_btn:false,undelete_library_btn:false},initialize:function(e){this.render(e)},render:function(f){if(typeof f==="undefined"){f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"))}this.prepareButtons(f);var e=this.templateRow();this.setElement(e({library:f,button_config:this.element_visibility_config,edit_mode:this.edit_mode}));this.$el.show();return this},repaint:function(e){$(".tooltip").hide();var f=this.$el;this.render(e);f.replaceWith(this.$el);this.$el.find("[data-toggle]").tooltip()},prepareButtons:function(e){vis_config=this.element_visibility_config;if(this.edit_mode===false){vis_config.save_library_btn=false;vis_config.cancel_library_btn=false;vis_config.delete_library_btn=false;if(e.get("deleted")===true){vis_config.undelete_library_btn=true;vis_config.upload_library_btn=false;vis_config.edit_library_btn=false;vis_config.permission_library_btn=false}else{if(e.get("deleted")===false){vis_config.save_library_btn=false;vis_config.cancel_library_btn=false;vis_config.undelete_library_btn=false;if(e.get("can_user_add")===true){vis_config.upload_library_btn=true}if(e.get("can_user_modify")===true){vis_config.edit_library_btn=true}if(e.get("can_user_manage")===true){vis_config.permission_library_btn=true}}}}else{if(this.edit_mode===true){vis_config.upload_library_btn=false;vis_config.edit_library_btn=false;vis_config.permission_library_btn=false;vis_config.save_library_btn=true;vis_config.cancel_library_btn=true;vis_config.delete_library_btn=true;vis_config.undelete_library_btn=false}}this.element_visibility_config=vis_config},edit_button_clicked:function(){this.edit_mode=true;this.repaint()},cancel_library_modification:function(){this.edit_mode=false;this.repaint()},save_library_modification:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var g=false;var i=this.$el.find(".input_library_name").val();if(typeof i!=="undefined"&&i!==f.get("name")){if(i.length>2){f.set("name",i);g=true}else{d.warning("Library name has to be at least 3 characters long");return}}var h=this.$el.find(".input_library_description").val();if(typeof h!=="undefined"&&h!==f.get("description")){f.set("description",h);g=true}var j=this.$el.find(".input_library_synopsis").val();if(typeof j!=="undefined"&&j!==f.get("synopsis")){f.set("synopsis",j);g=true}if(g){var e=this;f.save(null,{patch:true,success:function(k){e.edit_mode=false;e.repaint(k);d.success("Changes to library saved")},error:function(l,k){if(typeof k.responseJSON!=="undefined"){d.error(k.responseJSON.err_msg)}else{d.error("An error occured during updating the library :(")}}})}else{this.edit_mode=false;this.repaint(f);d.info("Nothing has changed")}},delete_library:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var e=this;f.destroy({success:function(g){g.set("deleted",true);Galaxy.libraries.libraryListView.collection.add(g);e.edit_mode=false;if(Galaxy.libraries.preferences.get("with_deleted")===false){$(".tooltip").hide();e.repaint(g);e.$el.remove()}else{if(Galaxy.libraries.preferences.get("with_deleted")===true){e.repaint(g)}}d.success("Library has been marked deleted")},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg)}else{d.error("An error occured during deleting the library :(")}}})},undelete_library:function(){var f=Galaxy.libraries.libraryListView.collection.get(this.$el.data("id"));var e=this;f.url=f.urlRoot+f.id+"?undelete=true";f.destroy({success:function(g){g.set("deleted",false);Galaxy.libraries.libraryListView.collection.add(g);e.edit_mode=false;e.repaint(g);d.success("Library has been undeleted")},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg)}else{d.error("An error occured while undeleting the library :(")}}})},templateRow:function(){tmpl_array=[];tmpl_array.push(' <tr class="<% if(library.get("deleted") === true) { print("active") } %>" style="display:none;" data-id="<%- library.get("id") %>">');tmpl_array.push(" <% if(!edit_mode) { %>");tmpl_array.push(' <% if(library.get("deleted")) { %>');tmpl_array.push(' <td style="color:grey;"><span data-toggle="tooltip" data-placement="top" title="Marked deleted" style="color:grey;" class="fa fa-ban fa-lg deleted_lib_ico"></span><%- library.get("name") %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><a href="#folders/<%- library.get("root_folder_id") %>"><%- library.get("name") %></a></td>');tmpl_array.push(" <% } %>");tmpl_array.push(' <% if(library.get("description")) { %>');tmpl_array.push(' <% if( (library.get("description")).length> 80 ) { %>');tmpl_array.push(' <td data-toggle="tooltip" data-placement="bottom" title="<%= _.escape(library.get("description")) %>"><%= _.escape(library.get("description")).substring(0, 80) + "..." %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><%= _.escape(library.get("description"))%></td>');tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else { %>");tmpl_array.push(" <td></td>");tmpl_array.push(" <% } %>");tmpl_array.push(' <% if(library.get("synopsis")) { %>');tmpl_array.push(' <% if( (library.get("synopsis")).length> 120 ) { %>');tmpl_array.push(' <td data-toggle="tooltip" data-placement="bottom" title="<%= _.escape(library.get("synopsis")) %>"><%= _.escape(library.get("synopsis")).substring(0, 120) + "..." %></td>');tmpl_array.push(" <% } else { %>");tmpl_array.push(' <td><%= _.escape(library.get("synopsis"))%></td>');tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else { %>");tmpl_array.push(" <td></td>");tmpl_array.push(" <% } %>");tmpl_array.push(" <% } else if(edit_mode){ %>");tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_name" placeholder="name" ><%- library.get("name") %></textarea></td>');tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_description" placeholder="description" ><%- library.get("description") %></textarea></td>');tmpl_array.push(' <td><textarea rows="4" class="form-control input_library_synopsis" placeholder="synopsis" ><%- library.get("synopsis") %></textarea></td>');tmpl_array.push(" <% } %>");tmpl_array.push(' <td class="right-center">');tmpl_array.push(' <% if( (library.get("public")) && (library.get("deleted") === false) ) { %>');tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" title="Unrestricted library" style="color:grey;" class="fa fa-globe fa-lg public_lib_ico"></span>');tmpl_array.push(" <% }%>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Modify <%- library.get("name") %>" class="primary-button btn-xs edit_library_btn" type="button" style="<% if(button_config.edit_library_btn === false) { print("display:none;") } %>"><span class="fa fa-pencil"></span></button>');tmpl_array.push(' <a href="#library/<%- library.get("id") %>/permissions"><button data-toggle="tooltip" data-placement="top" title="Modify permissions" class="primary-button btn-xs permission_library_btn" type="button" style="<% if(button_config.permission_library_btn === false) { print("display:none;") } %>"><span class="fa fa-group"></span></button></a>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Save changes" class="primary-button btn-xs save_library_btn" type="button" style="<% if(button_config.save_library_btn === false) { print("display:none;") } %>"><span class="fa fa-floppy-o"> Save</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Discard changes" class="primary-button btn-xs cancel_library_btn" type="button" style="<% if(button_config.cancel_library_btn === false) { print("display:none;") } %>"><span class="fa fa-times"> Cancel</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Delete <%- library.get("name") %>" class="primary-button btn-xs delete_library_btn" type="button" style="<% if(button_config.delete_library_btn === false) { print("display:none;") } %>"><span class="fa fa-trash-o"> Delete</span></button>');tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Undelete <%- library.get("name") %> " class="primary-button btn-xs undelete_library_btn" type="button" style="<% if(button_config.undelete_library_btn === false) { print("display:none;") } %>"><span class="fa fa-unlock"> Undelete</span></button>');tmpl_array.push(" </td>");tmpl_array.push(" </tr>");return _.template(tmpl_array.join(""))}});return{LibraryRowView:a}}); \ No newline at end of file diff -r a4a6834f4b2fe443f40235fd6331a7da7fa09d57 -r 858c12951cfa764fb8b948e360b29f8a9e90b89b static/scripts/packed/mvc/library/library-model.js --- a/static/scripts/packed/mvc/library/library-model.js +++ b/static/scripts/packed/mvc/library/library-model.js @@ -1,1 +1,1 @@ -define([],function(){var f=Backbone.Model.extend({urlRoot:"/api/libraries/",isVisible:function(m){var l=true;if((!m)&&(this.get("deleted"))){l=false}return l}});var i=Backbone.Collection.extend({url:"/api/libraries",model:f,sort_key:"name",sort_order:null,initialize:function(l){l=l||{}},getVisible:function(m,n){n=n||[];var l=new i(this.filter(function(o){return o.isVisible(m)}));return l},sortByNameAsc:function(){this.comparator=function(m,l){if(m.get("name").toLowerCase()>l.get("name").toLowerCase()){return 1}if(l.get("name").toLowerCase()>m.get("name").toLowerCase()){return -1}return 0};this.sort();return this},sortByNameDesc:function(){this.comparator=function(m,l){if(m.get("name").toLowerCase()>l.get("name").toLowerCase()){return -1}if(l.get("name").toLowerCase()>m.get("name").toLowerCase()){return 1}return 0};this.sort();return this}});var g=Backbone.Model.extend({urlRoot:"/api/libraries/datasets/"});var k=Backbone.Model.extend({urlRoot:"/api/libraries/datasets/"});var a=Backbone.Model.extend({urlRoot:"/api/folders"});var c=Backbone.Collection.extend({model:g,sortByNameAsc:function(){this.comparator=function(m,l){if(m.get("type")===l.get("type")){if(m.get("name").toLowerCase()>l.get("name").toLowerCase()){return 1}if(l.get("name").toLowerCase()>m.get("name").toLowerCase()){return -1}return 0}else{if(m.get("type")==="folder"){return -1}else{return 1}}};this.sort();return this},sortByNameDesc:function(){this.comparator=function(m,l){if(m.get("type")===l.get("type")){if(m.get("name").toLowerCase()>l.get("name").toLowerCase()){return -1}if(l.get("name").toLowerCase()>m.get("name").toLowerCase()){return 1}return 0}else{if(m.get("type")==="folder"){return -1}else{return 1}}};this.sort();return this}});var e=Backbone.Model.extend({defaults:{folder:new c(),urlRoot:"/api/folders/",id:"unknown"},parse:function(l){this.get("folder").reset(l.folder_contents);return l}});var b=Backbone.Model.extend({urlRoot:"/api/histories/"});var d=Backbone.Collection.extend({urlRoot:"/api/histories/",initialize:function(l){this.id=l.id},url:function(){return this.urlRoot+this.id+"/contents"},model:b});var h=Backbone.Model.extend({urlRoot:"/api/histories/"});var j=Backbone.Collection.extend({url:"/api/histories",model:h});return{Library:f,FolderAsModel:a,Libraries:i,Item:g,Ldda:k,Folder:c,FolderContainer:e,HistoryItem:b,HistoryContents:d,GalaxyHistory:h,GalaxyHistories:j}}); \ No newline at end of file +define([],function(){var f=Backbone.Model.extend({urlRoot:"/api/libraries/",isVisible:function(n){var m=true;if((!n)&&(this.get("deleted"))){m=false}return m}});var i=Backbone.Collection.extend({url:"/api/libraries",model:f,sort_key:"name",sort_order:null,initialize:function(m){m=m||{}},getVisible:function(n,o){o=o||[];var m=new i(this.filter(function(p){return p.isVisible(n)}));return m},sortByNameAsc:function(){this.comparator=function(n,m){if(n.get("name").toLowerCase()>m.get("name").toLowerCase()){return 1}if(m.get("name").toLowerCase()>n.get("name").toLowerCase()){return -1}return 0};this.sort();return this},sortByNameDesc:function(){this.comparator=function(n,m){if(n.get("name").toLowerCase()>m.get("name").toLowerCase()){return -1}if(m.get("name").toLowerCase()>n.get("name").toLowerCase()){return 1}return 0};this.sort();return this}});var g=Backbone.Model.extend({urlRoot:"/api/libraries/datasets/"});var l=Backbone.Model.extend({urlRoot:"/api/libraries/datasets/"});var a=Backbone.Model.extend({urlRoot:"/api/folders"});var c=Backbone.Collection.extend({model:g,sortByNameAsc:function(){this.comparator=function(n,m){if(n.get("type")===m.get("type")){if(n.get("name").toLowerCase()>m.get("name").toLowerCase()){return 1}if(m.get("name").toLowerCase()>n.get("name").toLowerCase()){return -1}return 0}else{if(n.get("type")==="folder"){return -1}else{return 1}}};this.sort();return this},sortByNameDesc:function(){this.comparator=function(n,m){if(n.get("type")===m.get("type")){if(n.get("name").toLowerCase()>m.get("name").toLowerCase()){return -1}if(m.get("name").toLowerCase()>n.get("name").toLowerCase()){return 1}return 0}else{if(n.get("type")==="folder"){return -1}else{return 1}}};this.sort();return this}});var e=Backbone.Model.extend({defaults:{folder:new c(),urlRoot:"/api/folders/",id:"unknown"},parse:function(m){this.get("folder").reset(m.folder_contents);return m}});var b=Backbone.Model.extend({urlRoot:"/api/histories/"});var d=Backbone.Collection.extend({urlRoot:"/api/histories/",initialize:function(m){this.id=m.id},url:function(){return this.urlRoot+this.id+"/contents"},model:b});var h=Backbone.Model.extend({urlRoot:"/api/histories/"});var k=Backbone.Collection.extend({url:"/api/histories",model:h});var j=Backbone.Model.extend({urlRoot:"/api/ftp_files"});return{Library:f,FolderAsModel:a,Libraries:i,Item:g,Ldda:l,Folder:c,FolderContainer:e,HistoryItem:b,HistoryContents:d,GalaxyHistory:h,GalaxyHistories:k,Jstree:j}}); \ No newline at end of file https://bitbucket.org/galaxy/galaxy-central/commits/d277478dce50/ Changeset: d277478dce50 User: martenson Date: 2014-09-16 15:40:08+00:00 Summary: Merge Affected #: 293 files diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 config/plugins/visualizations/charts/templates/charts.mako --- a/config/plugins/visualizations/charts/templates/charts.mako +++ b/config/plugins/visualizations/charts/templates/charts.mako @@ -86,8 +86,8 @@ require(['plugin/app'], function(App) { // load options var options = { - id : ${h.to_json_string( visualization_id )} || undefined, - config : ${h.to_json_string( config )} + id : ${h.dumps( visualization_id )} || undefined, + config : ${h.dumps( config )} } // create application diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 config/plugins/visualizations/common/templates/config_utils.mako --- a/config/plugins/visualizations/common/templates/config_utils.mako +++ b/config/plugins/visualizations/common/templates/config_utils.mako @@ -36,7 +36,7 @@ 'action' : 'saved', 'type' : visualization_name, 'title' : title, - 'config' : h.to_json_string( config ) + 'config' : h.dumps( config ) } # save to existing visualization if visualization_id: diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 config/plugins/visualizations/scatterplot/templates/scatterplot.mako --- a/config/plugins/visualizations/scatterplot/templates/scatterplot.mako +++ b/config/plugins/visualizations/scatterplot/templates/scatterplot.mako @@ -50,11 +50,11 @@ <script type="text/javascript"> $(function(){ var model = new ScatterplotModel({ - id : ${h.to_json_string( visualization_id )} || undefined, + id : ${h.dumps( visualization_id )} || undefined, title : "${title}", - config : ${h.to_json_string( config, indent=2 )} + config : ${h.dumps( config, indent=2 )} }); - hdaJson = ${h.to_json_string( trans.security.encode_dict_ids( hda.to_dict() ), indent=2 )}, + hdaJson = ${h.dumps( trans.security.encode_dict_ids( hda.to_dict() ), indent=2 )}, display = new ScatterplotDisplay({ el : $( '.scatterplot-display' ).attr( 'id', 'scatterplot-display-' + '${visualization_id}' ), model : model, @@ -78,11 +78,11 @@ <script type="text/javascript"> $(function(){ var model = new ScatterplotModel({ - id : ${h.to_json_string( visualization_id )} || undefined, + id : ${h.dumps( visualization_id )} || undefined, title : "${title or default_title}", - config : ${h.to_json_string( config, indent=2 )} + config : ${h.dumps( config, indent=2 )} }), - hdaJson = ${h.to_json_string( trans.security.encode_dict_ids( hda.to_dict() ), indent=2 )}, + hdaJson = ${h.dumps( trans.security.encode_dict_ids( hda.to_dict() ), indent=2 )}, editor = new ScatterplotConfigEditor({ el : $( '.scatterplot-editor' ).attr( 'id', 'scatterplot-editor-hda-' + hdaJson.id ), model : model, diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/igv/bam.xml --- a/display_applications/igv/bam.xml +++ b/display_applications/igv/bam.xml @@ -12,15 +12,19 @@ <dynamic_param name="site_organisms" value="4" split="True" separator="," /><!-- Filter out some of the links based upon matching site_dbkeys to dataset dbkey --> - <filter>${dataset.dbkey in $site_dbkeys}</filter> - + <filter>${$site_id.startswith( 'local_' ) or $dataset.dbkey in $site_dbkeys}</filter> + <!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${redirect_url}</url><param type="data" name="bam_file" url="galaxy_${DATASET_HASH}.bam" /><param type="data" name="bai_file" url="galaxy_${DATASET_HASH}.bam.bai" metadata="bam_index" /><param type="template" name="site_organism" strip="True" > - $site_organisms[ $site_dbkeys.index( $bam_file.dbkey ) ] + #if ($dataset.dbkey in $site_dbkeys) + $site_organisms[ $site_dbkeys.index( $bam_file.dbkey ) ] + #else: + $bam_file.dbkey + #end if </param><param type="template" name="jnlp" url="galaxy_${DATASET_HASH}.jnlp" viewable="True" mimetype="application/x-java-jnlp-file"><?xml version="1.0" encoding="utf-8"?> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/igv/vcf.xml --- a/display_applications/igv/vcf.xml +++ b/display_applications/igv/vcf.xml @@ -12,15 +12,19 @@ <dynamic_param name="site_organisms" value="4" split="True" separator="," /><!-- Filter out some of the links based upon matching site_dbkeys to dataset dbkey --> - <filter>${dataset.dbkey in $site_dbkeys}</filter> - + <filter>${$site_id.startswith( 'local_' ) or $dataset.dbkey in $site_dbkeys}</filter> + <!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${redirect_url}</url><param type="data" name="bgzip_file" url="galaxy_${DATASET_HASH}.vcf.gz" format="vcf_bgzip" /><param type="data" name="tabix_file" dataset="bgzip_file" url="galaxy_${DATASET_HASH}.vcf.gz.tbi" format="tabix" /><param type="template" name="site_organism" strip="True" > - $site_organisms[ $site_dbkeys.index( $bgzip_file.dbkey ) ] + #if ($dataset.dbkey in $site_dbkeys) + $site_organisms[ $site_dbkeys.index( $bgzip_file.dbkey ) ] + #else: + $bgzip_file.dbkey + #end if </param><param type="template" name="jnlp" url="galaxy_${DATASET_HASH}.jnlp" viewable="True" mimetype="application/x-java-jnlp-file"><?xml version="1.0" encoding="utf-8"?> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/bam.xml --- a/display_applications/ucsc/bam.xml +++ b/display_applications/ucsc/bam.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($bam_file.dbkey)}&hgt.customText=${qp($track.url)}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/bigbed.xml --- a/display_applications/ucsc/bigbed.xml +++ b/display_applications/ucsc/bigbed.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($bigbed_file.dbkey)}&hgt.customText=${qp($track.url)}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/bigwig.xml --- a/display_applications/ucsc/bigwig.xml +++ b/display_applications/ucsc/bigwig.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($bigwig_file.dbkey)}&hgt.customText=${qp($track.url)}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/interval_as_bed.xml --- a/display_applications/ucsc/interval_as_bed.xml +++ b/display_applications/ucsc/interval_as_bed.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($bed_file.dbkey)}&position=${position.qp}&hgt.customText=${bed_file.qp}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/maf_customtrack.xml --- a/display_applications/ucsc/maf_customtrack.xml +++ b/display_applications/ucsc/maf_customtrack.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($maf_customtrack_file.dbkey)}&position=${maf_customtrack_file.metadata.vp_chromosome}:${maf_customtrack_file.metadata.vp_start}-${maf_customtrack_file.metadata.vp_end}&hgt.customText=${maf_customtrack_file.qp}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 display_applications/ucsc/vcf.xml --- a/display_applications/ucsc/vcf.xml +++ b/display_applications/ucsc/vcf.xml @@ -6,7 +6,7 @@ <dynamic_param name="ucsc_link" value="1"/><dynamic_param name="builds" value="2" split="True" separator="," /><!-- Filter out some of the links based upon matching site_id to a Galaxy application configuration parameter and by dataset dbkey --> - <filter>${site_id in $APP.config.ucsc_display_sites}</filter> + <filter>${site_id in $APP.datatypes_registry.get_display_sites('ucsc')}</filter><filter>${dataset.dbkey in $builds}</filter><!-- We define url and params as normal, but values defined in dynamic_param are available by specified name --><url>${ucsc_link}db=${qp($bgzip_file.dbkey)}&hgt.customText=${qp($track.url)}</url> diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/app.py --- a/lib/galaxy/app.py +++ b/lib/galaxy/app.py @@ -5,7 +5,7 @@ from galaxy import config, jobs import galaxy.model import galaxy.security -from galaxy import dataset_collections +from galaxy.managers.collections import DatasetCollectionManager import galaxy.quota from galaxy.tags.tag_handler import GalaxyTagHandler from galaxy.visualization.genomes import Genomes @@ -57,7 +57,7 @@ # Tag handler self.tag_handler = GalaxyTagHandler() # Dataset Collection Plugins - self.dataset_collections_service = dataset_collections.DatasetCollectionsService(self) + self.dataset_collections_service = DatasetCollectionManager(self) # Tool Data Tables self._configure_tool_data_tables( from_shed_config=False ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/dataset_collections/__init__.py --- a/lib/galaxy/dataset_collections/__init__.py +++ b/lib/galaxy/dataset_collections/__init__.py @@ -1,295 +0,0 @@ -from .registry import DatasetCollectionTypesRegistry -from .matching import MatchingCollections -from .type_description import CollectionTypeDescriptionFactory - - -from galaxy import model -from galaxy.exceptions import MessageException -from galaxy.exceptions import ItemAccessibilityException -from galaxy.exceptions import RequestParameterInvalidException -from galaxy.web.base.controller import ( - UsesHistoryDatasetAssociationMixin, - UsesLibraryMixinItems, - UsesTagsMixin, -) -from galaxy.managers import hdas # TODO: Refactor all mixin use into managers. -from galaxy.managers.collections_util import validate_input_element_identifiers -from galaxy.util import validation -from galaxy.util import odict - -import logging -log = logging.getLogger( __name__ ) - - -ERROR_INVALID_ELEMENTS_SPECIFICATION = "Create called with invalid parameters, must specify element identifiers." -ERROR_NO_COLLECTION_TYPE = "Create called without specifing a collection type." - - -class DatasetCollectionsService( - UsesHistoryDatasetAssociationMixin, - UsesLibraryMixinItems, - UsesTagsMixin, -): - """ - Abstraction for interfacing with dataset collections instance - ideally abstarcts - out model and plugin details. - """ - - def __init__( self, app ): - self.type_registry = DatasetCollectionTypesRegistry( app ) - self.collection_type_descriptions = CollectionTypeDescriptionFactory( self.type_registry ) - self.model = app.model - self.security = app.security - self.hda_manager = hdas.HDAManager() - - def create( - self, - trans, - parent, # PRECONDITION: security checks on ability to add to parent occurred during load. - name, - collection_type, - element_identifiers=None, - elements=None, - implicit_collection_info=None, - ): - """ - """ - # Trust embedded, newly created objects created by tool subsystem. - trusted_identifiers = implicit_collection_info is not None - - if element_identifiers and not trusted_identifiers: - validate_input_element_identifiers( element_identifiers ) - - dataset_collection = self.__create_dataset_collection( - trans=trans, - collection_type=collection_type, - element_identifiers=element_identifiers, - elements=elements, - ) - if isinstance( parent, model.History ): - dataset_collection_instance = self.model.HistoryDatasetCollectionAssociation( - collection=dataset_collection, - name=name, - ) - if implicit_collection_info: - for input_name, input_collection in implicit_collection_info[ "implicit_inputs" ]: - dataset_collection_instance.add_implicit_input_collection( input_name, input_collection ) - for output_dataset in implicit_collection_info.get( "outputs" ): - output_dataset.hidden_beneath_collection_instance = dataset_collection_instance - trans.sa_session.add( output_dataset ) - - dataset_collection_instance.implicit_output_name = implicit_collection_info[ "implicit_output_name" ] - log.debug("Created collection with %d elements" % ( len( dataset_collection_instance.collection.elements ) ) ) - # Handle setting hid - parent.add_dataset_collection( dataset_collection_instance ) - elif isinstance( parent, model.LibraryFolder ): - dataset_collection_instance = self.model.LibraryDatasetCollectionAssociation( - collection=dataset_collection, - folder=parent, - name=name, - ) - else: - message = "Internal logic error - create called with unknown parent type %s" % type( parent ) - log.exception( message ) - raise MessageException( message ) - - return self.__persist( dataset_collection_instance ) - - def __create_dataset_collection( - self, - trans, - collection_type, - element_identifiers=None, - elements=None, - ): - if element_identifiers is None and elements is None: - raise RequestParameterInvalidException( ERROR_INVALID_ELEMENTS_SPECIFICATION ) - if not collection_type: - raise RequestParameterInvalidException( ERROR_NO_COLLECTION_TYPE ) - collection_type_description = self.collection_type_descriptions.for_collection_type( collection_type ) - # If we have elements, this is an internal request, don't need to load - # objects from identifiers. - if elements is None: - if collection_type_description.has_subcollections( ): - # Nested collection - recursively create collections and update identifiers. - self.__recursively_create_collections( trans, element_identifiers ) - elements = self.__load_elements( trans, element_identifiers ) - # else if elements is set, it better be an ordered dict! - - type_plugin = collection_type_description.rank_type_plugin() - dataset_collection = type_plugin.build_collection( elements ) - dataset_collection.collection_type = collection_type - return dataset_collection - - def delete( self, trans, instance_type, id ): - dataset_collection_instance = self.get_dataset_collection_instance( trans, instance_type, id, check_ownership=True ) - dataset_collection_instance.deleted = True - trans.sa_session.add( dataset_collection_instance ) - trans.sa_session.flush( ) - - def update( self, trans, instance_type, id, payload ): - dataset_collection_instance = self.get_dataset_collection_instance( trans, instance_type, id, check_ownership=True ) - if trans.user is None: - anon_allowed_payload = {} - if 'deleted' in payload: - anon_allowed_payload[ 'deleted' ] = payload[ 'deleted' ] - if 'visible' in payload: - anon_allowed_payload[ 'visible' ] = payload[ 'visible' ] - payload = self._validate_and_parse_update_payload( anon_allowed_payload ) - else: - payload = self._validate_and_parse_update_payload( payload ) - changed = self._set_from_dict( trans, dataset_collection_instance, payload ) - return changed - - def copy( - self, - trans, - parent, # PRECONDITION: security checks on ability to add to parent occurred during load. - source, - encoded_source_id, - ): - assert source == "hdca" # for now - source_hdca = self.__get_history_collection_instance( trans, encoded_source_id ) - new_hdca = source_hdca.copy() - parent.add_dataset_collection( new_hdca ) - trans.sa_session.add( new_hdca ) - trans.sa_session.flush() - return source_hdca - - def _set_from_dict( self, trans, dataset_collection_instance, new_data ): - # Blatantly stolen from UsesHistoryDatasetAssociationMixin.set_hda_from_dict. - - # send what we can down into the model - changed = dataset_collection_instance.set_from_dict( new_data ) - # the rest (often involving the trans) - do here - if 'annotation' in new_data.keys() and trans.get_user(): - dataset_collection_instance.add_item_annotation( trans.sa_session, trans.get_user(), dataset_collection_instance, new_data[ 'annotation' ] ) - changed[ 'annotation' ] = new_data[ 'annotation' ] - if 'tags' in new_data.keys() and trans.get_user(): - self.set_tags_from_list( trans, dataset_collection_instance, new_data[ 'tags' ], user=trans.user ) - - if changed.keys(): - trans.sa_session.flush() - - return changed - - def _validate_and_parse_update_payload( self, payload ): - validated_payload = {} - for key, val in payload.items(): - if val is None: - continue - if key in ( 'name' ): - val = validation.validate_and_sanitize_basestring( key, val ) - validated_payload[ key ] = val - if key in ( 'deleted', 'visible' ): - validated_payload[ key ] = validation.validate_boolean( key, val ) - elif key == 'tags': - validated_payload[ key ] = validation.validate_and_sanitize_basestring_list( key, val ) - return validated_payload - - def history_dataset_collections(self, history, query): - collections = history.active_dataset_collections - collections = filter( query.direct_match, collections ) - return collections - - def __persist( self, dataset_collection_instance ): - context = self.model.context - context.add( dataset_collection_instance ) - context.flush() - return dataset_collection_instance - - def __recursively_create_collections( self, trans, element_identifiers ): - for index, element_identifier in enumerate( element_identifiers ): - try: - if not element_identifier[ "src" ] == "new_collection": - # not a new collection, keep moving... - continue - except KeyError: - # Not a dictionary, just an id of an HDA - move along. - continue - - # element identifier is a dict with src new_collection... - collection_type = element_identifier.get( "collection_type", None ) - collection = self.__create_dataset_collection( - trans=trans, - collection_type=collection_type, - element_identifiers=element_identifier[ "element_identifiers" ], - ) - element_identifier[ "__object__" ] = collection - - return element_identifiers - - def __load_elements( self, trans, element_identifiers ): - elements = odict.odict() - for element_identifier in element_identifiers: - elements[ element_identifier[ "name" ] ] = self.__load_element( trans, element_identifier ) - return elements - - def __load_element( self, trans, element_identifier ): - #if not isinstance( element_identifier, dict ): - # # Is allowing this to just be the id of an hda too clever? Somewhat - # # consistent with other API methods though. - # element_identifier = dict( src='hda', id=str( element_identifier ) ) - - # Previously created collection already found in request, just pass - # through as is. - if "__object__" in element_identifier: - return element_identifier[ "__object__" ] - - # dateset_identifier is dict {src=hda|ldda|hdca|new_collection, id=<encoded_id>} - try: - src_type = element_identifier.get( 'src', 'hda' ) - except AttributeError: - raise MessageException( "Dataset collection element definition (%s) not dictionary-like." % element_identifier ) - encoded_id = element_identifier.get( 'id', None ) - if not src_type or not encoded_id: - raise RequestParameterInvalidException( "Problem decoding element identifier %s" % element_identifier ) - - if src_type == 'hda': - decoded_id = int( trans.app.security.decode_id( encoded_id ) ) - element = self.hda_manager.get( trans, decoded_id, check_ownership=False ) - elif src_type == 'ldda': - element = self.get_library_dataset_dataset_association( trans, encoded_id ) - elif src_type == 'hdca': - # TODO: Option to copy? Force copy? Copy or allow if not owned? - element = self.__get_history_collection_instance( trans, encoded_id ).collection - # TODO: ldca. - else: - raise RequestParameterInvalidException( "Unknown src_type parameter supplied '%s'." % src_type ) - return element - - def match_collections( self, collections_to_match ): - """ - May seem odd to place it here, but planning to grow sophistication and - get plugin types involved so it will likely make sense in the future. - """ - return MatchingCollections.for_collections( collections_to_match, self.collection_type_descriptions ) - - def get_dataset_collection_instance( self, trans, instance_type, id, **kwds ): - """ - """ - if instance_type == "history": - return self.__get_history_collection_instance( trans, id, **kwds ) - elif instance_type == "library": - return self.__get_library_collection_instance( trans, id, **kwds ) - - def get_dataset_collection( self, trans, encoded_id ): - collection_id = int( trans.app.security.decode_id( encoded_id ) ) - collection = trans.sa_session.query( trans.app.model.DatasetCollection ).get( collection_id ) - return collection - - def __get_history_collection_instance( self, trans, id, check_ownership=False, check_accessible=True ): - instance_id = int( trans.app.security.decode_id( id ) ) - collection_instance = trans.sa_session.query( trans.app.model.HistoryDatasetCollectionAssociation ).get( instance_id ) - self.security_check( trans, collection_instance.history, check_ownership=check_ownership, check_accessible=check_accessible ) - return collection_instance - - def __get_library_collection_instance( self, trans, id, check_ownership=False, check_accessible=True ): - if check_ownership: - raise NotImplemented( "Functionality (getting library dataset collection with ownership check) unimplemented." ) - instance_id = int( trans.security.decode_id( id ) ) - collection_instance = trans.sa_session.query( trans.app.model.LibraryDatasetCollectionAssociation ).get( instance_id ) - if check_accessible: - if not trans.app.security_agent.can_access_library_item( trans.get_current_user_roles(), collection_instance, trans.user ): - raise ItemAccessibilityException( "LibraryDatasetCollectionAssociation is not accessible to the current user", type='error' ) - return collection_instance diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/bedgraph_to_array_tree_converter.py --- a/lib/galaxy/datatypes/converters/bedgraph_to_array_tree_converter.py +++ b/lib/galaxy/datatypes/converters/bedgraph_to_array_tree_converter.py @@ -52,4 +52,4 @@ FileArrayTreeDict.dict_to_file( d, open( out_fname, "w" ) ) if __name__ == "__main__": - main() \ No newline at end of file + main() diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/fasta_to_len.py --- a/lib/galaxy/datatypes/converters/fasta_to_len.py +++ b/lib/galaxy/datatypes/converters/fasta_to_len.py @@ -49,4 +49,4 @@ out.close() if __name__ == "__main__" : - compute_fasta_length( sys.argv[1], sys.argv[2], sys.argv[3], True ) \ No newline at end of file + compute_fasta_length( sys.argv[1], sys.argv[2], sys.argv[3], True ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/fasta_to_tabular_converter.py --- a/lib/galaxy/datatypes/converters/fasta_to_tabular_converter.py +++ b/lib/galaxy/datatypes/converters/fasta_to_tabular_converter.py @@ -40,4 +40,4 @@ print >> out, "%s\t%s" %( fasta_title, sequence ) out.close() -if __name__ == "__main__" : __main__() \ No newline at end of file +if __name__ == "__main__" : __main__() diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/fastqsolexa_to_fasta_converter.py --- a/lib/galaxy/datatypes/converters/fastqsolexa_to_fasta_converter.py +++ b/lib/galaxy/datatypes/converters/fastqsolexa_to_fasta_converter.py @@ -52,4 +52,4 @@ outfile.close() -if __name__ == "__main__": __main__() \ No newline at end of file +if __name__ == "__main__": __main__() diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/interval_to_coverage.py --- a/lib/galaxy/datatypes/converters/interval_to_coverage.py +++ b/lib/galaxy/datatypes/converters/interval_to_coverage.py @@ -149,4 +149,4 @@ fix_strand=True ) main( interval, coverage ) temp_file.close() - coverage.close() \ No newline at end of file + coverage.close() diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/converters/wiggle_to_array_tree_converter.py --- a/lib/galaxy/datatypes/converters/wiggle_to_array_tree_converter.py +++ b/lib/galaxy/datatypes/converters/wiggle_to_array_tree_converter.py @@ -26,4 +26,4 @@ FileArrayTreeDict.dict_to_file( d, open( out_fname, "w" ) ) if __name__ == "__main__": - main() \ No newline at end of file + main() diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/tabular.py --- a/lib/galaxy/datatypes/tabular.py +++ b/lib/galaxy/datatypes/tabular.py @@ -14,7 +14,7 @@ from galaxy.datatypes.checkers import is_gzip from galaxy.datatypes.metadata import MetadataElement from galaxy.datatypes.sniff import get_headers, get_test_fname -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps import dataproviders log = logging.getLogger(__name__) @@ -272,7 +272,7 @@ while cursor and ck_data[-1] != '\n': ck_data += cursor cursor = f.read(1) - return to_json_string( { 'ck_data': util.unicodify( ck_data ), 'ck_index': ck_index + 1 } ) + return dumps( { 'ck_data': util.unicodify( ck_data ), 'ck_index': ck_index + 1 } ) def display_data(self, trans, dataset, preview=False, filename=None, to_ext=None, chunk=None, **kwd): preview = util.string_as_bool( preview ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/datatypes/util/__init__.py --- a/lib/galaxy/datatypes/util/__init__.py +++ b/lib/galaxy/datatypes/util/__init__.py @@ -1,3 +1,3 @@ """ Utilities for Galaxy datatypes. -""" \ No newline at end of file +""" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/external_services/result_handlers/basic.py --- a/lib/galaxy/external_services/result_handlers/basic.py +++ b/lib/galaxy/external_services/result_handlers/basic.py @@ -1,4 +1,4 @@ -from galaxy.util.json import to_json_string, from_json_string +from galaxy.util.json import dumps, loads from galaxy.util.template import fill_template import logging @@ -44,7 +44,7 @@ type = 'json_display' def handle_result( self, result, param_dict, trans ): - rval = from_json_string( result.content ) + rval = loads( result.content ) return trans.fill_template( '/external_services/generic_json.mako', result = rval, param_dict = param_dict, action=self.parent ) class ExternalServiceActionJQueryGridResultHandler( ExternalServiceActionResultHandler ): @@ -53,7 +53,7 @@ type = 'jquery_grid' def handle_result( self, result, param_dict, trans ): - rval = from_json_string( result.content ) + rval = loads( result.content ) return trans.fill_template( '/external_services/generic_jquery_grid.mako', result = rval, param_dict = param_dict, action=self.parent ) result_type_to_class = {} diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/jobs/__init__.py --- a/lib/galaxy/jobs/__init__.py +++ b/lib/galaxy/jobs/__init__.py @@ -25,7 +25,7 @@ from galaxy.jobs.runners import BaseJobRunner, JobState from galaxy.util.bunch import Bunch from galaxy.util.expressions import ExpressionContext -from galaxy.util.json import from_json_string +from galaxy.util.json import loads from galaxy.util import unicodify from .output_checker import check_output @@ -723,7 +723,7 @@ self.job_runner_mapper = JobRunnerMapper( self, queue.dispatcher.url_to_destination, self.app.job_config ) self.params = None if job.params: - self.params = from_json_string( job.params ) + self.params = loads( job.params ) if use_persisted_destination: self.job_runner_mapper.cached_job_destination = JobDestination( from_job=job ) @@ -1390,7 +1390,7 @@ if os.path.exists( meta_file ): for line in open( meta_file, 'r' ): try: - line = from_json_string( line ) + line = loads( line ) assert 'type' in line except: log.exception( '(%s) Got JSON data from tool, but data is improperly formatted or no "type" key in data' % self.job_id ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/jobs/actions/__init__.py --- a/lib/galaxy/jobs/actions/__init__.py +++ b/lib/galaxy/jobs/actions/__init__.py @@ -1,4 +1,4 @@ """ This package contains job action classes. -""" \ No newline at end of file +""" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/jobs/actions/post.py --- a/lib/galaxy/jobs/actions/post.py +++ b/lib/galaxy/jobs/actions/post.py @@ -5,7 +5,7 @@ import datetime import logging from galaxy.util import send_mail -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps log = logging.getLogger( __name__ ) @@ -461,7 +461,7 @@ else: # Not pja stuff. pass - return to_json_string(npd) + return dumps(npd) @classmethod def get_add_list(cls): diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/jobs/deferred/pacific_biosciences_smrt_portal.py --- a/lib/galaxy/jobs/deferred/pacific_biosciences_smrt_portal.py +++ b/lib/galaxy/jobs/deferred/pacific_biosciences_smrt_portal.py @@ -83,7 +83,7 @@ return self.job_states.INVALID url = 'http://' + job.params[ 'smrt_host' ] + self.api_path + '/Jobs/' + job.params[ 'smrt_job_id' ] + '/Status' r = urllib2.urlopen( url ) - status = json.from_json_string( r.read() ) + status = json.loads( r.read() ) # TODO: error handling: unexpected json or bad response, bad url, etc. if status[ 'Code' ] == 'Completed': log.debug( "SMRT Portal job '%s' is Completed. Initiating transfer." % job.params[ 'smrt_job_id' ] ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/jobs/transfer_manager.py --- a/lib/galaxy/jobs/transfer_manager.py +++ b/lib/galaxy/jobs/transfer_manager.py @@ -82,7 +82,7 @@ sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) sock.settimeout( 5 ) sock.connect( ( 'localhost', tj.socket ) ) - sock.send( json.to_json_string( request ) ) + sock.send( json.dumps( request ) ) response = sock.recv( 8192 ) valid, response = json.validate_jsonrpc_response( response, id=request['id'] ) if not valid: diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/managers/base.py --- a/lib/galaxy/managers/base.py +++ b/lib/galaxy/managers/base.py @@ -1,7 +1,120 @@ +from galaxy import exceptions + +from galaxy import model +from galaxy.model import tool_shed_install + + +import logging +log = logging.getLogger( __name__ ) class ModelManager( object ): pass + class ModelSerializer( object ): pass + + +def security_check( trans, item, check_ownership=False, check_accessible=False ): + """ Security checks for an item: checks if (a) user owns item or (b) item + is accessible to user. This is a generic method for dealing with objects + uniformly from the older controller mixin code - however whenever possible + the managers for a particular model should be used to perform security + checks. + """ + + # all items are accessible to an admin + if trans.user_is_admin(): + return item + + # Verify ownership: there is a current user and that user is the same as the item's + if check_ownership: + if not trans.user: + raise exceptions.ItemOwnershipException( "Must be logged in to manage Galaxy items", type='error' ) + if item.user != trans.user: + raise exceptions.ItemOwnershipException( "%s is not owned by the current user" % item.__class__.__name__, type='error' ) + + # Verify accessible: + # if it's part of a lib - can they access via security + # if it's something else (sharable) have they been added to the item's users_shared_with_dot_users + if check_accessible: + if type( item ) in ( trans.app.model.LibraryFolder, trans.app.model.LibraryDatasetDatasetAssociation, trans.app.model.LibraryDataset ): + if not trans.app.security_agent.can_access_library_item( trans.get_current_user_roles(), item, trans.user ): + raise exceptions.ItemAccessibilityException( "%s is not accessible to the current user" % item.__class__.__name__, type='error' ) + else: + if ( item.user != trans.user ) and ( not item.importable ) and ( trans.user not in item.users_shared_with_dot_users ): + raise exceptions.ItemAccessibilityException( "%s is not accessible to the current user" % item.__class__.__name__, type='error' ) + return item + + +def get_class( class_name ): + """ Returns the class object that a string denotes. Without this method, we'd have to do eval(<class_name>). """ + if class_name == 'History': + item_class = model.History + elif class_name == 'HistoryDatasetAssociation': + item_class = model.HistoryDatasetAssociation + elif class_name == 'Page': + item_class = model.Page + elif class_name == 'StoredWorkflow': + item_class = model.StoredWorkflow + elif class_name == 'Visualization': + item_class = model.Visualization + elif class_name == 'Tool': + item_class = model.Tool + elif class_name == 'Job': + item_class = model.Job + elif class_name == 'User': + item_class = model.User + elif class_name == 'Group': + item_class = model.Group + elif class_name == 'Role': + item_class = model.Role + elif class_name == 'Quota': + item_class = model.Quota + elif class_name == 'Library': + item_class = model.Library + elif class_name == 'LibraryFolder': + item_class = model.LibraryFolder + elif class_name == 'LibraryDatasetDatasetAssociation': + item_class = model.LibraryDatasetDatasetAssociation + elif class_name == 'LibraryDataset': + item_class = model.LibraryDataset + elif class_name == 'ToolShedRepository': + item_class = tool_shed_install.ToolShedRepository + else: + item_class = None + return item_class + + +def get_object( trans, id, class_name, check_ownership=False, check_accessible=False, deleted=None ): + """ + Convenience method to get a model object with the specified checks. This is + a generic method for dealing with objects uniformly from the older + controller mixin code - however whenever possible the managers for a + particular model should be used to load objects. + """ + try: + decoded_id = trans.security.decode_id( id ) + except: + raise exceptions.MessageException( "Malformed %s id ( %s ) specified, unable to decode" + % ( class_name, str( id ) ), type='error' ) + try: + item_class = get_class( class_name ) + assert item_class is not None + item = trans.sa_session.query( item_class ).get( decoded_id ) + assert item is not None + except Exception: + log.exception( "Invalid %s id ( %s ) specified." % ( class_name, id ) ) + raise exceptions.MessageException( "Invalid %s id ( %s ) specified" % ( class_name, id ), type="error" ) + + if check_ownership or check_accessible: + security_check( trans, item, check_ownership, check_accessible ) + if deleted is True and not item.deleted: + raise exceptions.ItemDeletionException( '%s "%s" is not deleted' + % ( class_name, getattr( item, 'name', id ) ), type="warning" ) + elif deleted is False and item.deleted: + raise exceptions.ItemDeletionException( '%s "%s" is deleted' + % ( class_name, getattr( item, 'name', id ) ), type="warning" ) + return item + diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/managers/collections.py --- a/lib/galaxy/managers/collections.py +++ b/lib/galaxy/managers/collections.py @@ -1,1 +1,291 @@ -""" Future home of dataset collections managers. """ +from galaxy.dataset_collections.registry import DatasetCollectionTypesRegistry +from galaxy.dataset_collections.matching import MatchingCollections +from galaxy.dataset_collections.type_description import CollectionTypeDescriptionFactory + +from galaxy import model +from galaxy.exceptions import MessageException +from galaxy.exceptions import ItemAccessibilityException +from galaxy.exceptions import RequestParameterInvalidException +from galaxy.managers import hdas # TODO: Refactor all mixin use into managers. +from galaxy.managers import histories +from galaxy.managers import lddas +from galaxy.managers import tags +from galaxy.managers.collections_util import validate_input_element_identifiers +from galaxy.util import validation +from galaxy.util import odict + +import logging +log = logging.getLogger( __name__ ) + + +ERROR_INVALID_ELEMENTS_SPECIFICATION = "Create called with invalid parameters, must specify element identifiers." +ERROR_NO_COLLECTION_TYPE = "Create called without specifing a collection type." + + +class DatasetCollectionManager( object ): + """ + Abstraction for interfacing with dataset collections instance - ideally abstarcts + out model and plugin details. + """ + + def __init__( self, app ): + self.type_registry = DatasetCollectionTypesRegistry( app ) + self.collection_type_descriptions = CollectionTypeDescriptionFactory( self.type_registry ) + self.model = app.model + self.security = app.security + self.hda_manager = hdas.HDAManager() + self.history_manager = histories.HistoryManager() + self.tag_manager = tags.TagsManager( app ) + self.ldda_manager = lddas.LDDAManager( ) + + def create( + self, + trans, + parent, # PRECONDITION: security checks on ability to add to parent occurred during load. + name, + collection_type, + element_identifiers=None, + elements=None, + implicit_collection_info=None, + ): + """ + """ + # Trust embedded, newly created objects created by tool subsystem. + trusted_identifiers = implicit_collection_info is not None + + if element_identifiers and not trusted_identifiers: + validate_input_element_identifiers( element_identifiers ) + + dataset_collection = self.__create_dataset_collection( + trans=trans, + collection_type=collection_type, + element_identifiers=element_identifiers, + elements=elements, + ) + if isinstance( parent, model.History ): + dataset_collection_instance = self.model.HistoryDatasetCollectionAssociation( + collection=dataset_collection, + name=name, + ) + if implicit_collection_info: + for input_name, input_collection in implicit_collection_info[ "implicit_inputs" ]: + dataset_collection_instance.add_implicit_input_collection( input_name, input_collection ) + for output_dataset in implicit_collection_info.get( "outputs" ): + output_dataset.hidden_beneath_collection_instance = dataset_collection_instance + trans.sa_session.add( output_dataset ) + + dataset_collection_instance.implicit_output_name = implicit_collection_info[ "implicit_output_name" ] + log.debug("Created collection with %d elements" % ( len( dataset_collection_instance.collection.elements ) ) ) + # Handle setting hid + parent.add_dataset_collection( dataset_collection_instance ) + elif isinstance( parent, model.LibraryFolder ): + dataset_collection_instance = self.model.LibraryDatasetCollectionAssociation( + collection=dataset_collection, + folder=parent, + name=name, + ) + else: + message = "Internal logic error - create called with unknown parent type %s" % type( parent ) + log.exception( message ) + raise MessageException( message ) + + return self.__persist( dataset_collection_instance ) + + def __create_dataset_collection( + self, + trans, + collection_type, + element_identifiers=None, + elements=None, + ): + if element_identifiers is None and elements is None: + raise RequestParameterInvalidException( ERROR_INVALID_ELEMENTS_SPECIFICATION ) + if not collection_type: + raise RequestParameterInvalidException( ERROR_NO_COLLECTION_TYPE ) + collection_type_description = self.collection_type_descriptions.for_collection_type( collection_type ) + # If we have elements, this is an internal request, don't need to load + # objects from identifiers. + if elements is None: + if collection_type_description.has_subcollections( ): + # Nested collection - recursively create collections and update identifiers. + self.__recursively_create_collections( trans, element_identifiers ) + elements = self.__load_elements( trans, element_identifiers ) + # else if elements is set, it better be an ordered dict! + + type_plugin = collection_type_description.rank_type_plugin() + dataset_collection = type_plugin.build_collection( elements ) + dataset_collection.collection_type = collection_type + return dataset_collection + + def delete( self, trans, instance_type, id ): + dataset_collection_instance = self.get_dataset_collection_instance( trans, instance_type, id, check_ownership=True ) + dataset_collection_instance.deleted = True + trans.sa_session.add( dataset_collection_instance ) + trans.sa_session.flush( ) + + def update( self, trans, instance_type, id, payload ): + dataset_collection_instance = self.get_dataset_collection_instance( trans, instance_type, id, check_ownership=True ) + if trans.user is None: + anon_allowed_payload = {} + if 'deleted' in payload: + anon_allowed_payload[ 'deleted' ] = payload[ 'deleted' ] + if 'visible' in payload: + anon_allowed_payload[ 'visible' ] = payload[ 'visible' ] + payload = self._validate_and_parse_update_payload( anon_allowed_payload ) + else: + payload = self._validate_and_parse_update_payload( payload ) + changed = self._set_from_dict( trans, dataset_collection_instance, payload ) + return changed + + def copy( + self, + trans, + parent, # PRECONDITION: security checks on ability to add to parent occurred during load. + source, + encoded_source_id, + ): + assert source == "hdca" # for now + source_hdca = self.__get_history_collection_instance( trans, encoded_source_id ) + new_hdca = source_hdca.copy() + parent.add_dataset_collection( new_hdca ) + trans.sa_session.add( new_hdca ) + trans.sa_session.flush() + return source_hdca + + def _set_from_dict( self, trans, dataset_collection_instance, new_data ): + # Blatantly stolen from UsesHistoryDatasetAssociationMixin.set_hda_from_dict. + + # send what we can down into the model + changed = dataset_collection_instance.set_from_dict( new_data ) + # the rest (often involving the trans) - do here + if 'annotation' in new_data.keys() and trans.get_user(): + dataset_collection_instance.add_item_annotation( trans.sa_session, trans.get_user(), dataset_collection_instance, new_data[ 'annotation' ] ) + changed[ 'annotation' ] = new_data[ 'annotation' ] + if 'tags' in new_data.keys() and trans.get_user(): + self.tag_manager.set_tags_from_list( trans, dataset_collection_instance, new_data[ 'tags' ], user=trans.user ) + + if changed.keys(): + trans.sa_session.flush() + + return changed + + def _validate_and_parse_update_payload( self, payload ): + validated_payload = {} + for key, val in payload.items(): + if val is None: + continue + if key in ( 'name' ): + val = validation.validate_and_sanitize_basestring( key, val ) + validated_payload[ key ] = val + if key in ( 'deleted', 'visible' ): + validated_payload[ key ] = validation.validate_boolean( key, val ) + elif key == 'tags': + validated_payload[ key ] = validation.validate_and_sanitize_basestring_list( key, val ) + return validated_payload + + def history_dataset_collections(self, history, query): + collections = history.active_dataset_collections + collections = filter( query.direct_match, collections ) + return collections + + def __persist( self, dataset_collection_instance ): + context = self.model.context + context.add( dataset_collection_instance ) + context.flush() + return dataset_collection_instance + + def __recursively_create_collections( self, trans, element_identifiers ): + for index, element_identifier in enumerate( element_identifiers ): + try: + if not element_identifier[ "src" ] == "new_collection": + # not a new collection, keep moving... + continue + except KeyError: + # Not a dictionary, just an id of an HDA - move along. + continue + + # element identifier is a dict with src new_collection... + collection_type = element_identifier.get( "collection_type", None ) + collection = self.__create_dataset_collection( + trans=trans, + collection_type=collection_type, + element_identifiers=element_identifier[ "element_identifiers" ], + ) + element_identifier[ "__object__" ] = collection + + return element_identifiers + + def __load_elements( self, trans, element_identifiers ): + elements = odict.odict() + for element_identifier in element_identifiers: + elements[ element_identifier[ "name" ] ] = self.__load_element( trans, element_identifier ) + return elements + + def __load_element( self, trans, element_identifier ): + #if not isinstance( element_identifier, dict ): + # # Is allowing this to just be the id of an hda too clever? Somewhat + # # consistent with other API methods though. + # element_identifier = dict( src='hda', id=str( element_identifier ) ) + + # Previously created collection already found in request, just pass + # through as is. + if "__object__" in element_identifier: + return element_identifier[ "__object__" ] + + # dateset_identifier is dict {src=hda|ldda|hdca|new_collection, id=<encoded_id>} + try: + src_type = element_identifier.get( 'src', 'hda' ) + except AttributeError: + raise MessageException( "Dataset collection element definition (%s) not dictionary-like." % element_identifier ) + encoded_id = element_identifier.get( 'id', None ) + if not src_type or not encoded_id: + raise RequestParameterInvalidException( "Problem decoding element identifier %s" % element_identifier ) + + if src_type == 'hda': + decoded_id = int( trans.app.security.decode_id( encoded_id ) ) + element = self.hda_manager.get( trans, decoded_id, check_ownership=False ) + elif src_type == 'ldda': + element = self.ldda_manager.get( trans, encoded_id ) + elif src_type == 'hdca': + # TODO: Option to copy? Force copy? Copy or allow if not owned? + element = self.__get_history_collection_instance( trans, encoded_id ).collection + # TODO: ldca. + else: + raise RequestParameterInvalidException( "Unknown src_type parameter supplied '%s'." % src_type ) + return element + + def match_collections( self, collections_to_match ): + """ + May seem odd to place it here, but planning to grow sophistication and + get plugin types involved so it will likely make sense in the future. + """ + return MatchingCollections.for_collections( collections_to_match, self.collection_type_descriptions ) + + def get_dataset_collection_instance( self, trans, instance_type, id, **kwds ): + """ + """ + if instance_type == "history": + return self.__get_history_collection_instance( trans, id, **kwds ) + elif instance_type == "library": + return self.__get_library_collection_instance( trans, id, **kwds ) + + def get_dataset_collection( self, trans, encoded_id ): + collection_id = int( trans.app.security.decode_id( encoded_id ) ) + collection = trans.sa_session.query( trans.app.model.DatasetCollection ).get( collection_id ) + return collection + + def __get_history_collection_instance( self, trans, id, check_ownership=False, check_accessible=True ): + instance_id = int( trans.app.security.decode_id( id ) ) + collection_instance = trans.sa_session.query( trans.app.model.HistoryDatasetCollectionAssociation ).get( instance_id ) + self.history_manager.secure( trans, collection_instance.history, check_ownership=check_ownership, check_accessible=check_accessible ) + return collection_instance + + def __get_library_collection_instance( self, trans, id, check_ownership=False, check_accessible=True ): + if check_ownership: + raise NotImplemented( "Functionality (getting library dataset collection with ownership check) unimplemented." ) + instance_id = int( trans.security.decode_id( id ) ) + collection_instance = trans.sa_session.query( trans.app.model.LibraryDatasetCollectionAssociation ).get( instance_id ) + if check_accessible: + if not trans.app.security_agent.can_access_library_item( trans.get_current_user_roles(), collection_instance, trans.user ): + raise ItemAccessibilityException( "LibraryDatasetCollectionAssociation is not accessible to the current user", type='error' ) + return collection_instance diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/managers/context.py --- a/lib/galaxy/managers/context.py +++ b/lib/galaxy/managers/context.py @@ -4,7 +4,7 @@ import os -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps from galaxy.util import bunch class ProvidesAppContext( object ): @@ -19,7 +19,7 @@ Application-level logging of user actions. """ if self.app.config.log_actions: - action = self.app.model.UserAction(action=action, context=context, params=unicode( to_json_string( params ) ) ) + action = self.app.model.UserAction(action=action, context=context, params=unicode( dumps( params ) ) ) try: if user: action.user = user diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/managers/lddas.py --- /dev/null +++ b/lib/galaxy/managers/lddas.py @@ -0,0 +1,16 @@ +from galaxy.managers import base as manager_base + + +class LDDAManager( manager_base.ModelManager ): + """ A fairly sparse manager for LDDAs. + """ + + def __init__( self ): + """ + Set up and initialize other managers needed by lddas. + """ + pass + + def get( self, trans, id, check_accessible=True ): + return manager_base.get_object( trans, id, 'LibraryDatasetDatasetAssociation', + check_ownership=False, check_accessible=check_accessible ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/managers/tags.py --- /dev/null +++ b/lib/galaxy/managers/tags.py @@ -0,0 +1,20 @@ + + +class TagsManager( object ): + """ Manages CRUD operations related to tagging objects. + """ + + def __init__( self, app ): + self.app = app + self.tag_handler = app.tag_handler + + def set_tags_from_list( self, trans, item, new_tags_list, user=None ): + #precondition: item is already security checked against user + #precondition: incoming tags is a list of sanitized/formatted strings + user = user or trans.user + + self.tag_handler.delete_item_tags( trans, user, item ) + new_tags_str = ','.join( new_tags_list ) + self.tag_handler.apply_item_tags( trans, user, item, unicode( new_tags_str.encode( 'utf-8' ), 'utf-8' ) ) + trans.sa_session.flush() + return item.tags diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/item_attrs.py --- a/lib/galaxy/model/item_attrs.py +++ b/lib/galaxy/model/item_attrs.py @@ -4,6 +4,7 @@ import galaxy import logging import datetime +import uuid log = logging.getLogger( __name__ ) @@ -186,6 +187,8 @@ return value_mapper.get( key )( item ) if type(item) == datetime.datetime: return item.isoformat() + elif type(item) == uuid.UUID: + return str(item) # Leaving this for future reference, though we may want a more # generic way to handle special type mappings going forward. # If the item is of a class that needs to be 'stringified' before being put into a JSON data structure diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0052_sample_dataset_table.py --- a/lib/galaxy/model/migrate/versions/0052_sample_dataset_table.py +++ b/lib/galaxy/model/migrate/versions/0052_sample_dataset_table.py @@ -10,7 +10,7 @@ from sqlalchemy.exc import * from galaxy.model.custom_types import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import datetime now = datetime.datetime.utcnow @@ -62,7 +62,7 @@ for r in result: sample_id = r[0] if r[1]: - dataset_files = from_json_string(r[1]) + dataset_files = loads(r[1]) for df in dataset_files: if type(df) == type(dict()): cmd = "INSERT INTO sample_dataset VALUES (%s, %s, %s, %s, '%s', '%s', '%s', '%s', '%s')" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0054_visualization_dbkey.py --- a/lib/galaxy/model/migrate/versions/0054_visualization_dbkey.py +++ b/lib/galaxy/model/migrate/versions/0054_visualization_dbkey.py @@ -6,7 +6,7 @@ from sqlalchemy.orm import * from migrate import * from migrate.changeset import * -from galaxy.util.json import from_json_string +from galaxy.util.json import loads import logging log = logging.getLogger( __name__ ) @@ -41,7 +41,7 @@ viz_id = viz['viz_id'] viz_rev_id = viz['viz_rev_id'] if viz[Visualization_revision_table.c.config]: - dbkey = from_json_string(viz[Visualization_revision_table.c.config]).get('dbkey', "").replace("'", "\\'") + dbkey = loads(viz[Visualization_revision_table.c.config]).get('dbkey', "").replace("'", "\\'") migrate_engine.execute("UPDATE visualization_revision SET dbkey='%s' WHERE id=%s" % (dbkey, viz_rev_id)) migrate_engine.execute("UPDATE visualization SET dbkey='%s' WHERE id=%s" % (dbkey, viz_id)) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0057_request_notify.py --- a/lib/galaxy/model/migrate/versions/0057_request_notify.py +++ b/lib/galaxy/model/migrate/versions/0057_request_notify.py @@ -10,7 +10,7 @@ from sqlalchemy.exc import * from galaxy.model.custom_types import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import datetime now = datetime.datetime.utcnow @@ -46,13 +46,13 @@ id = int(r[0]) notify_old = r[1] notify_new = dict(email=[], sample_states=[], body='', subject='') - cmd = "update request set notification='%s' where id=%i" % (to_json_string(notify_new), id) + cmd = "update request set notification='%s' where id=%i" % (dumps(notify_new), id) migrate_engine.execute( cmd ) cmd = "SELECT id, notification FROM request" result = migrate_engine.execute( cmd ) for r in result: - rr = from_json_string(str(r[1])) + rr = loads(str(r[1])) # remove the 'notify' column for non-sqlite databases. if migrate_engine.name != 'sqlite': diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0059_sample_dataset_file_path.py --- a/lib/galaxy/model/migrate/versions/0059_sample_dataset_file_path.py +++ b/lib/galaxy/model/migrate/versions/0059_sample_dataset_file_path.py @@ -10,7 +10,7 @@ from sqlalchemy.exc import * from galaxy.model.custom_types import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import datetime now = datetime.datetime.utcnow diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0065_add_name_to_form_fields_and_values.py --- a/lib/galaxy/model/migrate/versions/0065_add_name_to_form_fields_and_values.py +++ b/lib/galaxy/model/migrate/versions/0065_add_name_to_form_fields_and_values.py @@ -9,7 +9,7 @@ from migrate import * from migrate.changeset import * from sqlalchemy.exc import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps from galaxy.model.custom_types import _sniffnfix_pg9_hex import datetime @@ -53,13 +53,13 @@ fields = str( row[1] ) if not fields.strip(): continue - fields_list = from_json_string( _sniffnfix_pg9_hex( fields ) ) + fields_list = loads( _sniffnfix_pg9_hex( fields ) ) if len( fields_list ): for index, field in enumerate( fields_list ): field[ 'name' ] = 'field_%i' % index field[ 'helptext' ] = field[ 'helptext' ].replace("'", "''").replace('"', "") field[ 'label' ] = field[ 'label' ].replace("'", "''") - fields_json = to_json_string( fields_list ) + fields_json = dumps( fields_list ) if migrate_engine.name == 'mysql': cmd = "UPDATE form_definition AS f SET f.fields='%s' WHERE f.id=%i" %( fields_json, form_definition_id ) else: @@ -76,16 +76,16 @@ if not str( row[1] ).strip(): continue row1 = str(row[1]).replace('\n', '').replace('\r', '') - values_list = from_json_string( str( row1 ).strip() ) + values_list = loads( str( row1 ).strip() ) if not str( row[2] ).strip(): continue - fields_list = from_json_string( str( row[2] ).strip() ) + fields_list = loads( str( row[2] ).strip() ) if fields_list and type(values_list) == type(list()): values_dict = {} for field_index, field in enumerate( fields_list ): field_name = field[ 'name' ] values_dict[ field_name ] = get_value(values_list, field_index ) - cmd = "UPDATE form_values SET content='%s' WHERE id=%i" %( to_json_string( values_dict ), form_values_id ) + cmd = "UPDATE form_values SET content='%s' WHERE id=%i" %( dumps( values_dict ), form_values_id ) migrate_engine.execute( cmd ) def downgrade(migrate_engine): @@ -110,17 +110,17 @@ form_values_id = int( row[0] ) if not str( row[1] ).strip(): continue - values_dict = from_json_string( str( row[1] ) ) + values_dict = loads( str( row[1] ) ) if not str( row[2] ).strip(): continue - fields_list = from_json_string( str( row[2] ) ) + fields_list = loads( str( row[2] ) ) if fields_list: values_list = [] for field_index, field in enumerate( fields_list ): field_name = field[ 'name' ] field_value = values_dict[ field_name ] values_list.append( field_value ) - cmd = "UPDATE form_values SET content='%s' WHERE id=%i" %( to_json_string( values_list ), form_values_id ) + cmd = "UPDATE form_values SET content='%s' WHERE id=%i" %( dumps( values_list ), form_values_id ) migrate_engine.execute( cmd ) # remove name attribute from the field column of the form_definition table cmd = "SELECT f.id, f.fields FROM form_definition AS f" @@ -130,13 +130,13 @@ fields = str( row[1] ) if not fields.strip(): continue - fields_list = from_json_string( _sniffnfix_pg9_hex( fields ) ) + fields_list = loads( _sniffnfix_pg9_hex( fields ) ) if len( fields_list ): for index, field in enumerate( fields_list ): if field.has_key( 'name' ): del field[ 'name' ] if migrate_engine.name == 'mysql': - cmd = "UPDATE form_definition AS f SET f.fields='%s' WHERE f.id=%i" %( to_json_string( fields_list ), form_definition_id ) + cmd = "UPDATE form_definition AS f SET f.fields='%s' WHERE f.id=%i" %( dumps( fields_list ), form_definition_id ) else: - cmd = "UPDATE form_definition SET fields='%s' WHERE id=%i" %( to_json_string( fields_list ), form_definition_id ) + cmd = "UPDATE form_definition SET fields='%s' WHERE id=%i" %( dumps( fields_list ), form_definition_id ) migrate_engine.execute( cmd ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0067_populate_sequencer_table.py --- a/lib/galaxy/model/migrate/versions/0067_populate_sequencer_table.py +++ b/lib/galaxy/model/migrate/versions/0067_populate_sequencer_table.py @@ -13,7 +13,7 @@ from galaxy.model.custom_types import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import datetime now = datetime.datetime.utcnow @@ -104,7 +104,7 @@ 'layout': 'none', 'default': '' } ) form_definition_type = 'Sequencer Information Form' - form_definition_layout = to_json_string('[]') + form_definition_layout = dumps('[]') cmd = "INSERT INTO form_definition VALUES ( %s, %s, %s, '%s', '%s', %s, '%s', '%s', '%s' )" cmd = cmd % ( nextval( 'form_definition' ), localtimestamp(), @@ -112,7 +112,7 @@ form_definition_name, form_definition_desc, form_definition_current_id, - to_json_string( form_definition_fields ), + dumps( form_definition_fields ), form_definition_type, form_definition_layout ) migrate_engine.execute( cmd ) @@ -134,7 +134,7 @@ values = str( row[1] ) if not values.strip(): continue - values = from_json_string( values ) + values = loads( values ) # proceed only if sequencer_info is a valid list if values and type( values ) == type( dict() ): if sequencer_info.get( 'host', '' ) == values.get( 'field_0', '' ) \ @@ -148,7 +148,7 @@ def add_sequencer( sequencer_index, sequencer_form_definition_id, sequencer_info ): '''Adds a new sequencer to the sequencer table along with its form values.''' # Create a new form values record with the supplied sequencer information - values = to_json_string( { 'field_0': sequencer_info.get( 'host', '' ), + values = dumps( { 'field_0': sequencer_info.get( 'host', '' ), 'field_1': sequencer_info.get( 'username', '' ), 'field_2': sequencer_info.get( 'password', '' ), 'field_3': sequencer_info.get( 'data_dir', '' ), @@ -233,7 +233,7 @@ # skip if sequencer_info is empty if not sequencer_info.strip() or sequencer_info in ['None', 'null']: continue - sequencer_info = from_json_string( sequencer_info.strip() ) + sequencer_info = loads( sequencer_info.strip() ) # proceed only if sequencer_info is a valid dict if sequencer_info and type( sequencer_info ) == type( dict() ): # check if this sequencer has already been added to the sequencer table @@ -277,9 +277,9 @@ result = migrate_engine.execute( cmd ) for row in result: request_type_id = row[0] - seq_values = from_json_string( str( row[1] ) ) + seq_values = loads( str( row[1] ) ) # create the datatx_info json dict - datatx_info = to_json_string( dict( host = seq_values.get( 'field_0', '' ), + datatx_info = dumps( dict( host = seq_values.get( 'field_0', '' ), username = seq_values.get( 'field_1', '' ), password = seq_values.get( 'field_2', '' ), data_dir = seq_values.get( 'field_3', '' ), diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0068_rename_sequencer_to_external_services.py --- a/lib/galaxy/model/migrate/versions/0068_rename_sequencer_to_external_services.py +++ b/lib/galaxy/model/migrate/versions/0068_rename_sequencer_to_external_services.py @@ -15,7 +15,7 @@ from galaxy.model.custom_types import * -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import datetime now = datetime.datetime.utcnow diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0076_fix_form_values_data_corruption.py --- a/lib/galaxy/model/migrate/versions/0076_fix_form_values_data_corruption.py +++ b/lib/galaxy/model/migrate/versions/0076_fix_form_values_data_corruption.py @@ -9,7 +9,7 @@ from sqlalchemy.exc import * import binascii -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import logging log = logging.getLogger( __name__ ) @@ -42,11 +42,11 @@ # first check if loading the dict from the json succeeds # if that fails, it means that the content field is corrupted. try: - field_values_dict = from_json_string( _sniffnfix_pg9_hex( str( row['field_values'] ) ) ) + field_values_dict = loads( _sniffnfix_pg9_hex( str( row['field_values'] ) ) ) except Exception, e: corrupted_rows = corrupted_rows + 1 # content field is corrupted - fields_list = from_json_string( _sniffnfix_pg9_hex( str( row['fdfields'] ) ) ) + fields_list = loads( _sniffnfix_pg9_hex( str( row['fdfields'] ) ) ) field_values_str = _sniffnfix_pg9_hex( str( row['field_values'] ) ) try: #Encoding errors? Just to be safe. @@ -85,7 +85,7 @@ # add to the new values dict field_values_dict[ field['name'] ] = value # update the db - json_values = to_json_string(field_values_dict) + json_values = dumps(field_values_dict) cmd = "UPDATE form_values SET content='%s' WHERE id=%i" %( json_values, int( row['id'] ) ) migrate_engine.execute( cmd ) try: diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0091_add_tool_version_tables.py --- a/lib/galaxy/model/migrate/versions/0091_add_tool_version_tables.py +++ b/lib/galaxy/model/migrate/versions/0091_add_tool_version_tables.py @@ -12,7 +12,7 @@ # Need our custom types, but don't import anything else from model from galaxy.model.custom_types import * from galaxy.model.custom_types import _sniffnfix_pg9_hex -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps import sys, logging log = logging.getLogger( __name__ ) @@ -77,7 +77,7 @@ for row in result: if row[1]: tool_shed_repository_id = row[0] - repository_metadata = from_json_string( _sniffnfix_pg9_hex( str( row[1] ) ) ) + repository_metadata = loads( _sniffnfix_pg9_hex( str( row[1] ) ) ) # Create a new row in the tool table for each tool included in repository. We will NOT # handle tool_version_associaions because we do not have the information we need to do so. tools = repository_metadata.get( 'tools', [] ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0115_longer_user_password_field.py --- a/lib/galaxy/model/migrate/versions/0115_longer_user_password_field.py +++ b/lib/galaxy/model/migrate/versions/0115_longer_user_password_field.py @@ -22,4 +22,4 @@ try: user.c.password.alter(type=String(40)) except: - log.exception( "Altering password column failed" ) \ No newline at end of file + log.exception( "Altering password column failed" ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/migrate/versions/0117_add_user_activation.py --- a/lib/galaxy/model/migrate/versions/0117_add_user_activation.py +++ b/lib/galaxy/model/migrate/versions/0117_add_user_activation.py @@ -54,4 +54,4 @@ user_active.drop() user_activation_token.drop() except Exception, e: - log.debug( "Dropping 'active' and 'activation_token' columns from galaxy_user table failed: %s" % ( str( e ) ) ) \ No newline at end of file + log.debug( "Dropping 'active' and 'activation_token' columns from galaxy_user table failed: %s" % ( str( e ) ) ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/orm/logging_connection_proxy.py --- a/lib/galaxy/model/orm/logging_connection_proxy.py +++ b/lib/galaxy/model/orm/logging_connection_proxy.py @@ -45,4 +45,4 @@ self.trace_logger.log( "sqlalchemy_query", message="Query executed", statement=statement, parameters=parameters, executemany=executemany, duration=duration ) - return rval \ No newline at end of file + return rval diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/model/search.py --- a/lib/galaxy/model/search.py +++ b/lib/galaxy/model/search.py @@ -39,7 +39,7 @@ Page, PageRevision) from galaxy.model.tool_shed_install import ToolVersion -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps from sqlalchemy import and_ from sqlalchemy.orm import aliased @@ -429,7 +429,7 @@ and_( Job.id == alias.job_id, alias.name == param_name, - alias.value == to_json_string(right) + alias.value == dumps(right) ) ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/openid/__init__.py --- a/lib/galaxy/openid/__init__.py +++ b/lib/galaxy/openid/__init__.py @@ -1,3 +1,3 @@ """ OpenID functionality -""" \ No newline at end of file +""" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/__init__.py --- a/lib/galaxy/tools/__init__.py +++ b/lib/galaxy/tools/__init__.py @@ -756,7 +756,6 @@ tarball_files.append( ( filesystem_path, tarball_path ) ) image_found = True tool_xml = tool_xml.replace( '${static_path}/%s' % tarball_path, tarball_path ) - log.debug( tarball_files ) # If one or more tool help images were found, add the modified tool XML to the tarball instead of the original. if image_found: fd, new_tool_config = tempfile.mkstemp( suffix='.xml' ) @@ -817,8 +816,7 @@ if len( data_table_definitions ) > 0: # Put the data table definition XML in a temporary file. table_definition = '<?xml version="1.0" encoding="utf-8"?>\n<tables>\n %s</tables>' - table_xml = [ data_table.xml_string for data_table in data_table_definitions ] - table_definition = table_definition % '\n'.join( table_xml ) + table_definition = table_definition % '\n'.join( data_table_definitions ) fd, table_conf = tempfile.mkstemp() os.close( fd ) file( table_conf, 'w' ).write( table_definition ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/actions/__init__.py --- a/lib/galaxy/tools/actions/__init__.py +++ b/lib/galaxy/tools/actions/__init__.py @@ -4,7 +4,7 @@ from galaxy.tools.parameters import DataToolParameter from galaxy.tools.parameters import DataCollectionToolParameter from galaxy.tools.parameters.wrapped import WrappedParameters -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps from galaxy.util.none_like import NoneDataset from galaxy.util.odict import odict from galaxy.util.template import fill_template @@ -324,7 +324,7 @@ job.add_output_dataset( name, dataset ) job.object_store_id = object_store_populator.object_store_id if job_params: - job.params = to_json_string( job_params ) + job.params = dumps( job_params ) job.set_handler(tool.get_job_handler(job_params)) trans.sa_session.add( job ) # Now that we have a job id, we can remap any outputs if this is a rerun and the user chose to continue dependent jobs diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/actions/metadata.py --- a/lib/galaxy/tools/actions/metadata.py +++ b/lib/galaxy/tools/actions/metadata.py @@ -1,7 +1,7 @@ from __init__ import ToolAction from galaxy.datatypes.metadata import JobExternalOutputMetadataWrapper from galaxy.util.odict import odict -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps import logging log = logging.getLogger( __name__ ) @@ -50,7 +50,7 @@ if user: job.user_id = user.id if job_params: - job.params = to_json_string( job_params ) + job.params = dumps( job_params ) start_job_state = job.state #should be job.states.NEW try: # For backward compatibility, some tools may not have versions yet. diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/actions/upload_common.py --- a/lib/galaxy/tools/actions/upload_common.py +++ b/lib/galaxy/tools/actions/upload_common.py @@ -7,7 +7,7 @@ from galaxy import datatypes, util from galaxy.util.odict import odict from galaxy.datatypes import sniff -from galaxy.util.json import to_json_string +from galaxy.util.json import dumps from galaxy.model.orm import eagerload_all from galaxy.exceptions import ObjectInvalid @@ -342,7 +342,7 @@ # user cannot remove it unless the parent directory is writable. if link_data_only == 'copy_files' and trans.app.config.external_chown_script: _chown( uploaded_dataset.path ) - json_file.write( to_json_string( json ) + '\n' ) + json_file.write( dumps( json ) + '\n' ) json_file.close() if trans.app.config.external_chown_script: _chown( json_file_path ) @@ -375,7 +375,7 @@ for name, value in tool.params_to_strings( params, trans.app ).iteritems(): job.add_parameter( name, value ) - job.add_parameter( 'paramfile', to_json_string( json_file_path ) ) + job.add_parameter( 'paramfile', dumps( json_file_path ) ) object_store_id = None for i, dataset in enumerate( data_list ): if folder: diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/imp_exp/__init__.py --- a/lib/galaxy/tools/imp_exp/__init__.py +++ b/lib/galaxy/tools/imp_exp/__init__.py @@ -8,7 +8,7 @@ from galaxy.tools.parameters.basic import UnvalidatedValue from galaxy.web.framework.helpers import to_unicode from galaxy.model.item_attrs import UsesAnnotations -from galaxy.util.json import from_json_string, to_json_string +from galaxy.util.json import loads, dumps from galaxy.web.base.controller import UsesHistoryMixin log = logging.getLogger(__name__) @@ -108,7 +108,7 @@ # history_attr_file_name = os.path.join( archive_dir, 'history_attrs.txt') history_attr_str = read_file_contents( history_attr_file_name ) - history_attrs = from_json_string( history_attr_str ) + history_attrs = loads( history_attr_str ) # Create history. new_history = model.History( name='imported from archive: %s' % history_attrs['name'].encode( 'utf-8' ), \ @@ -134,12 +134,12 @@ # datasets_attrs_file_name = os.path.join( archive_dir, 'datasets_attrs.txt') datasets_attr_str = read_file_contents( datasets_attrs_file_name ) - datasets_attrs = from_json_string( datasets_attr_str ) - + datasets_attrs = loads( datasets_attr_str ) + if os.path.exists( datasets_attrs_file_name + ".provenance" ): provenance_attr_str = read_file_contents( datasets_attrs_file_name + ".provenance" ) - provenance_attrs = from_json_string( provenance_attr_str ) - datasets_attrs += provenance_attrs + provenance_attrs = loads( provenance_attr_str ) + datasets_attrs += provenance_attrs # Get counts of how often each dataset file is used; a file can # be linked to multiple dataset objects (HDAs). @@ -230,7 +230,7 @@ return self.sa_session.query( model.HistoryDatasetAssociation ) \ .filter_by( history=new_history, hid=obj_dct['hid'] ).first() return obj_dct - jobs_attrs = from_json_string( jobs_attr_str, object_hook=as_hda ) + jobs_attrs = loads( jobs_attr_str, object_hook=as_hda ) # Create each job. for job_attrs in jobs_attrs: @@ -279,7 +279,7 @@ .filter_by( history=new_history, hid=value.hid ).first() value = input_hda.id #print "added parameter %s-->%s to job %i" % ( name, value, imported_job.id ) - imported_job.add_parameter( name, to_json_string( value, cls=HistoryDatasetAssociationIDEncoder ) ) + imported_job.add_parameter( name, dumps( value, cls=HistoryDatasetAssociationIDEncoder ) ) # TODO: Connect jobs to input datasets. @@ -292,14 +292,14 @@ imported_job.add_output_dataset( output_hda.name, output_hda ) # Connect jobs to input datasets. - if 'input_mapping' in job_attrs: + if 'input_mapping' in job_attrs: for input_name, input_hid in job_attrs[ 'input_mapping' ].items(): #print "%s job has input dataset %i" % (imported_job.id, input_hid) input_hda = self.sa_session.query( model.HistoryDatasetAssociation ) \ .filter_by( history=new_history, hid=input_hid ).first() if input_hda: imported_job.add_input_dataset( input_name, input_hda ) - + self.sa_session.flush() @@ -409,7 +409,7 @@ } history_attrs_filename = tempfile.NamedTemporaryFile( dir=temp_output_dir ).name history_attrs_out = open( history_attrs_filename, 'w' ) - history_attrs_out.write( to_json_string( history_attrs ) ) + history_attrs_out.write( dumps( history_attrs ) ) history_attrs_out.close() jeha.history_attrs_filename = history_attrs_filename @@ -427,12 +427,12 @@ included_datasets.append( dataset ) datasets_attrs_filename = tempfile.NamedTemporaryFile( dir=temp_output_dir ).name datasets_attrs_out = open( datasets_attrs_filename, 'w' ) - datasets_attrs_out.write( to_json_string( datasets_attrs, cls=HistoryDatasetAssociationEncoder ) ) + datasets_attrs_out.write( dumps( datasets_attrs, cls=HistoryDatasetAssociationEncoder ) ) datasets_attrs_out.close() jeha.datasets_attrs_filename = datasets_attrs_filename - + provenance_attrs_out = open( datasets_attrs_filename + ".provenance", 'w' ) - provenance_attrs_out.write( to_json_string( provenance_attrs, cls=HistoryDatasetAssociationEncoder ) ) + provenance_attrs_out.write( dumps( provenance_attrs, cls=HistoryDatasetAssociationEncoder ) ) provenance_attrs_out.close() # @@ -477,7 +477,7 @@ job_attrs[ 'exit_code' ] = job.exit_code job_attrs[ 'create_time' ] = job.create_time.isoformat() job_attrs[ 'update_time' ] = job.update_time.isoformat() - + # Get the job's parameters try: @@ -509,7 +509,7 @@ jobs_attrs_filename = tempfile.NamedTemporaryFile( dir=temp_output_dir ).name jobs_attrs_out = open( jobs_attrs_filename, 'w' ) - jobs_attrs_out.write( to_json_string( jobs_attrs, cls=HistoryDatasetAssociationEncoder ) ) + jobs_attrs_out.write( dumps( jobs_attrs, cls=HistoryDatasetAssociationEncoder ) ) jobs_attrs_out.close() jeha.jobs_attrs_filename = jobs_attrs_filename diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/imp_exp/export_history.py --- a/lib/galaxy/tools/imp_exp/export_history.py +++ b/lib/galaxy/tools/imp_exp/export_history.py @@ -39,7 +39,7 @@ except OverflowError: pass datasets_attr_in.close() - datasets_attrs = from_json_string( datasets_attr_str ) + datasets_attrs = loads( datasets_attr_str ) # Add datasets to archive and update dataset attributes. # TODO: security check to ensure that files added are in Galaxy dataset directory? @@ -54,7 +54,7 @@ # Rewrite dataset attributes file. datasets_attrs_out = open( datasets_attrs_file, 'w' ) - datasets_attrs_out.write( to_json_string( datasets_attrs ) ) + datasets_attrs_out.write( dumps( datasets_attrs ) ) datasets_attrs_out.close() # Finish archive. @@ -80,4 +80,4 @@ # Create archive. status = create_archive( history_attrs, dataset_attrs, job_attrs, out_file, gzip ) - print status \ No newline at end of file + print status diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/parameters/__init__.py --- a/lib/galaxy/tools/parameters/__init__.py +++ b/lib/galaxy/tools/parameters/__init__.py @@ -85,7 +85,7 @@ for key, value in param_values.iteritems(): if key in params: value = params[ key ].value_to_basic( value, app ) - rval[ key ] = str( to_json_string( value ) ) + rval[ key ] = str( dumps( value ) ) return rval @@ -98,7 +98,7 @@ """ rval = dict() for key, value in param_values.iteritems(): - value = json_fix( from_json_string( value ) ) + value = json_fix( loads( value ) ) if key in params: value = params[key].value_from_basic( value, app, ignore_errors ) rval[ key ] = value diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/tools/util/__init__.py --- a/lib/galaxy/tools/util/__init__.py +++ b/lib/galaxy/tools/util/__init__.py @@ -3,4 +3,4 @@ FIXME: These are used by tool scripts, not the framework, and should not live in this package. -""" \ No newline at end of file +""" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/__init__.py --- a/lib/galaxy/util/__init__.py +++ b/lib/galaxy/util/__init__.py @@ -338,8 +338,8 @@ def pretty_print_json(json_data, is_json_string=False): if is_json_string: - json_data = json.from_json_string(json_data) - return json.to_json_string(json_data, sort_keys=True, indent=4) + json_data = json.loads(json_data) + return json.dumps(json_data, sort_keys=True, indent=4) # characters that are valid valid_chars = set(string.letters + string.digits + " -=_.()/+*^,:?!") diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/backports/__init__.py --- a/lib/galaxy/util/backports/__init__.py +++ b/lib/galaxy/util/backports/__init__.py @@ -1,3 +1,3 @@ """ Modules for providing backward compatibility with future versions of Python -""" \ No newline at end of file +""" diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/backports/importlib/__init__.py --- a/lib/galaxy/util/backports/importlib/__init__.py +++ b/lib/galaxy/util/backports/importlib/__init__.py @@ -39,4 +39,4 @@ ## Note: this was copied from ## http://svn.python.org/projects/python/trunk/Lib/importlib/__init__.py - ## on 24 September 2012 \ No newline at end of file + ## on 24 September 2012 diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/dbkeys.py --- a/lib/galaxy/util/dbkeys.py +++ b/lib/galaxy/util/dbkeys.py @@ -3,7 +3,7 @@ """ #dbkeys read from disk using builds.txt from galaxy.util import read_dbnames -from galaxy.util.json import from_json_string +from galaxy.util.json import loads import os.path @@ -38,7 +38,7 @@ rval.append( ( dataset.dbkey, "%s (%s) [History]" % ( dataset.name, dataset.dbkey ) ) ) user = trans.user if user and 'dbkeys' in user.preferences: - user_keys = from_json_string( user.preferences['dbkeys'] ) + user_keys = loads( user.preferences['dbkeys'] ) for key, chrom_dict in user_keys.iteritems(): rval.append( ( key, "%s (%s) [Custom]" % ( chrom_dict['name'], key ) ) ) # Load old builds.txt static keys @@ -61,8 +61,8 @@ chrom_info = db_dataset.file_name else: # Do Custom Build handling - if trans.user and ( 'dbkeys' in trans.user.preferences ) and ( dbkey in from_json_string( trans.user.preferences[ 'dbkeys' ] ) ): - custom_build_dict = from_json_string( trans.user.preferences[ 'dbkeys' ] )[ dbkey ] + if trans.user and ( 'dbkeys' in trans.user.preferences ) and ( dbkey in loads( trans.user.preferences[ 'dbkeys' ] ) ): + custom_build_dict = loads( trans.user.preferences[ 'dbkeys' ] )[ dbkey ] # HACK: the attempt to get chrom_info below will trigger the # fasta-to-len converter if the dataset is not available or, # which will in turn create a recursive loop when diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/json.py --- a/lib/galaxy/util/json.py +++ b/lib/galaxy/util/json.py @@ -1,14 +1,16 @@ from __future__ import absolute_import -__all__ = [ "to_json_string", "from_json_string", "json_fix", "validate_jsonrpc_request", "validate_jsonrpc_response", "jsonrpc_request", "jsonrpc_response" ] +__all__ = [ "dumps", "loads", "json_fix", "validate_jsonrpc_request", "validate_jsonrpc_response", "jsonrpc_request", "jsonrpc_response" ] import json import logging import random import string -to_json_string = json.dumps -from_json_string = json.loads +to_json_string = json.dumps # deprecated +from_json_string = json.loads # deprecated +dumps = json.dumps +loads = json.loads log = logging.getLogger( __name__ ) @@ -23,12 +25,12 @@ else: return val + # Methods for handling JSON-RPC - def validate_jsonrpc_request( request, regular_methods, notification_methods ): try: - request = from_json_string( request ) + request = loads( request ) except Exception, e: return False, request, jsonrpc_response( id=None, error=dict( code=-32700, @@ -65,7 +67,7 @@ def validate_jsonrpc_response( response, id=None ): try: - response = from_json_string( response ) + response = loads( response ) except Exception, e: log.error( 'Response was not valid JSON: %s' % str( e ) ) log.debug( 'Response was: %s' % response ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/log/__init__.py --- a/lib/galaxy/util/log/__init__.py +++ b/lib/galaxy/util/log/__init__.py @@ -2,4 +2,4 @@ def __init__( self, name ): self.name = name def log( **kwargs ): - raise TypeError( "Abstract Method" ) \ No newline at end of file + raise TypeError( "Abstract Method" ) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/util/pastescript/serve.py --- a/lib/galaxy/util/pastescript/serve.py +++ b/lib/galaxy/util/pastescript/serve.py @@ -1056,4 +1056,4 @@ except BadCommand, e: print e.message exit_code = e.exit_code - sys.exit(exit_code) \ No newline at end of file + sys.exit(exit_code) diff -r 858c12951cfa764fb8b948e360b29f8a9e90b89b -r d277478dce504dac182886b89192459bc6f83db3 lib/galaxy/visualization/data_providers/__init__.py --- a/lib/galaxy/visualization/data_providers/__init__.py +++ b/lib/galaxy/visualization/data_providers/__init__.py @@ -1,3 +1,3 @@ """ Galaxy visualization/visual analysis data providers. -""" \ No newline at end of file +""" This diff is so big that we needed to truncate the remainder. https://bitbucket.org/galaxy/galaxy-central/commits/3497f7509b00/ Changeset: 3497f7509b00 User: martenson Date: 2014-09-16 15:56:13+00:00 Summary: trying to merge Affected #: 35 files diff -r 80d68ea889c01357b520ecefc56f86b0a44549fc -r 3497f7509b007b04a4db905daf3509f1f3c76626 client/galaxy/scripts/galaxy.library.js --- a/client/galaxy/scripts/galaxy.library.js +++ b/client/galaxy/scripts/galaxy.library.js @@ -47,7 +47,8 @@ "folders/:folder_id/datasets/:dataset_id" : "dataset_detail", "folders/:folder_id/datasets/:dataset_id/permissions" : "dataset_permissions", "folders/:folder_id/datasets/:dataset_id/versions/:ldda_id" : "dataset_version", - "folders/:folder_id/download/:format" : "download" + "folders/:folder_id/download/:format" : "download", + "folders/:folder_id/import/:source" : "import_datasets" }, back: function() { @@ -147,6 +148,15 @@ } Galaxy.libraries.folderView = new mod_library_folder_view.FolderView({id: folder_id, show_permissions: true}); }); + this.library_router.on('route:import_datasets', function(folder_id, source){ + if (Galaxy.libraries.folderToolbarView && Galaxy.libraries.folderListView){ + Galaxy.libraries.folderToolbarView.showImportModal({source:source}); + } else { + Galaxy.libraries.folderToolbarView = new mod_foldertoolbar_view.FolderToolbarView({id: folder_id}); + Galaxy.libraries.folderListView = new mod_folderlist_view.FolderListView({id: folder_id}); + Galaxy.libraries.folderToolbarView.showImportModal({source: source}); + } + }); Backbone.history.start({pushState: false}); } This diff is so big that we needed to truncate the remainder. https://bitbucket.org/galaxy/galaxy-central/commits/aec146e3828b/ Changeset: aec146e3828b User: martenson Date: 2014-09-16 17:15:32+00:00 Summary: removed bug with missing return Affected #: 5 files diff -r 3497f7509b007b04a4db905daf3509f1f3c76626 -r aec146e3828b16812ca24c5f8651ba3d0d483a6a client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js --- a/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js +++ b/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js @@ -592,13 +592,15 @@ // need to check which paths to call var that = this; var popped_item = paths.pop(); - if (typeof popped_item === "undefined") { + if (typeof popped_item == "undefined") { if (this.options.chain_call_control.failed_number === 0){ mod_toastr.success('Selected folders and their contents imported into the current folder'); Galaxy.modal.hide(); } else { + // TODO better error report mod_toastr.error('Something went wrong :('); } + return true; } var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + '&source=' + source + diff -r 3497f7509b007b04a4db905daf3509f1f3c76626 -r aec146e3828b16812ca24c5f8651ba3d0d483a6a static/scripts/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/mvc/library/library-foldertoolbar-view.js @@ -592,13 +592,14 @@ // need to check which paths to call var that = this; var popped_item = paths.pop(); - if (typeof popped_item === "undefined") { + if (typeof popped_item == "undefined") { if (this.options.chain_call_control.failed_number === 0){ mod_toastr.success('Selected folders and their contents imported into the current folder'); Galaxy.modal.hide(); } else { mod_toastr.error('Something went wrong :('); } + return true; } var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + '&source=' + source + diff -r 3497f7509b007b04a4db905daf3509f1f3c76626 -r aec146e3828b16812ca24c5f8651ba3d0d483a6a static/scripts/packed/mvc/library/library-folderrow-view.js --- a/static/scripts/packed/mvc/library/library-folderrow-view.js +++ b/static/scripts/packed/mvc/library/library-folderrow-view.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr","mvc/library/library-model","mvc/library/library-dataset-view"],function(c,e,f,d,b){var a=Backbone.View.extend({lastSelectedHistory:"",events:{"click .undelete_dataset_btn":"undelete_dataset"},options:{type:null},initialize:function(g){this.render(g)},render:function(g){var h=null;if(g.get("type")==="folder"){this.options.type="folder";h=this.templateRowFolder()}else{this.options.type="file";if(g.get("deleted")){h=this.templateRowDeletedFile()}else{h=this.templateRowFile()}}this.setElement(h({content_item:g}));this.$el.show();return this},showDatasetDetails:function(){Galaxy.libraries.datasetView=new b.LibraryDatasetView({id:this.id})},undelete_dataset:function(i){$(".tooltip").hide();var h=this;var g=$(i.target).closest("tr")[0].id;var j=Galaxy.libraries.folderListView.collection.get(g);j.url=j.urlRoot+j.id+"?undelete=true";j.destroy({success:function(l,k){Galaxy.libraries.folderListView.collection.remove(g);var m=new d.Item(k);Galaxy.libraries.folderListView.collection.add(m);f.success("Dataset undeleted. Click this to see it.","",{onclick:function(){h.showDatasetDetails()}})},error:function(l,k){if(typeof k.responseJSON!=="undefined"){f.error("Dataset was not undeleted. "+k.responseJSON.err_msg)}else{f.error("An error occured! Dataset was not undeleted. Please try again.")}}})},templateRowFolder:function(){tmpl_array=[];tmpl_array.push('<tr class="folder_row light library-row" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Folder" class="fa fa-folder-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(" <td></td>");tmpl_array.push(" <td>");tmpl_array.push(' <a href="#folders/<%- content_item.id %>"><%- content_item.get("name") %></a>');tmpl_array.push(" </td>");tmpl_array.push(" <td>folder</td>");tmpl_array.push(" <td></td>");tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(" <td>");tmpl_array.push(' <% if (content_item.get("can_manage")) { %><a href="#/folders/<%- content_item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" class="primary-button btn-xs permissions-folder-btn show_on_hover" title="Manage permissions" style="display:none;"><span class="fa fa-group"></span></button></a><% } %>');tmpl_array.push(" </td>");tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))},templateRowFile:function(){tmpl_array=[];tmpl_array.push('<tr class="dataset_row light library-row" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Dataset" class="fa fa-file-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(' <td style="text-align: center; "><input style="margin: 0;" type="checkbox"></td>');tmpl_array.push(' <td><a href="#folders/<%- content_item.get("folder_id") %>/datasets/<%- content_item.id %>" class="library-dataset"><%- content_item.get("name") %><a></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_ext")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_size")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(" <td>");tmpl_array.push(' <% if (content_item.get("is_unrestricted")) { %><span data-toggle="tooltip" data-placement="top" title="Unrestricted dataset" style="color:grey;" class="fa fa-globe fa-lg"></span><% } %>');tmpl_array.push(' <% if (content_item.get("is_private")) { %><span data-toggle="tooltip" data-placement="top" title="Private dataset" style="color:grey;" class="fa fa-key fa-lg"></span><% } %>');tmpl_array.push(' <% if ((content_item.get("is_unrestricted") === false) && (content_item.get("is_private") === false)) { %><span data-toggle="tooltip" data-placement="top" title="Restricted dataset" style="color:grey;" class="fa fa-shield fa-lg"></span><% } %>');tmpl_array.push(' <% if (content_item.get("can_manage")) { %><a href="#folders/<%- content_item.get("folder_id") %>/datasets/<%- content_item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" class="primary-button btn-xs permissions-dataset-btn show_on_hover" title="Manage permissions" style="display:none;"><span class="fa fa-group"></span></button></a><% } %>');tmpl_array.push(" </td>");tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))},templateRowDeletedFile:function(){tmpl_array=[];tmpl_array.push('<tr class="active deleted_dataset" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Dataset" class="fa fa-file-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(" <td></td>");tmpl_array.push(' <td style="color:grey;"><%- content_item.get("name") %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_ext")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_size")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(' <td><span data-toggle="tooltip" data-placement="top" title="Marked deleted" style="color:grey;" class="fa fa-ban fa-lg"></span><button data-toggle="tooltip" data-placement="top" title="Undelete <%- content_item.get("name") %>" class="primary-button btn-xs undelete_dataset_btn show_on_hover" type="button" style="display:none; margin-left:1em;"><span class="fa fa-unlock"> Undelete</span></button></td>');tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))}});return{FolderRowView:a}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr","mvc/library/library-model","mvc/library/library-dataset-view"],function(c,e,f,d,b){var a=Backbone.View.extend({lastSelectedHistory:"",events:{"click .undelete_dataset_btn":"undelete_dataset"},options:{type:null},initialize:function(g){this.model=g;this.render(g)},render:function(g){var h=null;if(g.get("type")==="folder"){this.options.type="folder";h=this.templateRowFolder()}else{this.options.type="file";if(g.get("deleted")){h=this.templateRowDeletedFile()}else{h=this.templateRowFile()}}this.setElement(h({content_item:g}));this.$el.show();return this},showDatasetDetails:function(){Galaxy.libraries.datasetView=new b.LibraryDatasetView({id:this.id})},undelete_dataset:function(i){$(".tooltip").hide();var h=this;var g=$(i.target).closest("tr")[0].id;var j=Galaxy.libraries.folderListView.collection.get(g);j.url=j.urlRoot+j.id+"?undelete=true";j.destroy({success:function(l,k){Galaxy.libraries.folderListView.collection.remove(g);var m=new d.Item(k);Galaxy.libraries.folderListView.collection.add(m);f.success("Dataset undeleted. Click this to see it.","",{onclick:function(){var n=h.model.get("folder_id");window.location="#folders/"+n+"/datasets/"+h.id}})},error:function(l,k){if(typeof k.responseJSON!=="undefined"){f.error("Dataset was not undeleted. "+k.responseJSON.err_msg)}else{f.error("An error occured! Dataset was not undeleted. Please try again.")}}})},templateRowFolder:function(){tmpl_array=[];tmpl_array.push('<tr class="folder_row light library-row" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Folder" class="fa fa-folder-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(" <td></td>");tmpl_array.push(" <td>");tmpl_array.push(' <a href="#folders/<%- content_item.id %>"><%- content_item.get("name") %></a>');tmpl_array.push(" </td>");tmpl_array.push(" <td>folder</td>");tmpl_array.push(" <td></td>");tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(" <td>");tmpl_array.push(' <% if (content_item.get("can_manage")) { %><a href="#/folders/<%- content_item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" class="primary-button btn-xs permissions-folder-btn show_on_hover" title="Manage permissions" style="display:none;"><span class="fa fa-group"></span></button></a><% } %>');tmpl_array.push(" </td>");tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))},templateRowFile:function(){tmpl_array=[];tmpl_array.push('<tr class="dataset_row light library-row" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Dataset" class="fa fa-file-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(' <td style="text-align: center; "><input style="margin: 0;" type="checkbox"></td>');tmpl_array.push(' <td><a href="#folders/<%- content_item.get("folder_id") %>/datasets/<%- content_item.id %>" class="library-dataset"><%- content_item.get("name") %><a></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_ext")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_size")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(" <td>");tmpl_array.push(' <% if (content_item.get("is_unrestricted")) { %><span data-toggle="tooltip" data-placement="top" title="Unrestricted dataset" style="color:grey;" class="fa fa-globe fa-lg"></span><% } %>');tmpl_array.push(' <% if (content_item.get("is_private")) { %><span data-toggle="tooltip" data-placement="top" title="Private dataset" style="color:grey;" class="fa fa-key fa-lg"></span><% } %>');tmpl_array.push(' <% if ((content_item.get("is_unrestricted") === false) && (content_item.get("is_private") === false)) { %><span data-toggle="tooltip" data-placement="top" title="Restricted dataset" style="color:grey;" class="fa fa-shield fa-lg"></span><% } %>');tmpl_array.push(' <% if (content_item.get("can_manage")) { %><a href="#folders/<%- content_item.get("folder_id") %>/datasets/<%- content_item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" class="primary-button btn-xs permissions-dataset-btn show_on_hover" title="Manage permissions" style="display:none;"><span class="fa fa-group"></span></button></a><% } %>');tmpl_array.push(" </td>");tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))},templateRowDeletedFile:function(){tmpl_array=[];tmpl_array.push('<tr class="active deleted_dataset library-row" id="<%- content_item.id %>">');tmpl_array.push(" <td>");tmpl_array.push(' <span title="Dataset" class="fa fa-file-o"></span>');tmpl_array.push(" </td>");tmpl_array.push(" <td></td>");tmpl_array.push(' <td style="color:grey;"><%- content_item.get("name") %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_ext")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("file_size")) %></td>');tmpl_array.push(' <td><%= _.escape(content_item.get("update_time")) %></td>');tmpl_array.push(' <td><span data-toggle="tooltip" data-placement="top" title="Marked deleted" style="color:grey;" class="fa fa-ban fa-lg"></span><button data-toggle="tooltip" data-placement="top" title="Undelete <%- content_item.get("name") %>" class="primary-button btn-xs undelete_dataset_btn show_on_hover" type="button" style="display:none; margin-left:1em;"><span class="fa fa-unlock"> Undelete</span></button></td>');tmpl_array.push("</tr>");return _.template(tmpl_array.join(""))}});return{FolderRowView:a}}); \ No newline at end of file diff -r 3497f7509b007b04a4db905daf3509f1f3c76626 -r aec146e3828b16812ca24c5f8651ba3d0d483a6a static/scripts/packed/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/packed/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/packed/mvc/library/library-foldertoolbar-view.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr","libs/jquery/jstree","mvc/library/library-model"],function(c,e,f,b,d){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0},disabled_jstree_element:"folders"},modal:null,jstree:null,histories:null,initialize:function(g){this.options=_.defaults(g||{},this.defaults);this.render()},render:function(g){this.options=_.extend(this.options,g);var i=this.templateToolBar();var h={id:this.options.id,is_admin:false,is_anonym:true,user_library_import_dir:Galaxy.config.user_library_import_dir,allow_library_path_paste:Galaxy.config.allow_library_path_paste,library_import_dir:Galaxy.config.library_import_dir,mutiple_add_dataset_options:false};if(Galaxy.currUser){h.is_admin=Galaxy.currUser.isAdmin();h.is_anonym=Galaxy.currUser.isAnonymous();if(h.user_library_import_dir!==null||h.allow_library_path_paste!==false||h.library_import_dir!==null){h.mutiple_add_dataset_options=true}}this.$el.html(i(h))},configureElements:function(g){this.options=_.extend(this.options,g);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(i){i.preventDefault();i.stopPropagation();var g=this;var h=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:h(),buttons:{Create:function(){g.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var g=this.serialize_new_folder();if(this.validate_new_folder(g)){var h=new d.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];h.url=h.urlRoot+"/"+current_folder_id;h.save(g,{success:function(i){Galaxy.modal.hide();f.success("Folder created");i.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(i)},error:function(j,i){Galaxy.modal.hide();if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}else{f.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(g){return g.name!==""},modalBulkImport:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(i){var h=i.templateBulkImportInModal();i.modal=Galaxy.modal;i.modal.show({closing_events:true,title:"Import into History",body:h({histories:i.histories.models}),buttons:{Import:function(){i.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(h){var g=this;this.histories=new d.GalaxyHistories();this.histories.fetch({success:function(){h(g)},error:function(j,i){if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var k=$("select[name=dataset_import_bulk] option:selected").val();this.options.last_used_history_id=k;var n=$("select[name=dataset_import_bulk] option:selected").text();var p=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){p.push(this.parentElement.parentElement.id)}});var o=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(o({history_name:n}));var l=100/p.length;this.initProgress(l);var g=[];for(var h=p.length-1;h>=0;h--){var j=p[h];var m=new d.HistoryItem();m.url=m.urlRoot+k+"/contents";m.content=j;m.source="library";g.push(m)}this.options.chain_call_control.total_number=g.length;jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+k);this.chainCall(g,n)},chainCall:function(h,k){var g=this;var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return}var j=$.when(i.save({content:i.content,source:i.source}));j.done(function(){g.updateProgress();g.chainCall(h,k)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCall(h,k)})},initProgress:function(g){this.progress=0;this.progressStep=g},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(g,k){var i=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){i.push(this.parentElement.parentElement.id)}});var h="/api/libraries/datasets/download/"+k;var j={ldda_ids:i};this.processDownload(h,j,"get")},processDownload:function(h,i,j){if(h&&i){i=typeof i==="string"?i:$.param(i);var g="";$.each(i.split("&"),function(){var k=this.split("=");g+='<input type="hidden" name="'+k[0]+'" value="'+k[1]+'" />'});$('<form action="'+h+'" method="'+(j||"post")+'">'+g+"</form>").appendTo("body").submit().remove();f.info("Your download will begin soon")}else{f.error("An error occurred :(")}},addFilesFromHistoryModal:function(){this.refreshUserHistoriesList(function(g){g.modal=Galaxy.modal;var h=g.templateAddFilesFromHistory();var i=g.options.full_path[g.options.full_path.length-1][1];g.modal.show({closing_events:true,title:"Adding datasets from your history to folder "+i,body:h({histories:g.histories.models}),buttons:{Add:function(){g.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.back()}});if(g.histories.models.length>0){g.fetchAndDisplayHistoryContents(g.histories.models[0].id);$("#dataset_add_bulk").change(function(j){g.fetchAndDisplayHistoryContents(j.target.value)})}else{f.error("An error ocurred :(")}})},importFilesFromPathModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateImportPathModal();this.modal.show({closing_events:true,title:"Enter paths relative to Galaxy root",body:g({}),buttons:{Import:function(){h.importFromPathsClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}})},importFilesFromUserdirModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateBrowserModal();this.modal.show({closing_events:true,title:"Select folders or files to import",body:g({}),buttons:{Import:function(){h.importFromUserdirClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}});this.renderJstree({disabled_jstree_element:"folders"});$("input[type=radio]").change(function(i){if(i.target.value==="jstree-disable-folders"){h.renderJstree({disabled_jstree_element:"folders"});$(".jstree-folders-message").hide();$(".jstree-preserve-structure").hide();$(".jstree-link-files").hide();$(".jstree-files-message").show()}else{if(i.target.value==="jstree-disable-files"){$(".jstree-files-message").hide();$(".jstree-folders-message").show();$(".jstree-link-files").show();$(".jstree-preserve-structure").show();h.renderJstree({disabled_jstree_element:"files"})}}})},renderJstree:function(g){var i=this;this.options=_.extend(this.options,g);var h=this.options.disabled_jstree_element;this.jstree=new d.Jstree();this.jstree.url=this.jstree.urlRoot+"?target=userdir&format=jstree&disable="+h;this.jstree.fetch({success:function(k,j){$("#jstree_browser").jstree("destroy");var l=$("#jstree_browser").jstree({core:{data:k},plugins:["types","checkbox"],types:{folder:{icon:"jstree-folder"},file:{icon:"jstree-file"}},checkbox:{three_state:false}})},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importFromPathsClicked:function(){var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var l=this.modal.$el.find(".link-checkbox").is(":checked");var k=$("textarea#import_paths").val();if(!k){f.info("Please enter a path relative to Galaxy root")}else{this.modal.disableButton("Import");k=k.split("\n");var j=[];for(var h=k.length-1;h>=0;h--){trimmed=k[h].trim();if(trimmed.length!==0){j.push(trimmed)}}this.initChainCallControl(j.length);this.chainCallImportingFolders(j,g,l,"admin_path")}},initChainCallControl:function(g){var h=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(h({folder_name:this.options.folder_name}));this.progress=0;this.progressStep=100/g;this.options.chain_call_control.total_number=g;this.options.chain_call_control.failed_number=0},importFromUserdirClicked:function(l){var h=$("#jstree_browser").jstree().get_selected(true);var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var o=this.modal.$el.find(".link-checkbox").is(":checked");var n=[];if(h.length<1){f.info("You have to select some items first")}else{this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;for(var j=h.length-1;j>=0;j--){if(h[j].li_attr.full_path!==undefined){n.push(h[j].li_attr.full_path)}}var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/n.length;this.progress=0;this.options.chain_call_control.total_number=n.length;var k=h[0].type;if(k==="folder"){this.chainCallImportingFolders(n,g,o,"userdir_folder")}else{if(k==="file"){this.chainCallImportingUserdirFiles(n)}}}},chainCallImportingUserdirFiles:function(j){var g=this;var h=j.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected files imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var i=$.when($.post("/api/libraries/datasets?encoded_folder_id="+g.id+"&source=userdir_file&path="+h));i.done(function(k){g.updateProgress();g.chainCallImportingUserdirFiles(j)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallImportingUserdirFiles(j)})},chainCallImportingFolders:function(l,g,m,j){var h=this;var i=l.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected folders and their contents imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}}var k=$.when($.post("/api/libraries/datasets?encoded_folder_id="+h.id+"&source="+j+"&path="+i+"&preserve_dirs="+g+"&link_data="+m));k.done(function(n){h.updateProgress();h.chainCallImportingFolders(l,g,m,j)}).fail(function(){h.options.chain_call_control.failed_number+=1;h.updateProgress();h.chainCallImportingFolders(l,g,m,j)})},fetchAndDisplayHistoryContents:function(i){var h=new d.HistoryContents({id:i});var g=this;h.fetch({success:function(k){var j=g.templateHistoryContents();g.histories.get(i).set({contents:k});g.modal.$el.find("#selected_history_content").html(j({history_contents:k.models.reverse()}))},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){var l=this.modal.$el.find("#selected_history_content").find(":checked");if(l.length<1){f.info("You have to select some datasets first")}else{this.modal.disableButton("Add");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];l.each(function(){var i=$(this.parentElement).data("id");if(i){g.push(i)}});var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/g.length;this.progress=0;var k=[];for(var j=g.length-1;j>=0;j--){history_dataset_id=g[j];var h=new d.Item();h.url="/api/folders/"+this.options.id+"/contents";h.set({from_hda_id:history_dataset_id});k.push(h)}this.options.chain_call_control.total_number=k.length;this.chainCallAddingHdas(k)}},chainCallAddingHdas:function(h){var g=this;this.added_hdas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var j=$.when(i.save({from_hda_id:i.get("from_hda_id")}));j.done(function(k){Galaxy.libraries.folderListView.collection.add(k);g.updateProgress();g.chainCallAddingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallAddingHdas(h)})},checkIncludeDeleted:function(g){if(g.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{var k=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:k({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var h=[];g.each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});this.progressStep=100/h.length;this.progress=0;var m=[];for(var j=h.length-1;j>=0;j--){var l=new d.Item({id:h[j]});m.push(l)}this.options.chain_call_control.total_number=h.length;this.chainCallDeletingHdas(m)}},chainCallDeletingHdas:function(h){var g=this;this.deleted_lddas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var j=$.when(i.destroy());j.done(function(l){Galaxy.libraries.folderListView.collection.remove(i.id);g.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var k=new d.Item(l);Galaxy.libraries.folderListView.collection.add(k)}g.chainCallDeletingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallDeletingHdas(h)})},showLibInfo:function(){var h=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var g=null;var i=this;if(Galaxy.libraries.libraryListView!==null){g=Galaxy.libraries.libraryListView.collection.get(h);this.showLibInfoModal(g)}else{g=new d.Library({id:h});g.fetch({success:function(){i.showLibInfoModal(g)},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}},showLibInfoModal:function(g){var h=this.templateLibInfoInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Library Information",body:h({library:g}),buttons:{Close:function(){Galaxy.modal.hide()}}})},showImportModal:function(g){switch(g.source){case"history":this.addFilesFromHistoryModal();break;case"importdir":break;case"path":this.importFilesFromPathModal();break;case"userdir":this.importFilesFromUserdirModal();break;default:Galaxy.libraries.library_router.back();f.error("Invalid import source.");break}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push("<% if(mutiple_add_dataset_options) { %>");tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button title="Add Datasets to Current Folder" id="" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-plus"></span><span class="fa fa-file"></span><span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#folders/<%= id %>/import/history"> from History</a></li>');tmpl_array.push("<% if(user_library_import_dir !== null) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/userdir"> from User Directory</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li class="divider"></li>');tmpl_array.push(' <li class="dropdown-header">Admins only</li>');tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/path">from Path</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% } %>");tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push("<% } else { %>");tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push("<% } %>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var g=[];g.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');g.push("Select history: ");g.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</span>");return _.template(g.join(""))},templateImportIntoHistoryProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateAddingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateDeletingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateBrowserModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<div style="margin-bottom:1em;">');g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting files" type="radio" name="jstree-radio" value="jstree-disable-folders" checked="checked"> Files');g.push("</label>");g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting folders" type="radio" name="jstree-radio" value="jstree-disable-files"> Folders');g.push("</label>");g.push('<label class="checkbox-inline jstree-preserve-structure" style="display:none;">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files" style="display:none;">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-files-message">All files you select will be imported into the current folder.</div>');g.push('<div class="alert alert-info jstree-folders-message" style="display:none;">All files within the selected folders and their subfolders will be imported into the current folder.</div>');g.push('<div id="jstree_browser">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateImportPathModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<label class="checkbox-inline jstree-preserve-structure">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>');g.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>');g.push("</div>");return _.template(g.join(""))},templateAddFilesFromHistory:function(){var g=[];g.push('<div id="add_files_modal">');g.push('<div id="history_modal_combo_bulk">');g.push("Select history: ");g.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</div>");g.push("<br/>");g.push('<div id="selected_history_content">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateHistoryContents:function(){var g=[];g.push("<strong>Choose the datasets to import:</strong>");g.push("<ul>");g.push(" <% _.each(history_contents, function(history_item) { %>");g.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');g.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');g.push(" </li>");g.push(" <% }); %>");g.push("</ul>");return _.template(g.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr","libs/jquery/jstree","mvc/library/library-model"],function(c,e,f,b,d){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0},disabled_jstree_element:"folders"},modal:null,jstree:null,histories:null,initialize:function(g){this.options=_.defaults(g||{},this.defaults);this.render()},render:function(g){this.options=_.extend(this.options,g);var i=this.templateToolBar();var h={id:this.options.id,is_admin:false,is_anonym:true,user_library_import_dir:Galaxy.config.user_library_import_dir,allow_library_path_paste:Galaxy.config.allow_library_path_paste,library_import_dir:Galaxy.config.library_import_dir,mutiple_add_dataset_options:false};if(Galaxy.currUser){h.is_admin=Galaxy.currUser.isAdmin();h.is_anonym=Galaxy.currUser.isAnonymous();if(h.user_library_import_dir!==null||h.allow_library_path_paste!==false||h.library_import_dir!==null){h.mutiple_add_dataset_options=true}}this.$el.html(i(h))},configureElements:function(g){this.options=_.extend(this.options,g);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(i){i.preventDefault();i.stopPropagation();var g=this;var h=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:h(),buttons:{Create:function(){g.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var g=this.serialize_new_folder();if(this.validate_new_folder(g)){var h=new d.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];h.url=h.urlRoot+"/"+current_folder_id;h.save(g,{success:function(i){Galaxy.modal.hide();f.success("Folder created");i.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(i)},error:function(j,i){Galaxy.modal.hide();if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}else{f.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(g){return g.name!==""},modalBulkImport:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(i){var h=i.templateBulkImportInModal();i.modal=Galaxy.modal;i.modal.show({closing_events:true,title:"Import into History",body:h({histories:i.histories.models}),buttons:{Import:function(){i.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(h){var g=this;this.histories=new d.GalaxyHistories();this.histories.fetch({success:function(){h(g)},error:function(j,i){if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var k=$("select[name=dataset_import_bulk] option:selected").val();this.options.last_used_history_id=k;var n=$("select[name=dataset_import_bulk] option:selected").text();var p=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){p.push(this.parentElement.parentElement.id)}});var o=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(o({history_name:n}));var l=100/p.length;this.initProgress(l);var g=[];for(var h=p.length-1;h>=0;h--){var j=p[h];var m=new d.HistoryItem();m.url=m.urlRoot+k+"/contents";m.content=j;m.source="library";g.push(m)}this.options.chain_call_control.total_number=g.length;jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+k);this.chainCall(g,n)},chainCall:function(h,k){var g=this;var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return}var j=$.when(i.save({content:i.content,source:i.source}));j.done(function(){g.updateProgress();g.chainCall(h,k)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCall(h,k)})},initProgress:function(g){this.progress=0;this.progressStep=g},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(g,k){var i=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){i.push(this.parentElement.parentElement.id)}});var h="/api/libraries/datasets/download/"+k;var j={ldda_ids:i};this.processDownload(h,j,"get")},processDownload:function(h,i,j){if(h&&i){i=typeof i==="string"?i:$.param(i);var g="";$.each(i.split("&"),function(){var k=this.split("=");g+='<input type="hidden" name="'+k[0]+'" value="'+k[1]+'" />'});$('<form action="'+h+'" method="'+(j||"post")+'">'+g+"</form>").appendTo("body").submit().remove();f.info("Your download will begin soon")}else{f.error("An error occurred :(")}},addFilesFromHistoryModal:function(){this.refreshUserHistoriesList(function(g){g.modal=Galaxy.modal;var h=g.templateAddFilesFromHistory();var i=g.options.full_path[g.options.full_path.length-1][1];g.modal.show({closing_events:true,title:"Adding datasets from your history to folder "+i,body:h({histories:g.histories.models}),buttons:{Add:function(){g.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.back()}});if(g.histories.models.length>0){g.fetchAndDisplayHistoryContents(g.histories.models[0].id);$("#dataset_add_bulk").change(function(j){g.fetchAndDisplayHistoryContents(j.target.value)})}else{f.error("An error ocurred :(")}})},importFilesFromPathModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateImportPathModal();this.modal.show({closing_events:true,title:"Enter paths relative to Galaxy root",body:g({}),buttons:{Import:function(){h.importFromPathsClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}})},importFilesFromUserdirModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateBrowserModal();this.modal.show({closing_events:true,title:"Select folders or files to import",body:g({}),buttons:{Import:function(){h.importFromUserdirClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}});this.renderJstree({disabled_jstree_element:"folders"});$("input[type=radio]").change(function(i){if(i.target.value==="jstree-disable-folders"){h.renderJstree({disabled_jstree_element:"folders"});$(".jstree-folders-message").hide();$(".jstree-preserve-structure").hide();$(".jstree-link-files").hide();$(".jstree-files-message").show()}else{if(i.target.value==="jstree-disable-files"){$(".jstree-files-message").hide();$(".jstree-folders-message").show();$(".jstree-link-files").show();$(".jstree-preserve-structure").show();h.renderJstree({disabled_jstree_element:"files"})}}})},renderJstree:function(g){var i=this;this.options=_.extend(this.options,g);var h=this.options.disabled_jstree_element;this.jstree=new d.Jstree();this.jstree.url=this.jstree.urlRoot+"?target=userdir&format=jstree&disable="+h;this.jstree.fetch({success:function(k,j){$("#jstree_browser").jstree("destroy");var l=$("#jstree_browser").jstree({core:{data:k},plugins:["types","checkbox"],types:{folder:{icon:"jstree-folder"},file:{icon:"jstree-file"}},checkbox:{three_state:false}})},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importFromPathsClicked:function(){var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var l=this.modal.$el.find(".link-checkbox").is(":checked");var k=$("textarea#import_paths").val();if(!k){f.info("Please enter a path relative to Galaxy root")}else{this.modal.disableButton("Import");k=k.split("\n");var j=[];for(var h=k.length-1;h>=0;h--){trimmed=k[h].trim();if(trimmed.length!==0){j.push(trimmed)}}this.initChainCallControl(j.length);this.chainCallImportingFolders(j,g,l,"admin_path")}},initChainCallControl:function(g){var h=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(h({folder_name:this.options.folder_name}));this.progress=0;this.progressStep=100/g;this.options.chain_call_control.total_number=g;this.options.chain_call_control.failed_number=0},importFromUserdirClicked:function(l){var h=$("#jstree_browser").jstree().get_selected(true);var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var o=this.modal.$el.find(".link-checkbox").is(":checked");var n=[];if(h.length<1){f.info("You have to select some items first")}else{this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;for(var j=h.length-1;j>=0;j--){if(h[j].li_attr.full_path!==undefined){n.push(h[j].li_attr.full_path)}}var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/n.length;this.progress=0;this.options.chain_call_control.total_number=n.length;var k=h[0].type;if(k==="folder"){this.chainCallImportingFolders(n,g,o,"userdir_folder")}else{if(k==="file"){this.chainCallImportingUserdirFiles(n)}}}},chainCallImportingUserdirFiles:function(j){var g=this;var h=j.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected files imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var i=$.when($.post("/api/libraries/datasets?encoded_folder_id="+g.id+"&source=userdir_file&path="+h));i.done(function(k){g.updateProgress();g.chainCallImportingUserdirFiles(j)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallImportingUserdirFiles(j)})},chainCallImportingFolders:function(l,g,m,j){var h=this;var i=l.pop();if(typeof i=="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected folders and their contents imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var k=$.when($.post("/api/libraries/datasets?encoded_folder_id="+h.id+"&source="+j+"&path="+i+"&preserve_dirs="+g+"&link_data="+m));k.done(function(n){h.updateProgress();h.chainCallImportingFolders(l,g,m,j)}).fail(function(){h.options.chain_call_control.failed_number+=1;h.updateProgress();h.chainCallImportingFolders(l,g,m,j)})},fetchAndDisplayHistoryContents:function(i){var h=new d.HistoryContents({id:i});var g=this;h.fetch({success:function(k){var j=g.templateHistoryContents();g.histories.get(i).set({contents:k});g.modal.$el.find("#selected_history_content").html(j({history_contents:k.models.reverse()}))},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){var l=this.modal.$el.find("#selected_history_content").find(":checked");if(l.length<1){f.info("You have to select some datasets first")}else{this.modal.disableButton("Add");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];l.each(function(){var i=$(this.parentElement).data("id");if(i){g.push(i)}});var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/g.length;this.progress=0;var k=[];for(var j=g.length-1;j>=0;j--){history_dataset_id=g[j];var h=new d.Item();h.url="/api/folders/"+this.options.id+"/contents";h.set({from_hda_id:history_dataset_id});k.push(h)}this.options.chain_call_control.total_number=k.length;this.chainCallAddingHdas(k)}},chainCallAddingHdas:function(h){var g=this;this.added_hdas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var j=$.when(i.save({from_hda_id:i.get("from_hda_id")}));j.done(function(k){Galaxy.libraries.folderListView.collection.add(k);g.updateProgress();g.chainCallAddingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallAddingHdas(h)})},checkIncludeDeleted:function(g){if(g.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{var k=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:k({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var h=[];g.each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});this.progressStep=100/h.length;this.progress=0;var m=[];for(var j=h.length-1;j>=0;j--){var l=new d.Item({id:h[j]});m.push(l)}this.options.chain_call_control.total_number=h.length;this.chainCallDeletingHdas(m)}},chainCallDeletingHdas:function(h){var g=this;this.deleted_lddas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var j=$.when(i.destroy());j.done(function(l){Galaxy.libraries.folderListView.collection.remove(i.id);g.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var k=new d.Item(l);Galaxy.libraries.folderListView.collection.add(k)}g.chainCallDeletingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallDeletingHdas(h)})},showLibInfo:function(){var h=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var g=null;var i=this;if(Galaxy.libraries.libraryListView!==null){g=Galaxy.libraries.libraryListView.collection.get(h);this.showLibInfoModal(g)}else{g=new d.Library({id:h});g.fetch({success:function(){i.showLibInfoModal(g)},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}},showLibInfoModal:function(g){var h=this.templateLibInfoInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Library Information",body:h({library:g}),buttons:{Close:function(){Galaxy.modal.hide()}}})},showImportModal:function(g){switch(g.source){case"history":this.addFilesFromHistoryModal();break;case"importdir":break;case"path":this.importFilesFromPathModal();break;case"userdir":this.importFilesFromUserdirModal();break;default:Galaxy.libraries.library_router.back();f.error("Invalid import source.");break}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push("<% if(mutiple_add_dataset_options) { %>");tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button title="Add Datasets to Current Folder" id="" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-plus"></span><span class="fa fa-file"></span><span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#folders/<%= id %>/import/history"> from History</a></li>');tmpl_array.push("<% if(user_library_import_dir !== null) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/userdir"> from User Directory</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li class="divider"></li>');tmpl_array.push(' <li class="dropdown-header">Admins only</li>');tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/path">from Path</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% } %>");tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push("<% } else { %>");tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push("<% } %>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var g=[];g.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');g.push("Select history: ");g.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</span>");return _.template(g.join(""))},templateImportIntoHistoryProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateAddingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateDeletingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateBrowserModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<div style="margin-bottom:1em;">');g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting files" type="radio" name="jstree-radio" value="jstree-disable-folders" checked="checked"> Files');g.push("</label>");g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting folders" type="radio" name="jstree-radio" value="jstree-disable-files"> Folders');g.push("</label>");g.push('<label class="checkbox-inline jstree-preserve-structure" style="display:none;">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files" style="display:none;">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-files-message">All files you select will be imported into the current folder.</div>');g.push('<div class="alert alert-info jstree-folders-message" style="display:none;">All files within the selected folders and their subfolders will be imported into the current folder.</div>');g.push('<div id="jstree_browser">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateImportPathModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<label class="checkbox-inline jstree-preserve-structure">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>');g.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>');g.push("</div>");return _.template(g.join(""))},templateAddFilesFromHistory:function(){var g=[];g.push('<div id="add_files_modal">');g.push('<div id="history_modal_combo_bulk">');g.push("Select history: ");g.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</div>");g.push("<br/>");g.push('<div id="selected_history_content">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateHistoryContents:function(){var g=[];g.push("<strong>Choose the datasets to import:</strong>");g.push("<ul>");g.push(" <% _.each(history_contents, function(history_item) { %>");g.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');g.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');g.push(" </li>");g.push(" <% }); %>");g.push("</ul>");return _.template(g.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file diff -r 3497f7509b007b04a4db905daf3509f1f3c76626 -r aec146e3828b16812ca24c5f8651ba3d0d483a6a static/scripts/packed/mvc/library/library-library-view.js --- a/static/scripts/packed/mvc/library/library-library-view.js +++ b/static/scripts/packed/mvc/library/library-library-view.js @@ -1,1 +1,1 @@ -define(["libs/toastr","mvc/library/library-model","mvc/ui/ui-select"],function(d,c,a){var b=Backbone.View.extend({el:"#center",model:null,options:{},events:{"click .toolbtn_save_permissions":"savePermissions"},initialize:function(e){this.options=_.extend(this.options,e);if(this.options.id){this.fetchLibrary()}},fetchLibrary:function(e){this.options=_.extend(this.options,e);this.model=new c.Library({id:this.options.id});var f=this;this.model.fetch({success:function(){if(f.options.show_permissions){f.showPermissions()}else{f.render()}},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg+" Click this to go back.","",{onclick:function(){Galaxy.libraries.library_router.back()}})}else{d.error("An error ocurred :(. Click this to go back.","",{onclick:function(){Galaxy.libraries.library_router.back()}})}}})},render:function(e){$(".tooltip").remove();this.options=_.extend(this.options,e);var f=this.templateLibrary();this.$el.html(f({item:this.model}));$("#center [data-toggle]").tooltip()},shareDataset:function(){d.info("Feature coming soon.")},goBack:function(){Galaxy.libraries.library_router.back()},showPermissions:function(f){this.options=_.extend(this.options,f);$(".tooltip").remove();if(this.options.fetched_permissions!==undefined){if(this.options.fetched_permissions.access_library_role_list.length===0){this.model.set({is_unrestricted:true})}else{this.model.set({is_unrestricted:false})}}var h=false;if(Galaxy.currUser){h=Galaxy.currUser.isAdmin()}var g=this.templateLibraryPermissions();this.$el.html(g({library:this.model,is_admin:h}));var e=this;if(this.options.fetched_permissions===undefined){$.get("/api/libraries/"+e.id+"/permissions?scope=current").done(function(i){e.prepareSelectBoxes({fetched_permissions:i})}).fail(function(){d.error("An error occurred while fetching library permissions. :(")})}else{this.prepareSelectBoxes({})}$("#center [data-toggle]").tooltip();$("#center").css("overflow","auto")},_serializeRoles:function(g){var e=[];for(var f=0;f<g.length;f++){e.push(g[f]+":"+g[f])}return e},prepareSelectBoxes:function(i){this.options=_.extend(this.options,i);var e=this.options.fetched_permissions;var g=this;var f=this._serializeRoles(e.access_library_role_list);var j=this._serializeRoles(e.add_library_item_role_list);var h=this._serializeRoles(e.manage_library_role_list);var k=this._serializeRoles(e.modify_library_role_list);g.accessSelectObject=new a.View(this._createSelectOptions(this,"access_perm",f,true));g.addSelectObject=new a.View(this._createSelectOptions(this,"add_perm",j,false));g.manageSelectObject=new a.View(this._createSelectOptions(this,"manage_perm",h,false));g.modifySelectObject=new a.View(this._createSelectOptions(this,"modify_perm",k,false))},_createSelectOptions:function(f,k,i,e){e=e===true?e:false;var j={minimumInputLength:0,css:k,multiple:true,placeholder:"Click to select a role",container:f.$el.find("#"+k),ajax:{url:"/api/libraries/"+f.id+"/permissions?scope=available&is_library_access="+e,dataType:"json",quietMillis:100,data:function(l,m){return{q:l,page_limit:10,page:m}},results:function(n,m){var l=(m*10)<n.total;return{results:n.roles,more:l}}},formatResult:function g(l){return l.name+" type: "+l.type},formatSelection:function h(l){return l.name},initSelection:function(l,n){var m=[];$(l.val().split(",")).each(function(){var o=this.split(":");m.push({id:o[1],name:o[1]})});n(m)},initialData:i.join(","),dropdownCssClass:"bigdrop"};return j},comingSoon:function(){d.warning("Feature coming soon")},copyToClipboard:function(){var e=Backbone.history.location.href;if(e.lastIndexOf("/permissions")!==-1){e=e.substr(0,e.lastIndexOf("/permissions"))}window.prompt("Copy to clipboard: Ctrl+C, Enter",e)},makeDatasetPrivate:function(){var e=this;$.post("/api/libraries/datasets/"+e.id+"/permissions?action=make_private").done(function(f){e.model.set({is_unrestricted:false});e.showPermissions({fetched_permissions:f});d.success("The dataset is now private to you")}).fail(function(){d.error("An error occurred while making dataset private :(")})},removeDatasetRestrictions:function(){var e=this;$.post("/api/libraries/datasets/"+e.id+"/permissions?action=remove_restrictions").done(function(f){e.model.set({is_unrestricted:true});e.showPermissions({fetched_permissions:f});d.success("Access to this dataset is now unrestricted")}).fail(function(){d.error("An error occurred while making dataset unrestricted :(")})},_extractIds:function(e){ids_list=[];for(var f=e.length-1;f>=0;f--){ids_list.push(e[f].id)}return ids_list},savePermissions:function(h){var g=this;var i=this._extractIds(this.accessSelectObject.$el.select2("data"));var e=this._extractIds(this.addSelectObject.$el.select2("data"));var j=this._extractIds(this.manageSelectObject.$el.select2("data"));var f=this._extractIds(this.modifySelectObject.$el.select2("data"));$.post("/api/libraries/"+g.id+"/permissions?action=set_permissions",{"access_ids[]":i,"add_ids[]":e,"manage_ids[]":j,"modify_ids[]":f,}).done(function(k){g.showPermissions({fetched_permissions:k});d.success("Permissions saved")}).fail(function(){d.error("An error occurred while setting library permissions :(")})},templateLibrary:function(){var e=[];e.push('<div class="library_style_container">');e.push(' <div id="library_toolbar">');e.push(' <button data-toggle="tooltip" data-placement="top" title="Modify library item" class="btn btn-default toolbtn_modify_dataset primary-button" type="button"><span class="fa fa-pencil"></span> Modify</span></button>');e.push(' <a href="#folders/<%- item.get("folder_id") %>/datasets/<%- item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" title="Manage permissions" class="btn btn-default toolbtn_change_permissions primary-button" type="button"><span class="fa fa-group"></span> Permissions</span></button></a>');e.push(' <button data-toggle="tooltip" data-placement="top" title="Share dataset" class="btn btn-default toolbtn-share-dataset primary-button" type="button"><span class="fa fa-share"></span> Share</span></button>');e.push(" </div>");e.push(" <p>");e.push(" This dataset is unrestricted so everybody can access it. Just share the URL of this page. ");e.push(' <button data-toggle="tooltip" data-placement="top" title="Copy to clipboard" class="btn btn-default btn-copy-link-to-clipboard primary-button" type="button"><span class="fa fa-clipboard"></span> To Clipboard</span></button> ');e.push(" </p>");e.push('<div class="dataset_table">');e.push(' <table class="grid table table-striped table-condensed">');e.push(" <tr>");e.push(' <th scope="row" id="id_row" data-id="<%= _.escape(item.get("ldda_id")) %>">Name</th>');e.push(' <td><%= _.escape(item.get("name")) %></td>');e.push(" </tr>");e.push(' <% if (item.get("file_ext")) { %>');e.push(" <tr>");e.push(' <th scope="row">Data type</th>');e.push(' <td><%= _.escape(item.get("file_ext")) %></td>');e.push(" </tr>");e.push(" <% } %>");e.push(" </table>");e.push("</div>");e.push("</div>");return _.template(e.join(""))},templateLibraryPermissions:function(){var e=[];e.push('<div class="library_style_container">');e.push(' <div id="library_toolbar">');e.push(' <a href="#"><button data-toggle="tooltip" data-placement="top" title="Go back to the list of Libraries" class="btn btn-default primary-button" type="button"><span class="fa fa-list"></span> Libraries</span></button></a>');e.push(" </div>");e.push('<h1>Library: <%= _.escape(library.get("name")) %></h1>');e.push('<div class="alert alert-warning">');e.push("<% if (is_admin) { %>");e.push("You are logged in as an <strong>administrator</strong> therefore you can manage any library on this Galaxy instance. Please make sure you understand the consequences.");e.push("<% } else { %>");e.push("You can assign any number of roles to any of the following permission types. However please read carefully the implications of such actions.");e.push("<% }%>");e.push("</div>");e.push('<div class="dataset_table">');e.push("<h2>Library permissions</h2>");e.push("<h4>Roles that can access the library</h4>");e.push('<div id="access_perm" class="access_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can access this library. If there are no access roles set on the library it is considered <strong>unrestricted</strong>.</div>');e.push("<h4>Roles that can manage permissions on this library</h4>");e.push('<div id="manage_perm" class="manage_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can manage permissions on this library (includes giving access).</div>');e.push("<h4>Roles that can add items to this library</h4>");e.push('<div id="add_perm" class="add_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can add items to this library (folders and datasets).</div>');e.push("<h4>Roles that can modify this library</h4>");e.push('<div id="modify_perm" class="modify_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can modify this library (name, synopsis, etc.).</div>');e.push('<button data-toggle="tooltip" data-placement="top" title="Save modifications made on this page" class="btn btn-default toolbtn_save_permissions primary-button" type="button"><span class="fa fa-floppy-o"></span> Save</span></button>');e.push("</div>");e.push("</div>");return _.template(e.join(""))}});return{LibraryView:b}}); \ No newline at end of file +define(["libs/toastr","mvc/library/library-model","mvc/ui/ui-select"],function(d,c,a){var b=Backbone.View.extend({el:"#center",model:null,options:{},events:{"click .toolbtn_save_permissions":"savePermissions"},initialize:function(e){this.options=_.extend(this.options,e);if(this.options.id){this.fetchLibrary()}},fetchLibrary:function(e){this.options=_.extend(this.options,e);this.model=new c.Library({id:this.options.id});var f=this;this.model.fetch({success:function(){if(f.options.show_permissions){f.showPermissions()}else{f.render()}},error:function(h,g){if(typeof g.responseJSON!=="undefined"){d.error(g.responseJSON.err_msg+" Click this to go back.","",{onclick:function(){Galaxy.libraries.library_router.back()}})}else{d.error("An error ocurred :(. Click this to go back.","",{onclick:function(){Galaxy.libraries.library_router.back()}})}}})},render:function(e){$(".tooltip").remove();this.options=_.extend(this.options,e);var f=this.templateLibrary();this.$el.html(f({item:this.model}));$("#center [data-toggle]").tooltip()},shareDataset:function(){d.info("Feature coming soon.")},goBack:function(){Galaxy.libraries.library_router.back()},showPermissions:function(f){this.options=_.extend(this.options,f);$(".tooltip").remove();if(this.options.fetched_permissions!==undefined){if(this.options.fetched_permissions.access_library_role_list.length===0){this.model.set({is_unrestricted:true})}else{this.model.set({is_unrestricted:false})}}var h=false;if(Galaxy.currUser){h=Galaxy.currUser.isAdmin()}var g=this.templateLibraryPermissions();this.$el.html(g({library:this.model,is_admin:h}));var e=this;if(this.options.fetched_permissions===undefined){$.get("/api/libraries/"+e.id+"/permissions?scope=current").done(function(i){e.prepareSelectBoxes({fetched_permissions:i})}).fail(function(){d.error("An error occurred while fetching library permissions. :(")})}else{this.prepareSelectBoxes({})}$("#center [data-toggle]").tooltip();$("#center").css("overflow","auto")},_serializeRoles:function(g){var e=[];for(var f=0;f<g.length;f++){e.push(g[f][1]+":"+g[f][0])}return e},prepareSelectBoxes:function(i){this.options=_.extend(this.options,i);var e=this.options.fetched_permissions;var g=this;var f=this._serializeRoles(e.access_library_role_list);var j=this._serializeRoles(e.add_library_item_role_list);var h=this._serializeRoles(e.manage_library_role_list);var k=this._serializeRoles(e.modify_library_role_list);g.accessSelectObject=new a.View(this._createSelectOptions(this,"access_perm",f,true));g.addSelectObject=new a.View(this._createSelectOptions(this,"add_perm",j,false));g.manageSelectObject=new a.View(this._createSelectOptions(this,"manage_perm",h,false));g.modifySelectObject=new a.View(this._createSelectOptions(this,"modify_perm",k,false))},_createSelectOptions:function(f,k,i,e){e=e===true?e:false;var j={minimumInputLength:0,css:k,multiple:true,placeholder:"Click to select a role",container:f.$el.find("#"+k),ajax:{url:"/api/libraries/"+f.id+"/permissions?scope=available&is_library_access="+e,dataType:"json",quietMillis:100,data:function(l,m){return{q:l,page_limit:10,page:m}},results:function(n,m){var l=(m*10)<n.total;return{results:n.roles,more:l}}},formatResult:function g(l){return l.name+" type: "+l.type},formatSelection:function h(l){return l.name},initSelection:function(l,n){var m=[];$(l.val().split(",")).each(function(){var o=this.split(":");m.push({id:o[0],name:o[1]})});n(m)},initialData:i,dropdownCssClass:"bigdrop"};return j},comingSoon:function(){d.warning("Feature coming soon")},copyToClipboard:function(){var e=Backbone.history.location.href;if(e.lastIndexOf("/permissions")!==-1){e=e.substr(0,e.lastIndexOf("/permissions"))}window.prompt("Copy to clipboard: Ctrl+C, Enter",e)},makeDatasetPrivate:function(){var e=this;$.post("/api/libraries/datasets/"+e.id+"/permissions?action=make_private").done(function(f){e.model.set({is_unrestricted:false});e.showPermissions({fetched_permissions:f});d.success("The dataset is now private to you")}).fail(function(){d.error("An error occurred while making dataset private :(")})},removeDatasetRestrictions:function(){var e=this;$.post("/api/libraries/datasets/"+e.id+"/permissions?action=remove_restrictions").done(function(f){e.model.set({is_unrestricted:true});e.showPermissions({fetched_permissions:f});d.success("Access to this dataset is now unrestricted")}).fail(function(){d.error("An error occurred while making dataset unrestricted :(")})},_extractIds:function(e){ids_list=[];for(var f=e.length-1;f>=0;f--){ids_list.push(e[f].id)}return ids_list},savePermissions:function(h){var g=this;var i=this._extractIds(this.accessSelectObject.$el.select2("data"));var e=this._extractIds(this.addSelectObject.$el.select2("data"));var j=this._extractIds(this.manageSelectObject.$el.select2("data"));var f=this._extractIds(this.modifySelectObject.$el.select2("data"));$.post("/api/libraries/"+g.id+"/permissions?action=set_permissions",{"access_ids[]":i,"add_ids[]":e,"manage_ids[]":j,"modify_ids[]":f,}).done(function(k){g.showPermissions({fetched_permissions:k});d.success("Permissions saved")}).fail(function(){d.error("An error occurred while setting library permissions :(")})},templateLibrary:function(){var e=[];e.push('<div class="library_style_container">');e.push(' <div id="library_toolbar">');e.push(' <button data-toggle="tooltip" data-placement="top" title="Modify library item" class="btn btn-default toolbtn_modify_dataset primary-button" type="button"><span class="fa fa-pencil"></span> Modify</span></button>');e.push(' <a href="#folders/<%- item.get("folder_id") %>/datasets/<%- item.id %>/permissions"><button data-toggle="tooltip" data-placement="top" title="Manage permissions" class="btn btn-default toolbtn_change_permissions primary-button" type="button"><span class="fa fa-group"></span> Permissions</span></button></a>');e.push(' <button data-toggle="tooltip" data-placement="top" title="Share dataset" class="btn btn-default toolbtn-share-dataset primary-button" type="button"><span class="fa fa-share"></span> Share</span></button>');e.push(" </div>");e.push(" <p>");e.push(" This dataset is unrestricted so everybody can access it. Just share the URL of this page. ");e.push(' <button data-toggle="tooltip" data-placement="top" title="Copy to clipboard" class="btn btn-default btn-copy-link-to-clipboard primary-button" type="button"><span class="fa fa-clipboard"></span> To Clipboard</span></button> ');e.push(" </p>");e.push('<div class="dataset_table">');e.push(' <table class="grid table table-striped table-condensed">');e.push(" <tr>");e.push(' <th scope="row" id="id_row" data-id="<%= _.escape(item.get("ldda_id")) %>">Name</th>');e.push(' <td><%= _.escape(item.get("name")) %></td>');e.push(" </tr>");e.push(' <% if (item.get("file_ext")) { %>');e.push(" <tr>");e.push(' <th scope="row">Data type</th>');e.push(' <td><%= _.escape(item.get("file_ext")) %></td>');e.push(" </tr>");e.push(" <% } %>");e.push(" </table>");e.push("</div>");e.push("</div>");return _.template(e.join(""))},templateLibraryPermissions:function(){var e=[];e.push('<div class="library_style_container">');e.push(' <div id="library_toolbar">');e.push(' <a href="#"><button data-toggle="tooltip" data-placement="top" title="Go back to the list of Libraries" class="btn btn-default primary-button" type="button"><span class="fa fa-list"></span> Libraries</span></button></a>');e.push(" </div>");e.push('<h1>Library: <%= _.escape(library.get("name")) %></h1>');e.push('<div class="alert alert-warning">');e.push("<% if (is_admin) { %>");e.push("You are logged in as an <strong>administrator</strong> therefore you can manage any library on this Galaxy instance. Please make sure you understand the consequences.");e.push("<% } else { %>");e.push("You can assign any number of roles to any of the following permission types. However please read carefully the implications of such actions.");e.push("<% }%>");e.push("</div>");e.push('<div class="dataset_table">');e.push("<h2>Library permissions</h2>");e.push("<h4>Roles that can access the library</h4>");e.push('<div id="access_perm" class="access_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can access this library. If there are no access roles set on the library it is considered <strong>unrestricted</strong>.</div>');e.push("<h4>Roles that can manage permissions on this library</h4>");e.push('<div id="manage_perm" class="manage_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can manage permissions on this library (includes giving access).</div>');e.push("<h4>Roles that can add items to this library</h4>");e.push('<div id="add_perm" class="add_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can add items to this library (folders and datasets).</div>');e.push("<h4>Roles that can modify this library</h4>");e.push('<div id="modify_perm" class="modify_perm roles-selection"></div>');e.push('<div class="alert alert-info roles-selection">User with <strong>any</strong> of these roles can modify this library (name, synopsis, etc.).</div>');e.push('<button data-toggle="tooltip" data-placement="top" title="Save modifications made on this page" class="btn btn-default toolbtn_save_permissions primary-button" type="button"><span class="fa fa-floppy-o"></span> Save</span></button>');e.push("</div>");e.push("</div>");return _.template(e.join(""))}});return{LibraryView:b}}); \ No newline at end of file https://bitbucket.org/galaxy/galaxy-central/commits/f163dd7c2ccd/ Changeset: f163dd7c2ccd User: martenson Date: 2014-09-16 22:02:12+00:00 Summary: jstree refactoring, removed from global space, documentation to library imports, general JS cleanup Affected #: 7 files diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 client/galaxy/scripts/libs/jquery/jstree.js --- a/client/galaxy/scripts/libs/jquery/jstree.js +++ b/client/galaxy/scripts/libs/jquery/jstree.js @@ -2,7 +2,7 @@ (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { - // define(['jquery'], factory); + define(['jquery'], factory); } else if(typeof exports === 'object') { factory(require('jquery')); diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js --- a/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js +++ b/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js @@ -2,13 +2,11 @@ "galaxy.masthead", "utils/utils", "libs/toastr", - "libs/jquery/jstree", "mvc/library/library-model"], -function(mod_masthead, +function( mod_masthead, mod_utils, mod_toastr, - ignore_jstree, - mod_library_model) { + mod_library_model ) { var FolderToolbarView = Backbone.View.extend({ el: '#center', @@ -40,7 +38,7 @@ histories : null, initialize: function(options){ - this.options = _.defaults(options || {}, this.defaults); + this.options = _.defaults( options || {}, this.defaults ); this.render(); }, @@ -202,89 +200,42 @@ * Import all selected datasets into history. */ importAllIntoHistory : function (){ - this.modal.disableButton('Import'); - - // init the control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - var history_id = $("select[name=dataset_import_bulk] option:selected").val(); - // we can save last used history to pre-select it next time - this.options.last_used_history_id = history_id; - var history_name = $("select[name=dataset_import_bulk] option:selected").text(); - - var dataset_ids = []; - $('#folder_table').find(':checked').each(function(){ - if (this.parentElement.parentElement.id !== '') { - dataset_ids.push(this.parentElement.parentElement.id); - } - }); - var progress_bar_tmpl = this.templateImportIntoHistoryProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ history_name : history_name })); - - // init the progress bar - var progressStep = 100 / dataset_ids.length; - this.initProgress(progressStep); - - // prepare the dataset objects to be imported - var datasets_to_import = []; - for (var i = dataset_ids.length - 1; i >= 0; i--) { - var library_dataset_id = dataset_ids[i]; - var historyItem = new mod_library_model.HistoryItem(); - historyItem.url = historyItem.urlRoot + history_id + '/contents'; - historyItem.content = library_dataset_id; - historyItem.source = 'library'; - datasets_to_import.push(historyItem); - } - this.options.chain_call_control.total_number = datasets_to_import.length; - - // set the used history as current so user will see the last one - // that he imported into in the history panel on the 'analysis' page - jQuery.getJSON( galaxy_config.root + 'history/set_as_current?id=' + history_id ); - - // call the recursive function to call ajax one after each other (request FIFO queue) - this.chainCall(datasets_to_import, history_name); + this.modal.disableButton('Import'); + var history_id = $("select[name=dataset_import_bulk] option:selected").val(); + var history_name = $("select[name=dataset_import_bulk] option:selected").text(); + // we can save last used history to pre-select it next time + this.options.last_used_history_id = history_id; + var dataset_ids = []; + $('#folder_table').find(':checked').each(function(){ + if (this.parentElement.parentElement.id !== '') { + dataset_ids.push(this.parentElement.parentElement.id); + } + }); + // prepare the dataset objects to be imported + var datasets_to_import = []; + for (var i = dataset_ids.length - 1; i >= 0; i--) { + var library_dataset_id = dataset_ids[i]; + var historyItem = new mod_library_model.HistoryItem(); + historyItem.url = historyItem.urlRoot + history_id + '/contents'; + historyItem.content = library_dataset_id; + historyItem.source = 'library'; + datasets_to_import.push(historyItem); + } + this.initChainCallControl( { length: datasets_to_import.length, action: 'to_history', history_name: history_name } ); + // set the used history as current so user will see the last one + // that he imported into in the history panel on the 'analysis' page + jQuery.getJSON( galaxy_config.root + 'history/set_as_current?id=' + history_id ); + this.chainCallImportingIntoHistory( datasets_to_import, history_name ); }, - chainCall: function(history_item_set, history_name){ - var self = this; - var popped_item = history_item_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets imported into history. Click this to start analysing it.', '', {onclick: function() {window.location='/'}}); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were imported into history.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be imported into history. Click this to see what was imported.', '', {onclick: function() {window.location='/'}}); - } - Galaxy.modal.hide(); - return; - } - var promise = $.when(popped_item.save({content: popped_item.content, source: popped_item.source})); - - promise.done(function(){ - // we are fine - self.updateProgress(); - self.chainCall(history_item_set, history_name); - }) - .fail(function(){ - // we have a problem - self.options.chain_call_control.failed_number += 1; - self.updateProgress(); - self.chainCall(history_item_set, history_name); - }); - }, - - initProgress: function(progressStep){ - this.progress = 0; - this.progressStep = progressStep; - }, - + /** + * Update the progress bar in modal window. + */ updateProgress: function(){ this.progress += this.progressStep; - $('.progress-bar-import').width(Math.round(this.progress) + '%'); - txt_representation = Math.round(this.progress) + '% Complete'; - $('.completion_span').text(txt_representation); + $( '.progress-bar-import' ).width( Math.round( this.progress ) + '%' ); + txt_representation = Math.round( this.progress ) + '% Complete'; + $( '.completion_span' ).text( txt_representation ); }, /** @@ -292,16 +243,16 @@ * @param {str} folder_id id of the current folder * @param {str} format requested archive format */ - download : function(folder_id, format){ + download : function( folder_id, format ){ var dataset_ids = []; - $('#folder_table').find(':checked').each(function(){ - if (this.parentElement.parentElement.id !== '') { - dataset_ids.push(this.parentElement.parentElement.id); + $( '#folder_table' ).find( ':checked' ).each( function(){ + if ( this.parentElement.parentElement.id !== '' ) { + dataset_ids.push( this.parentElement.parentElement.id ); } - }); + } ); var url = '/api/libraries/datasets/download/' + format; - var data = {'ldda_ids' : dataset_ids}; - this.processDownload(url, data, 'get'); + var data = { 'ldda_ids' : dataset_ids }; + this.processDownload( url, data, 'get' ); }, /** @@ -311,27 +262,27 @@ * @param {obj} data data to include in the request * @param {str} method method of the request */ - processDownload: function(url, data, method){ + processDownload: function( url, data, method ){ if ( url && data ){ // data can be string of parameters or array/object - data = typeof data === 'string' ? data : $.param(data); + data = typeof data === 'string' ? data : $.param( data ); // split params into form inputs var inputs = ''; - $.each(data.split('&'), function(){ - var pair = this.split('='); + $.each( data.split( '&' ), function(){ + var pair = this.split( '=' ); inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; }); // send request $('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>') - .appendTo('body').submit().remove(); - mod_toastr.info('Your download will begin soon'); + .appendTo( 'body' ).submit().remove(); + mod_toastr.info( 'Your download will begin soon' ); } else { - mod_toastr.error('An error occurred :('); + mod_toastr.error( 'An error occurred :(' ); } }, addFilesFromHistoryModal: function(){ - this.refreshUserHistoriesList(function(self){ + this.refreshUserHistoriesList( function( self ){ self.modal = Galaxy.modal; var template_modal = self.templateAddFilesFromHistory(); var folder_name = self.options.full_path[self.options.full_path.length - 1][1] @@ -355,7 +306,7 @@ self.fetchAndDisplayHistoryContents(event.target.value); }); } else { - mod_toastr.error('An error ocurred :('); + mod_toastr.error( 'An error ocurred :(' ); } }); }, @@ -438,23 +389,28 @@ this.jstree.url = this.jstree.urlRoot + '?target=userdir&format=jstree&disable=' + disabled_jstree_element; this.jstree.fetch({ success: function(model, response){ - $('#jstree_browser').jstree("destroy"); - var jstreeObject = $('#jstree_browser').jstree({ - 'core':{ - 'data': model - }, - 'plugins': ['types', 'checkbox'], - 'types': { - "folder": { - "icon": "jstree-folder" + // This is to prevent double jquery load. I think. Carl is magician. + define( 'jquery', function(){ return jQuery; }); + // Now we need jstree, time to lazy load it. + require([ 'libs/jquery/jstree' ], function(jstree){ + $('#jstree_browser').jstree("destroy"); + $('#jstree_browser').jstree({ + 'core':{ + 'data': model }, - "file": { - "icon": "jstree-file" + 'plugins': ['types', 'checkbox'], + 'types': { + "folder": { + "icon": "jstree-folder" + }, + "file": { + "icon": "jstree-file" + } + }, + 'checkbox': { + three_state: false } - }, - 'checkbox': { - three_state: false - } + }); }); }, error: function(model, response){ @@ -476,19 +432,19 @@ var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); var paths = $('textarea#import_paths').val(); + var valid_paths = []; if (!paths){ mod_toastr.info('Please enter a path relative to Galaxy root'); } else { this.modal.disableButton('Import'); paths = paths.split('\n'); - var valid_paths = []; for (var i = paths.length - 1; i >= 0; i--) { trimmed = paths[i].trim(); if (trimmed.length!==0){ valid_paths.push(trimmed); } }; - this.initChainCallControl(valid_paths.length); + this.initChainCallControl( { length: valid_paths.length, action: 'adding_datasets' } ); this.chainCallImportingFolders(valid_paths, preserve_dirs, link_data, 'admin_path'); } }, @@ -496,87 +452,178 @@ /** * Initialize the control of chaining requests * in the current modal. + * @param {int} length The number of items in the chain call. */ - initChainCallControl: function(length){ - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); + initChainCallControl: function( options ){ + var template; + switch( options.action ){ + case "adding_datasets": + template = this.templateAddingDatasetsProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template( { folder_name : this.options.folder_name } ) ); + break; + case "deleting_datasets": + template = this.templateDeletingDatasetsProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template() ); + break; + case "to_history": + template = this.templateImportIntoHistoryProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template( { history_name : options.history_name } ) ); + break; + default: + console.error( 'Wrong action specified.') + break; + } + + // var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); + // this.modal.$el.find( '.modal-body' ).html( progress_bar_tmpl( { folder_name : this.options.folder_name } ) ); this.progress = 0; - this.progressStep = 100 / length; - this.options.chain_call_control.total_number = length; + this.progressStep = 100 / options.length; + this.options.chain_call_control.total_number = options.length; this.options.chain_call_control.failed_number = 0; }, /** * Take the selected items from the jstree, create a request queue * and send them one by one to the server for importing into - * the current folder. + * the current folder. + * + * jstree.js has to be loaded before + * @see renderJstree */ - importFromUserdirClicked: function (that){ - var selected_nodes = $('#jstree_browser').jstree().get_selected(true); - var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); - var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); + importFromUserdirClicked: function ( that ){ + var selected_nodes = $( '#jstree_browser' ).jstree().get_selected( true ); + var preserve_dirs = this.modal.$el.find( '.preserve-checkbox' ).is( ':checked' ); + var link_data = this.modal.$el.find( '.link-checkbox' ).is( ':checked' ); + var selection_type = selected_nodes[0].type; var paths = []; - if (selected_nodes.length < 1){ - mod_toastr.info('You have to select some items first'); + if ( selected_nodes.length < 1 ){ + mod_toastr.info( 'You have to select some items first' ); } else { - // disable the button to prevent multiple submission - this.modal.disableButton('Import'); - // init the chain control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - for (var i = selected_nodes.length - 1; i >= 0; i--){ - if(selected_nodes[i].li_attr.full_path !== undefined){ - paths.push(selected_nodes[i].li_attr.full_path); + this.modal.disableButton( 'Import' ); + for ( var i = selected_nodes.length - 1; i >= 0; i-- ){ + if ( selected_nodes[i].li_attr.full_path !== undefined ){ + paths.push( selected_nodes[i].li_attr.full_path ); } } - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); - - // init the progress bar - this.progressStep = 100 / paths.length; - this.progress = 0; - this.options.chain_call_control.total_number = paths.length; - - var selection_type = selected_nodes[0].type; - // call the recursive function to call ajax one after each other (request FIFO queue) - if (selection_type === 'folder'){ - this.chainCallImportingFolders(paths, preserve_dirs, link_data, 'userdir_folder'); - } else if (selection_type === 'file'){ - this.chainCallImportingUserdirFiles(paths); + this.initChainCallControl( { length: paths.length, action: 'adding_datasets' } ); + if ( selection_type === 'folder' ){ + this.chainCallImportingFolders( paths, preserve_dirs, link_data, 'userdir_folder' ); + } else if ( selection_type === 'file' ){ + this.chainCallImportingUserdirFiles( paths ); } } }, + fetchAndDisplayHistoryContents: function(history_id){ + var history_contents = new mod_library_model.HistoryContents({id:history_id}); + var self = this; + history_contents.fetch({ + success: function(history_contents){ + var history_contents_template = self.templateHistoryContents(); + self.histories.get(history_id).set({'contents' : history_contents}); + self.modal.$el.find('#selected_history_content').html(history_contents_template({history_contents: history_contents.models.reverse()})); + }, + error: function(model, response){ + if (typeof response.responseJSON !== "undefined"){ + mod_toastr.error(response.responseJSON.err_msg); + } else { + mod_toastr.error('An error ocurred :('); + } + } + }); + }, + + /** + * Import all selected datasets from history into the current folder. + */ + addAllDatasetsFromHistory : function (){ + var checked_hdas = this.modal.$el.find( '#selected_history_content' ).find( ':checked' ); + var history_dataset_ids = []; + var hdas_to_add = []; + if ( checked_hdas.length < 1 ){ + mod_toastr.info( 'You have to select some datasets first' ); + } else { + this.modal.disableButton( 'Add' ); + checked_hdas.each(function(){ + var hid = $( this.parentElement ).data( 'id' ); + if ( hid ) { + history_dataset_ids.push( hid ); + } + }); + for ( var i = history_dataset_ids.length - 1; i >= 0; i-- ) { + history_dataset_id = history_dataset_ids[i]; + var folder_item = new mod_library_model.Item(); + folder_item.url = '/api/folders/' + this.options.id + '/contents'; + folder_item.set( { 'from_hda_id':history_dataset_id } ); + hdas_to_add.push( folder_item ); + } + this.initChainCallControl( { length: hdas_to_add.length, action: 'adding_datasets' } ); + this.chainCallAddingHdas( hdas_to_add ); + } + }, + + /** + * Take array of empty history items and make request for each of them + * to create it on server. Update progress in between calls. + * @param {array} history_item_set array of empty history items + * @param {str} history_name name of the history to import to + */ + chainCallImportingIntoHistory: function( history_item_set, history_name ){ + var self = this; + var popped_item = history_item_set.pop(); + if ( typeof popped_item == "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets imported into history. Click this to start analysing it.', '', { onclick: function() { window.location='/' } } ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were imported into history.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be imported into history. Click this to see what was imported.', '', { onclick: function() { window.location='/' } } ); + } + Galaxy.modal.hide(); + return true; + } + var promise = $.when( popped_item.save( { content: popped_item.content, source: popped_item.source } ) ); + + promise.done( function(){ + self.updateProgress(); + self.chainCallImportingIntoHistory( history_item_set, history_name ); + } ) + .fail( function(){ + self.options.chain_call_control.failed_number += 1; + self.updateProgress(); + self.chainCallImportingIntoHistory( history_item_set, history_name ); + } ); + }, + /** * Take the array of paths and createa request for each of them * calling them in chain. Update the progress bar in between each. * @param {array} paths paths relative to user folder on Galaxy */ - chainCallImportingUserdirFiles: function(paths){ + chainCallImportingUserdirFiles: function( paths ){ var that = this; var popped_item = paths.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected files imported into the current folder'); + if ( typeof popped_item === "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected files imported into the current folder' ); Galaxy.modal.hide(); } else { - mod_toastr.error('Something went wrong :('); + mod_toastr.error( 'Something went wrong :(' ); } return true; } - var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + + var promise = $.when( $.post( '/api/libraries/datasets?encoded_folder_id=' + that.id + '&source=userdir_file' + - '&path=' + popped_item)) - promise.done(function(response){ + '&path=' + popped_item ) ) + promise.done( function( response ){ that.updateProgress(); - that.chainCallImportingUserdirFiles(paths); - }) - .fail(function(){ + that.chainCallImportingUserdirFiles( paths ); + } ) + .fail( function(){ that.options.chain_call_control.failed_number += 1; that.updateProgress(); - that.chainCallImportingUserdirFiles(paths); - }); + that.chainCallImportingUserdirFiles( paths ); + } ); }, /** @@ -618,98 +665,80 @@ }); }, - fetchAndDisplayHistoryContents: function(history_id){ - var history_contents = new mod_library_model.HistoryContents({id:history_id}); - var self = this; - history_contents.fetch({ - success: function(history_contents){ - var history_contents_template = self.templateHistoryContents(); - self.histories.get(history_id).set({'contents' : history_contents}); - self.modal.$el.find('#selected_history_content').html(history_contents_template({history_contents: history_contents.models.reverse()})); - }, - error: function(model, response){ - if (typeof response.responseJSON !== "undefined"){ - mod_toastr.error(response.responseJSON.err_msg); - } else { - mod_toastr.error('An error ocurred :('); - } - } - }); - }, - - // add all selected datasets from history into current folder - addAllDatasetsFromHistory : function (){ - var checked_hdas = this.modal.$el.find('#selected_history_content').find(':checked'); - if (checked_hdas.length < 1){ - mod_toastr.info('You have to select some datasets first'); - } else { - // disable the button to prevent multiple submission - this.modal.disableButton('Add'); - // init the control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - var history_dataset_ids = []; - checked_hdas.each(function(){ - var hid = $(this.parentElement).data('id'); - if (hid) { - history_dataset_ids.push(hid); - } - }); - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); - - // init the progress bar - this.progressStep = 100 / history_dataset_ids.length; - this.progress = 0; - - // prepare the dataset items to be added - var hdas_to_add = []; - for (var i = history_dataset_ids.length - 1; i >= 0; i--) { - history_dataset_id = history_dataset_ids[i]; - var folder_item = new mod_library_model.Item(); - folder_item.url = '/api/folders/' + this.options.id + '/contents'; - folder_item.set({'from_hda_id':history_dataset_id}); - hdas_to_add.push(folder_item); - } - this.options.chain_call_control.total_number = hdas_to_add.length; - // call the recursive function to call ajax one after each other (request FIFO queue) - this.chainCallAddingHdas(hdas_to_add); - } - }, - - chainCallAddingHdas: function(hdas_set){ + /** + * Take the array of hdas and create a request for each. + * Call them in chain and update progress bar in between each. + * @param {array} hdas_set array of empty hda objects + */ + chainCallAddingHdas: function( hdas_set ){ var self = this; this.added_hdas = new mod_library_model.Folder(); var popped_item = hdas_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets from history added to the folder'); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were added to the folder.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be added to the folder'); + if ( typeof popped_item == "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets from history added to the folder' ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were added to the folder.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be added to the folder' ); } Galaxy.modal.hide(); return this.added_hdas; } - var promise = $.when(popped_item.save({from_hda_id: popped_item.get('from_hda_id')})); + var promise = $.when( popped_item.save( { from_hda_id: popped_item.get( 'from_hda_id' ) } ) ); - promise.done(function(model){ - // we are fine - Galaxy.libraries.folderListView.collection.add(model); + promise.done( function( model ){ + Galaxy.libraries.folderListView.collection.add( model ); self.updateProgress(); - self.chainCallAddingHdas(hdas_set); + self.chainCallAddingHdas( hdas_set ); }) - .fail(function(){ - // we have a problem + .fail( function(){ self.options.chain_call_control.failed_number += 1; self.updateProgress(); - self.chainCallAddingHdas(hdas_set); + self.chainCallAddingHdas( hdas_set ); }); }, /** + * Take the array of lddas, create request for each and + * call them in chain. Update progress bar in between each. + * @param {array} lddas_set array of lddas to delete + */ + chainCallDeletingHdas: function( lddas_set ){ + var self = this; + this.deleted_lddas = new mod_library_model.Folder(); + var popped_item = lddas_set.pop(); + if ( typeof popped_item === "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets deleted' ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were deleted.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be deleted' ); + } + Galaxy.modal.hide(); + return this.deleted_lddas; + } + var promise = $.when( popped_item.destroy() ); + + promise.done( function( dataset ){ + Galaxy.libraries.folderListView.collection.remove( popped_item.id ); + self.updateProgress(); + // add the deleted dataset to collection, triggers rendering + if ( Galaxy.libraries.folderListView.options.include_deleted ){ + var updated_dataset = new mod_library_model.Item( dataset ); + Galaxy.libraries.folderListView.collection.add( updated_dataset ); + } + self.chainCallDeletingHdas( lddas_set ); + }) + .fail( function(){ + self.options.chain_call_control.failed_number += 1; + self.updateProgress(); + self.chainCallDeletingHdas( lddas_set ); + }); + }, + + /** * Handles the click on 'show deleted' checkbox */ checkIncludeDeleted: function(event){ @@ -765,43 +794,6 @@ } }, - chainCallDeletingHdas: function(lddas_set){ - var self = this; - this.deleted_lddas = new mod_library_model.Folder(); - var popped_item = lddas_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets deleted'); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were deleted.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be deleted'); - } - Galaxy.modal.hide(); - return this.deleted_lddas; - } - var promise = $.when(popped_item.destroy()); - - promise.done(function(dataset){ - // we are fine - Galaxy.libraries.folderListView.collection.remove(popped_item.id); - self.updateProgress(); - // add the deleted dataset to collection, triggers rendering - if (Galaxy.libraries.folderListView.options.include_deleted){ - var updated_dataset = new mod_library_model.Item(dataset); - Galaxy.libraries.folderListView.collection.add(updated_dataset); - } - // execute next request - self.chainCallDeletingHdas(lddas_set); - }) - .fail(function(){ - // we have a problem - self.options.chain_call_control.failed_number += 1; - self.updateProgress(); - // execute next request - self.chainCallDeletingHdas(lddas_set); - }); - }, showLibInfo: function(){ var library_id = Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id; @@ -989,7 +981,7 @@ var tmpl_array = []; tmpl_array.push('<div class="import_text">'); - tmpl_array.push('Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>'); + tmpl_array.push('Adding selected datasets to library folder <b><%= _.escape(folder_name) %></b>'); tmpl_array.push('</div>'); tmpl_array.push('<div class="progress">'); tmpl_array.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">'); diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 static/scripts/libs/jquery/jstree.js --- a/static/scripts/libs/jquery/jstree.js +++ b/static/scripts/libs/jquery/jstree.js @@ -2,7 +2,7 @@ (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { - // define(['jquery'], factory); + define(['jquery'], factory); } else if(typeof exports === 'object') { factory(require('jquery')); diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 static/scripts/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/mvc/library/library-foldertoolbar-view.js @@ -2,13 +2,11 @@ "galaxy.masthead", "utils/utils", "libs/toastr", - "libs/jquery/jstree", "mvc/library/library-model"], -function(mod_masthead, +function( mod_masthead, mod_utils, mod_toastr, - ignore_jstree, - mod_library_model) { + mod_library_model ) { var FolderToolbarView = Backbone.View.extend({ el: '#center', @@ -40,7 +38,7 @@ histories : null, initialize: function(options){ - this.options = _.defaults(options || {}, this.defaults); + this.options = _.defaults( options || {}, this.defaults ); this.render(); }, @@ -202,89 +200,42 @@ * Import all selected datasets into history. */ importAllIntoHistory : function (){ - this.modal.disableButton('Import'); - - // init the control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - var history_id = $("select[name=dataset_import_bulk] option:selected").val(); - // we can save last used history to pre-select it next time - this.options.last_used_history_id = history_id; - var history_name = $("select[name=dataset_import_bulk] option:selected").text(); - - var dataset_ids = []; - $('#folder_table').find(':checked').each(function(){ - if (this.parentElement.parentElement.id !== '') { - dataset_ids.push(this.parentElement.parentElement.id); - } - }); - var progress_bar_tmpl = this.templateImportIntoHistoryProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ history_name : history_name })); - - // init the progress bar - var progressStep = 100 / dataset_ids.length; - this.initProgress(progressStep); - - // prepare the dataset objects to be imported - var datasets_to_import = []; - for (var i = dataset_ids.length - 1; i >= 0; i--) { - var library_dataset_id = dataset_ids[i]; - var historyItem = new mod_library_model.HistoryItem(); - historyItem.url = historyItem.urlRoot + history_id + '/contents'; - historyItem.content = library_dataset_id; - historyItem.source = 'library'; - datasets_to_import.push(historyItem); - } - this.options.chain_call_control.total_number = datasets_to_import.length; - - // set the used history as current so user will see the last one - // that he imported into in the history panel on the 'analysis' page - jQuery.getJSON( galaxy_config.root + 'history/set_as_current?id=' + history_id ); - - // call the recursive function to call ajax one after each other (request FIFO queue) - this.chainCall(datasets_to_import, history_name); + this.modal.disableButton('Import'); + var history_id = $("select[name=dataset_import_bulk] option:selected").val(); + var history_name = $("select[name=dataset_import_bulk] option:selected").text(); + // we can save last used history to pre-select it next time + this.options.last_used_history_id = history_id; + var dataset_ids = []; + $('#folder_table').find(':checked').each(function(){ + if (this.parentElement.parentElement.id !== '') { + dataset_ids.push(this.parentElement.parentElement.id); + } + }); + // prepare the dataset objects to be imported + var datasets_to_import = []; + for (var i = dataset_ids.length - 1; i >= 0; i--) { + var library_dataset_id = dataset_ids[i]; + var historyItem = new mod_library_model.HistoryItem(); + historyItem.url = historyItem.urlRoot + history_id + '/contents'; + historyItem.content = library_dataset_id; + historyItem.source = 'library'; + datasets_to_import.push(historyItem); + } + this.initChainCallControl( { length: datasets_to_import.length, action: 'to_history', history_name: history_name } ); + // set the used history as current so user will see the last one + // that he imported into in the history panel on the 'analysis' page + jQuery.getJSON( galaxy_config.root + 'history/set_as_current?id=' + history_id ); + this.chainCallImportingIntoHistory( datasets_to_import, history_name ); }, - chainCall: function(history_item_set, history_name){ - var self = this; - var popped_item = history_item_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets imported into history. Click this to start analysing it.', '', {onclick: function() {window.location='/'}}); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were imported into history.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be imported into history. Click this to see what was imported.', '', {onclick: function() {window.location='/'}}); - } - Galaxy.modal.hide(); - return; - } - var promise = $.when(popped_item.save({content: popped_item.content, source: popped_item.source})); - - promise.done(function(){ - // we are fine - self.updateProgress(); - self.chainCall(history_item_set, history_name); - }) - .fail(function(){ - // we have a problem - self.options.chain_call_control.failed_number += 1; - self.updateProgress(); - self.chainCall(history_item_set, history_name); - }); - }, - - initProgress: function(progressStep){ - this.progress = 0; - this.progressStep = progressStep; - }, - + /** + * Update the progress bar in modal window. + */ updateProgress: function(){ this.progress += this.progressStep; - $('.progress-bar-import').width(Math.round(this.progress) + '%'); - txt_representation = Math.round(this.progress) + '% Complete'; - $('.completion_span').text(txt_representation); + $( '.progress-bar-import' ).width( Math.round( this.progress ) + '%' ); + txt_representation = Math.round( this.progress ) + '% Complete'; + $( '.completion_span' ).text( txt_representation ); }, /** @@ -292,16 +243,16 @@ * @param {str} folder_id id of the current folder * @param {str} format requested archive format */ - download : function(folder_id, format){ + download : function( folder_id, format ){ var dataset_ids = []; - $('#folder_table').find(':checked').each(function(){ - if (this.parentElement.parentElement.id !== '') { - dataset_ids.push(this.parentElement.parentElement.id); + $( '#folder_table' ).find( ':checked' ).each( function(){ + if ( this.parentElement.parentElement.id !== '' ) { + dataset_ids.push( this.parentElement.parentElement.id ); } - }); + } ); var url = '/api/libraries/datasets/download/' + format; - var data = {'ldda_ids' : dataset_ids}; - this.processDownload(url, data, 'get'); + var data = { 'ldda_ids' : dataset_ids }; + this.processDownload( url, data, 'get' ); }, /** @@ -311,27 +262,27 @@ * @param {obj} data data to include in the request * @param {str} method method of the request */ - processDownload: function(url, data, method){ + processDownload: function( url, data, method ){ if ( url && data ){ // data can be string of parameters or array/object - data = typeof data === 'string' ? data : $.param(data); + data = typeof data === 'string' ? data : $.param( data ); // split params into form inputs var inputs = ''; - $.each(data.split('&'), function(){ - var pair = this.split('='); + $.each( data.split( '&' ), function(){ + var pair = this.split( '=' ); inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; }); // send request $('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>') - .appendTo('body').submit().remove(); - mod_toastr.info('Your download will begin soon'); + .appendTo( 'body' ).submit().remove(); + mod_toastr.info( 'Your download will begin soon' ); } else { - mod_toastr.error('An error occurred :('); + mod_toastr.error( 'An error occurred :(' ); } }, addFilesFromHistoryModal: function(){ - this.refreshUserHistoriesList(function(self){ + this.refreshUserHistoriesList( function( self ){ self.modal = Galaxy.modal; var template_modal = self.templateAddFilesFromHistory(); var folder_name = self.options.full_path[self.options.full_path.length - 1][1] @@ -355,7 +306,7 @@ self.fetchAndDisplayHistoryContents(event.target.value); }); } else { - mod_toastr.error('An error ocurred :('); + mod_toastr.error( 'An error ocurred :(' ); } }); }, @@ -438,23 +389,28 @@ this.jstree.url = this.jstree.urlRoot + '?target=userdir&format=jstree&disable=' + disabled_jstree_element; this.jstree.fetch({ success: function(model, response){ - $('#jstree_browser').jstree("destroy"); - var jstreeObject = $('#jstree_browser').jstree({ - 'core':{ - 'data': model - }, - 'plugins': ['types', 'checkbox'], - 'types': { - "folder": { - "icon": "jstree-folder" + // This is to prevent double jquery load. I think. Carl is magician. + define( 'jquery', function(){ return jQuery; }); + // Now we need jstree, time to lazy load it. + require([ 'libs/jquery/jstree' ], function(jstree){ + $('#jstree_browser').jstree("destroy"); + $('#jstree_browser').jstree({ + 'core':{ + 'data': model }, - "file": { - "icon": "jstree-file" + 'plugins': ['types', 'checkbox'], + 'types': { + "folder": { + "icon": "jstree-folder" + }, + "file": { + "icon": "jstree-file" + } + }, + 'checkbox': { + three_state: false } - }, - 'checkbox': { - three_state: false - } + }); }); }, error: function(model, response){ @@ -476,19 +432,19 @@ var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); var paths = $('textarea#import_paths').val(); + var valid_paths = []; if (!paths){ mod_toastr.info('Please enter a path relative to Galaxy root'); } else { this.modal.disableButton('Import'); paths = paths.split('\n'); - var valid_paths = []; for (var i = paths.length - 1; i >= 0; i--) { trimmed = paths[i].trim(); if (trimmed.length!==0){ valid_paths.push(trimmed); } }; - this.initChainCallControl(valid_paths.length); + this.initChainCallControl( { length: valid_paths.length, action: 'adding_datasets' } ); this.chainCallImportingFolders(valid_paths, preserve_dirs, link_data, 'admin_path'); } }, @@ -496,127 +452,68 @@ /** * Initialize the control of chaining requests * in the current modal. + * @param {int} length The number of items in the chain call. */ - initChainCallControl: function(length){ - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); + initChainCallControl: function( options ){ + var template; + switch( options.action ){ + case "adding_datasets": + template = this.templateAddingDatasetsProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template( { folder_name : this.options.folder_name } ) ); + break; + case "deleting_datasets": + template = this.templateDeletingDatasetsProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template() ); + break; + case "to_history": + template = this.templateImportIntoHistoryProgressBar(); + this.modal.$el.find( '.modal-body' ).html( template( { history_name : options.history_name } ) ); + break; + default: + console.error( 'Wrong action specified.') + break; + } + + // var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); + // this.modal.$el.find( '.modal-body' ).html( progress_bar_tmpl( { folder_name : this.options.folder_name } ) ); this.progress = 0; - this.progressStep = 100 / length; - this.options.chain_call_control.total_number = length; + this.progressStep = 100 / options.length; + this.options.chain_call_control.total_number = options.length; this.options.chain_call_control.failed_number = 0; }, /** * Take the selected items from the jstree, create a request queue * and send them one by one to the server for importing into - * the current folder. + * the current folder. + * + * jstree.js has to be loaded before + * @see renderJstree */ - importFromUserdirClicked: function (that){ - var selected_nodes = $('#jstree_browser').jstree().get_selected(true); - var preserve_dirs = this.modal.$el.find('.preserve-checkbox').is(':checked'); - var link_data = this.modal.$el.find('.link-checkbox').is(':checked'); + importFromUserdirClicked: function ( that ){ + var selected_nodes = $( '#jstree_browser' ).jstree().get_selected( true ); + var preserve_dirs = this.modal.$el.find( '.preserve-checkbox' ).is( ':checked' ); + var link_data = this.modal.$el.find( '.link-checkbox' ).is( ':checked' ); + var selection_type = selected_nodes[0].type; var paths = []; - if (selected_nodes.length < 1){ - mod_toastr.info('You have to select some items first'); + if ( selected_nodes.length < 1 ){ + mod_toastr.info( 'You have to select some items first' ); } else { - // disable the button to prevent multiple submission - this.modal.disableButton('Import'); - // init the chain control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - for (var i = selected_nodes.length - 1; i >= 0; i--){ - if(selected_nodes[i].li_attr.full_path !== undefined){ - paths.push(selected_nodes[i].li_attr.full_path); + this.modal.disableButton( 'Import' ); + for ( var i = selected_nodes.length - 1; i >= 0; i-- ){ + if ( selected_nodes[i].li_attr.full_path !== undefined ){ + paths.push( selected_nodes[i].li_attr.full_path ); } } - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); - - // init the progress bar - this.progressStep = 100 / paths.length; - this.progress = 0; - this.options.chain_call_control.total_number = paths.length; - - var selection_type = selected_nodes[0].type; - // call the recursive function to call ajax one after each other (request FIFO queue) - if (selection_type === 'folder'){ - this.chainCallImportingFolders(paths, preserve_dirs, link_data, 'userdir_folder'); - } else if (selection_type === 'file'){ - this.chainCallImportingUserdirFiles(paths); + this.initChainCallControl( { length: paths.length, action: 'adding_datasets' } ); + if ( selection_type === 'folder' ){ + this.chainCallImportingFolders( paths, preserve_dirs, link_data, 'userdir_folder' ); + } else if ( selection_type === 'file' ){ + this.chainCallImportingUserdirFiles( paths ); } } }, - /** - * Take the array of paths and createa request for each of them - * calling them in chain. Update the progress bar in between each. - * @param {array} paths paths relative to user folder on Galaxy - */ - chainCallImportingUserdirFiles: function(paths){ - var that = this; - var popped_item = paths.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected files imported into the current folder'); - Galaxy.modal.hide(); - } else { - mod_toastr.error('Something went wrong :('); - } - return true; - } - var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + - '&source=userdir_file' + - '&path=' + popped_item)) - promise.done(function(response){ - that.updateProgress(); - that.chainCallImportingUserdirFiles(paths); - }) - .fail(function(){ - that.options.chain_call_control.failed_number += 1; - that.updateProgress(); - that.chainCallImportingUserdirFiles(paths); - }); - }, - - /** - * Take the array of paths and createa request for each of them - * calling them in chain. Update the progress bar in between each. - * @param {array} paths paths relative to Galaxy root folder - * @param {boolean} preserve_dirs indicates whether to preserve folder structure - * @param {boolean} link_data copy files to Galaxy or link instead - * @param {str} source string representing what type of folder - * is the source of import - */ - chainCallImportingFolders: function(paths, preserve_dirs, link_data, source){ - // need to check which paths to call - var that = this; - var popped_item = paths.pop(); - if (typeof popped_item == "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected folders and their contents imported into the current folder'); - Galaxy.modal.hide(); - } else { - mod_toastr.error('Something went wrong :('); - } - return true; - } - var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + - '&source=' + source + - '&path=' + popped_item + - '&preserve_dirs=' + preserve_dirs + - '&link_data=' + link_data)) - promise.done(function(response){ - that.updateProgress(); - that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); - }) - .fail(function(){ - that.options.chain_call_control.failed_number += 1; - that.updateProgress(); - that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); - }); - }, - fetchAndDisplayHistoryContents: function(history_id){ var history_contents = new mod_library_model.HistoryContents({id:history_id}); var self = this; @@ -636,79 +533,212 @@ }); }, - // add all selected datasets from history into current folder + /** + * Import all selected datasets from history into the current folder. + */ addAllDatasetsFromHistory : function (){ - var checked_hdas = this.modal.$el.find('#selected_history_content').find(':checked'); - if (checked_hdas.length < 1){ - mod_toastr.info('You have to select some datasets first'); - } else { - // disable the button to prevent multiple submission - this.modal.disableButton('Add'); - // init the control counters - this.options.chain_call_control.total_number = 0; - this.options.chain_call_control.failed_number = 0; - - var history_dataset_ids = []; - checked_hdas.each(function(){ - var hid = $(this.parentElement).data('id'); - if (hid) { - history_dataset_ids.push(hid); - } - }); - var progress_bar_tmpl = this.templateAddingDatasetsProgressBar(); - this.modal.$el.find('.modal-body').html(progress_bar_tmpl({ folder_name : this.options.folder_name })); - - // init the progress bar - this.progressStep = 100 / history_dataset_ids.length; - this.progress = 0; - - // prepare the dataset items to be added - var hdas_to_add = []; - for (var i = history_dataset_ids.length - 1; i >= 0; i--) { - history_dataset_id = history_dataset_ids[i]; - var folder_item = new mod_library_model.Item(); - folder_item.url = '/api/folders/' + this.options.id + '/contents'; - folder_item.set({'from_hda_id':history_dataset_id}); - hdas_to_add.push(folder_item); - } - this.options.chain_call_control.total_number = hdas_to_add.length; - // call the recursive function to call ajax one after each other (request FIFO queue) - this.chainCallAddingHdas(hdas_to_add); + var checked_hdas = this.modal.$el.find( '#selected_history_content' ).find( ':checked' ); + var history_dataset_ids = []; + var hdas_to_add = []; + if ( checked_hdas.length < 1 ){ + mod_toastr.info( 'You have to select some datasets first' ); + } else { + this.modal.disableButton( 'Add' ); + checked_hdas.each(function(){ + var hid = $( this.parentElement ).data( 'id' ); + if ( hid ) { + history_dataset_ids.push( hid ); + } + }); + for ( var i = history_dataset_ids.length - 1; i >= 0; i-- ) { + history_dataset_id = history_dataset_ids[i]; + var folder_item = new mod_library_model.Item(); + folder_item.url = '/api/folders/' + this.options.id + '/contents'; + folder_item.set( { 'from_hda_id':history_dataset_id } ); + hdas_to_add.push( folder_item ); } + this.initChainCallControl( { length: hdas_to_add.length, action: 'adding_datasets' } ); + this.chainCallAddingHdas( hdas_to_add ); + } }, - chainCallAddingHdas: function(hdas_set){ + /** + * Take array of empty history items and make request for each of them + * to create it on server. Update progress in between calls. + * @param {array} history_item_set array of empty history items + * @param {str} history_name name of the history to import to + */ + chainCallImportingIntoHistory: function( history_item_set, history_name ){ + var self = this; + var popped_item = history_item_set.pop(); + if ( typeof popped_item == "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets imported into history. Click this to start analysing it.', '', { onclick: function() { window.location='/' } } ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were imported into history.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be imported into history. Click this to see what was imported.', '', { onclick: function() { window.location='/' } } ); + } + Galaxy.modal.hide(); + return true; + } + var promise = $.when( popped_item.save( { content: popped_item.content, source: popped_item.source } ) ); + + promise.done( function(){ + self.updateProgress(); + self.chainCallImportingIntoHistory( history_item_set, history_name ); + } ) + .fail( function(){ + self.options.chain_call_control.failed_number += 1; + self.updateProgress(); + self.chainCallImportingIntoHistory( history_item_set, history_name ); + } ); + }, + + /** + * Take the array of paths and createa request for each of them + * calling them in chain. Update the progress bar in between each. + * @param {array} paths paths relative to user folder on Galaxy + */ + chainCallImportingUserdirFiles: function( paths ){ + var that = this; + var popped_item = paths.pop(); + if ( typeof popped_item === "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected files imported into the current folder' ); + Galaxy.modal.hide(); + } else { + mod_toastr.error( 'Something went wrong :(' ); + } + return true; + } + var promise = $.when( $.post( '/api/libraries/datasets?encoded_folder_id=' + that.id + + '&source=userdir_file' + + '&path=' + popped_item ) ) + promise.done( function( response ){ + that.updateProgress(); + that.chainCallImportingUserdirFiles( paths ); + } ) + .fail( function(){ + that.options.chain_call_control.failed_number += 1; + that.updateProgress(); + that.chainCallImportingUserdirFiles( paths ); + } ); + }, + + /** + * Take the array of paths and createa request for each of them + * calling them in chain. Update the progress bar in between each. + * @param {array} paths paths relative to Galaxy root folder + * @param {boolean} preserve_dirs indicates whether to preserve folder structure + * @param {boolean} link_data copy files to Galaxy or link instead + * @param {str} source string representing what type of folder + * is the source of import + */ + chainCallImportingFolders: function(paths, preserve_dirs, link_data, source){ + // need to check which paths to call + var that = this; + var popped_item = paths.pop(); + if (typeof popped_item == "undefined") { + if (this.options.chain_call_control.failed_number === 0){ + mod_toastr.success('Selected folders and their contents imported into the current folder'); + Galaxy.modal.hide(); + } else { + // TODO better error report + mod_toastr.error('Something went wrong :('); + } + return true; + } + var promise = $.when($.post('/api/libraries/datasets?encoded_folder_id=' + that.id + + '&source=' + source + + '&path=' + popped_item + + '&preserve_dirs=' + preserve_dirs + + '&link_data=' + link_data)) + promise.done(function(response){ + that.updateProgress(); + that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); + }) + .fail(function(){ + that.options.chain_call_control.failed_number += 1; + that.updateProgress(); + that.chainCallImportingFolders(paths, preserve_dirs, link_data, source); + }); + }, + + /** + * Take the array of hdas and create a request for each. + * Call them in chain and update progress bar in between each. + * @param {array} hdas_set array of empty hda objects + */ + chainCallAddingHdas: function( hdas_set ){ var self = this; this.added_hdas = new mod_library_model.Folder(); var popped_item = hdas_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets from history added to the folder'); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were added to the folder.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be added to the folder'); + if ( typeof popped_item == "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets from history added to the folder' ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were added to the folder.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be added to the folder' ); } Galaxy.modal.hide(); return this.added_hdas; } - var promise = $.when(popped_item.save({from_hda_id: popped_item.get('from_hda_id')})); + var promise = $.when( popped_item.save( { from_hda_id: popped_item.get( 'from_hda_id' ) } ) ); - promise.done(function(model){ - // we are fine - Galaxy.libraries.folderListView.collection.add(model); + promise.done( function( model ){ + Galaxy.libraries.folderListView.collection.add( model ); self.updateProgress(); - self.chainCallAddingHdas(hdas_set); + self.chainCallAddingHdas( hdas_set ); }) - .fail(function(){ - // we have a problem + .fail( function(){ self.options.chain_call_control.failed_number += 1; self.updateProgress(); - self.chainCallAddingHdas(hdas_set); + self.chainCallAddingHdas( hdas_set ); }); }, /** + * Take the array of lddas, create request for each and + * call them in chain. Update progress bar in between each. + * @param {array} lddas_set array of lddas to delete + */ + chainCallDeletingHdas: function( lddas_set ){ + var self = this; + this.deleted_lddas = new mod_library_model.Folder(); + var popped_item = lddas_set.pop(); + if ( typeof popped_item === "undefined" ) { + if ( this.options.chain_call_control.failed_number === 0 ){ + mod_toastr.success( 'Selected datasets deleted' ); + } else if ( this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number ){ + mod_toastr.error( 'There was an error and no datasets were deleted.' ); + } else if ( this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number ){ + mod_toastr.warning( 'Some of the datasets could not be deleted' ); + } + Galaxy.modal.hide(); + return this.deleted_lddas; + } + var promise = $.when( popped_item.destroy() ); + + promise.done( function( dataset ){ + Galaxy.libraries.folderListView.collection.remove( popped_item.id ); + self.updateProgress(); + // add the deleted dataset to collection, triggers rendering + if ( Galaxy.libraries.folderListView.options.include_deleted ){ + var updated_dataset = new mod_library_model.Item( dataset ); + Galaxy.libraries.folderListView.collection.add( updated_dataset ); + } + self.chainCallDeletingHdas( lddas_set ); + }) + .fail( function(){ + self.options.chain_call_control.failed_number += 1; + self.updateProgress(); + self.chainCallDeletingHdas( lddas_set ); + }); + }, + + /** * Handles the click on 'show deleted' checkbox */ checkIncludeDeleted: function(event){ @@ -764,43 +794,6 @@ } }, - chainCallDeletingHdas: function(lddas_set){ - var self = this; - this.deleted_lddas = new mod_library_model.Folder(); - var popped_item = lddas_set.pop(); - if (typeof popped_item === "undefined") { - if (this.options.chain_call_control.failed_number === 0){ - mod_toastr.success('Selected datasets deleted'); - } else if (this.options.chain_call_control.failed_number === this.options.chain_call_control.total_number){ - mod_toastr.error('There was an error and no datasets were deleted.'); - } else if (this.options.chain_call_control.failed_number < this.options.chain_call_control.total_number){ - mod_toastr.warning('Some of the datasets could not be deleted'); - } - Galaxy.modal.hide(); - return this.deleted_lddas; - } - var promise = $.when(popped_item.destroy()); - - promise.done(function(dataset){ - // we are fine - Galaxy.libraries.folderListView.collection.remove(popped_item.id); - self.updateProgress(); - // add the deleted dataset to collection, triggers rendering - if (Galaxy.libraries.folderListView.options.include_deleted){ - var updated_dataset = new mod_library_model.Item(dataset); - Galaxy.libraries.folderListView.collection.add(updated_dataset); - } - // execute next request - self.chainCallDeletingHdas(lddas_set); - }) - .fail(function(){ - // we have a problem - self.options.chain_call_control.failed_number += 1; - self.updateProgress(); - // execute next request - self.chainCallDeletingHdas(lddas_set); - }); - }, showLibInfo: function(){ var library_id = Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id; @@ -988,7 +981,7 @@ var tmpl_array = []; tmpl_array.push('<div class="import_text">'); - tmpl_array.push('Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>'); + tmpl_array.push('Adding selected datasets to library folder <b><%= _.escape(folder_name) %></b>'); tmpl_array.push('</div>'); tmpl_array.push('<div class="progress">'); tmpl_array.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">'); diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 static/scripts/packed/libs/jquery/jstree.js --- a/static/scripts/packed/libs/jquery/jstree.js +++ b/static/scripts/packed/libs/jquery/jstree.js @@ -1,4 +1,4 @@ -(function(a){if(typeof define==="function"&&define.amd){}else{if(typeof exports==="object"){a(require("jquery"))}else{a(jQuery)}}}(function(i,e){ +(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],a)}else{if(typeof exports==="object"){a(require("jquery"))}else{a(jQuery)}}}(function(i,e){ /* * jsTree 3.0.3 * http://jstree.com/ diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 static/scripts/packed/mvc/library/library-foldertoolbar-view.js --- a/static/scripts/packed/mvc/library/library-foldertoolbar-view.js +++ b/static/scripts/packed/mvc/library/library-foldertoolbar-view.js @@ -1,1 +1,1 @@ -define(["galaxy.masthead","utils/utils","libs/toastr","libs/jquery/jstree","mvc/library/library-model"],function(c,e,f,b,d){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0},disabled_jstree_element:"folders"},modal:null,jstree:null,histories:null,initialize:function(g){this.options=_.defaults(g||{},this.defaults);this.render()},render:function(g){this.options=_.extend(this.options,g);var i=this.templateToolBar();var h={id:this.options.id,is_admin:false,is_anonym:true,user_library_import_dir:Galaxy.config.user_library_import_dir,allow_library_path_paste:Galaxy.config.allow_library_path_paste,library_import_dir:Galaxy.config.library_import_dir,mutiple_add_dataset_options:false};if(Galaxy.currUser){h.is_admin=Galaxy.currUser.isAdmin();h.is_anonym=Galaxy.currUser.isAnonymous();if(h.user_library_import_dir!==null||h.allow_library_path_paste!==false||h.library_import_dir!==null){h.mutiple_add_dataset_options=true}}this.$el.html(i(h))},configureElements:function(g){this.options=_.extend(this.options,g);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(i){i.preventDefault();i.stopPropagation();var g=this;var h=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:h(),buttons:{Create:function(){g.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var g=this.serialize_new_folder();if(this.validate_new_folder(g)){var h=new d.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];h.url=h.urlRoot+"/"+current_folder_id;h.save(g,{success:function(i){Galaxy.modal.hide();f.success("Folder created");i.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(i)},error:function(j,i){Galaxy.modal.hide();if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}else{f.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(g){return g.name!==""},modalBulkImport:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(i){var h=i.templateBulkImportInModal();i.modal=Galaxy.modal;i.modal.show({closing_events:true,title:"Import into History",body:h({histories:i.histories.models}),buttons:{Import:function(){i.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(h){var g=this;this.histories=new d.GalaxyHistories();this.histories.fetch({success:function(){h(g)},error:function(j,i){if(typeof i.responseJSON!=="undefined"){f.error(i.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var k=$("select[name=dataset_import_bulk] option:selected").val();this.options.last_used_history_id=k;var n=$("select[name=dataset_import_bulk] option:selected").text();var p=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){p.push(this.parentElement.parentElement.id)}});var o=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(o({history_name:n}));var l=100/p.length;this.initProgress(l);var g=[];for(var h=p.length-1;h>=0;h--){var j=p[h];var m=new d.HistoryItem();m.url=m.urlRoot+k+"/contents";m.content=j;m.source="library";g.push(m)}this.options.chain_call_control.total_number=g.length;jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+k);this.chainCall(g,n)},chainCall:function(h,k){var g=this;var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return}var j=$.when(i.save({content:i.content,source:i.source}));j.done(function(){g.updateProgress();g.chainCall(h,k)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCall(h,k)})},initProgress:function(g){this.progress=0;this.progressStep=g},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(g,k){var i=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){i.push(this.parentElement.parentElement.id)}});var h="/api/libraries/datasets/download/"+k;var j={ldda_ids:i};this.processDownload(h,j,"get")},processDownload:function(h,i,j){if(h&&i){i=typeof i==="string"?i:$.param(i);var g="";$.each(i.split("&"),function(){var k=this.split("=");g+='<input type="hidden" name="'+k[0]+'" value="'+k[1]+'" />'});$('<form action="'+h+'" method="'+(j||"post")+'">'+g+"</form>").appendTo("body").submit().remove();f.info("Your download will begin soon")}else{f.error("An error occurred :(")}},addFilesFromHistoryModal:function(){this.refreshUserHistoriesList(function(g){g.modal=Galaxy.modal;var h=g.templateAddFilesFromHistory();var i=g.options.full_path[g.options.full_path.length-1][1];g.modal.show({closing_events:true,title:"Adding datasets from your history to folder "+i,body:h({histories:g.histories.models}),buttons:{Add:function(){g.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.back()}});if(g.histories.models.length>0){g.fetchAndDisplayHistoryContents(g.histories.models[0].id);$("#dataset_add_bulk").change(function(j){g.fetchAndDisplayHistoryContents(j.target.value)})}else{f.error("An error ocurred :(")}})},importFilesFromPathModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateImportPathModal();this.modal.show({closing_events:true,title:"Enter paths relative to Galaxy root",body:g({}),buttons:{Import:function(){h.importFromPathsClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}})},importFilesFromUserdirModal:function(){var h=this;this.modal=Galaxy.modal;var g=this.templateBrowserModal();this.modal.show({closing_events:true,title:"Select folders or files to import",body:g({}),buttons:{Import:function(){h.importFromUserdirClicked(h)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+h.id,{trigger:true})}});this.renderJstree({disabled_jstree_element:"folders"});$("input[type=radio]").change(function(i){if(i.target.value==="jstree-disable-folders"){h.renderJstree({disabled_jstree_element:"folders"});$(".jstree-folders-message").hide();$(".jstree-preserve-structure").hide();$(".jstree-link-files").hide();$(".jstree-files-message").show()}else{if(i.target.value==="jstree-disable-files"){$(".jstree-files-message").hide();$(".jstree-folders-message").show();$(".jstree-link-files").show();$(".jstree-preserve-structure").show();h.renderJstree({disabled_jstree_element:"files"})}}})},renderJstree:function(g){var i=this;this.options=_.extend(this.options,g);var h=this.options.disabled_jstree_element;this.jstree=new d.Jstree();this.jstree.url=this.jstree.urlRoot+"?target=userdir&format=jstree&disable="+h;this.jstree.fetch({success:function(k,j){$("#jstree_browser").jstree("destroy");var l=$("#jstree_browser").jstree({core:{data:k},plugins:["types","checkbox"],types:{folder:{icon:"jstree-folder"},file:{icon:"jstree-file"}},checkbox:{three_state:false}})},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},importFromPathsClicked:function(){var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var l=this.modal.$el.find(".link-checkbox").is(":checked");var k=$("textarea#import_paths").val();if(!k){f.info("Please enter a path relative to Galaxy root")}else{this.modal.disableButton("Import");k=k.split("\n");var j=[];for(var h=k.length-1;h>=0;h--){trimmed=k[h].trim();if(trimmed.length!==0){j.push(trimmed)}}this.initChainCallControl(j.length);this.chainCallImportingFolders(j,g,l,"admin_path")}},initChainCallControl:function(g){var h=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(h({folder_name:this.options.folder_name}));this.progress=0;this.progressStep=100/g;this.options.chain_call_control.total_number=g;this.options.chain_call_control.failed_number=0},importFromUserdirClicked:function(l){var h=$("#jstree_browser").jstree().get_selected(true);var g=this.modal.$el.find(".preserve-checkbox").is(":checked");var o=this.modal.$el.find(".link-checkbox").is(":checked");var n=[];if(h.length<1){f.info("You have to select some items first")}else{this.modal.disableButton("Import");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;for(var j=h.length-1;j>=0;j--){if(h[j].li_attr.full_path!==undefined){n.push(h[j].li_attr.full_path)}}var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/n.length;this.progress=0;this.options.chain_call_control.total_number=n.length;var k=h[0].type;if(k==="folder"){this.chainCallImportingFolders(n,g,o,"userdir_folder")}else{if(k==="file"){this.chainCallImportingUserdirFiles(n)}}}},chainCallImportingUserdirFiles:function(j){var g=this;var h=j.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected files imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var i=$.when($.post("/api/libraries/datasets?encoded_folder_id="+g.id+"&source=userdir_file&path="+h));i.done(function(k){g.updateProgress();g.chainCallImportingUserdirFiles(j)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallImportingUserdirFiles(j)})},chainCallImportingFolders:function(l,g,m,j){var h=this;var i=l.pop();if(typeof i=="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected folders and their contents imported into the current folder");Galaxy.modal.hide()}else{f.error("Something went wrong :(")}return true}var k=$.when($.post("/api/libraries/datasets?encoded_folder_id="+h.id+"&source="+j+"&path="+i+"&preserve_dirs="+g+"&link_data="+m));k.done(function(n){h.updateProgress();h.chainCallImportingFolders(l,g,m,j)}).fail(function(){h.options.chain_call_control.failed_number+=1;h.updateProgress();h.chainCallImportingFolders(l,g,m,j)})},fetchAndDisplayHistoryContents:function(i){var h=new d.HistoryContents({id:i});var g=this;h.fetch({success:function(k){var j=g.templateHistoryContents();g.histories.get(i).set({contents:k});g.modal.$el.find("#selected_history_content").html(j({history_contents:k.models.reverse()}))},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){var l=this.modal.$el.find("#selected_history_content").find(":checked");if(l.length<1){f.info("You have to select some datasets first")}else{this.modal.disableButton("Add");this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];l.each(function(){var i=$(this.parentElement).data("id");if(i){g.push(i)}});var m=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(m({folder_name:this.options.folder_name}));this.progressStep=100/g.length;this.progress=0;var k=[];for(var j=g.length-1;j>=0;j--){history_dataset_id=g[j];var h=new d.Item();h.url="/api/folders/"+this.options.id+"/contents";h.set({from_hda_id:history_dataset_id});k.push(h)}this.options.chain_call_control.total_number=k.length;this.chainCallAddingHdas(k)}},chainCallAddingHdas:function(h){var g=this;this.added_hdas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var j=$.when(i.save({from_hda_id:i.get("from_hda_id")}));j.done(function(k){Galaxy.libraries.folderListView.collection.add(k);g.updateProgress();g.chainCallAddingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallAddingHdas(h)})},checkIncludeDeleted:function(g){if(g.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var g=$("#folder_table").find(":checked");if(g.length===0){f.info("You have to select some datasets first")}else{var k=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:k({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var h=[];g.each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});this.progressStep=100/h.length;this.progress=0;var m=[];for(var j=h.length-1;j>=0;j--){var l=new d.Item({id:h[j]});m.push(l)}this.options.chain_call_control.total_number=h.length;this.chainCallDeletingHdas(m)}},chainCallDeletingHdas:function(h){var g=this;this.deleted_lddas=new d.Folder();var i=h.pop();if(typeof i==="undefined"){if(this.options.chain_call_control.failed_number===0){f.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){f.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){f.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var j=$.when(i.destroy());j.done(function(l){Galaxy.libraries.folderListView.collection.remove(i.id);g.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var k=new d.Item(l);Galaxy.libraries.folderListView.collection.add(k)}g.chainCallDeletingHdas(h)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallDeletingHdas(h)})},showLibInfo:function(){var h=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var g=null;var i=this;if(Galaxy.libraries.libraryListView!==null){g=Galaxy.libraries.libraryListView.collection.get(h);this.showLibInfoModal(g)}else{g=new d.Library({id:h});g.fetch({success:function(){i.showLibInfoModal(g)},error:function(k,j){if(typeof j.responseJSON!=="undefined"){f.error(j.responseJSON.err_msg)}else{f.error("An error ocurred :(")}}})}},showLibInfoModal:function(g){var h=this.templateLibInfoInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Library Information",body:h({library:g}),buttons:{Close:function(){Galaxy.modal.hide()}}})},showImportModal:function(g){switch(g.source){case"history":this.addFilesFromHistoryModal();break;case"importdir":break;case"path":this.importFilesFromPathModal();break;case"userdir":this.importFilesFromUserdirModal();break;default:Galaxy.libraries.library_router.back();f.error("Invalid import source.");break}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push("<% if(mutiple_add_dataset_options) { %>");tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button title="Add Datasets to Current Folder" id="" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-plus"></span><span class="fa fa-file"></span><span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#folders/<%= id %>/import/history"> from History</a></li>');tmpl_array.push("<% if(user_library_import_dir !== null) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/userdir"> from User Directory</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li class="divider"></li>');tmpl_array.push(' <li class="dropdown-header">Admins only</li>');tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/path">from Path</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% } %>");tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push("<% } else { %>");tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push("<% } %>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var g=[];g.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');g.push("Select history: ");g.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</span>");return _.template(g.join(""))},templateImportIntoHistoryProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateAddingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("Adding selected datasets from history to library folder <b><%= _.escape(folder_name) %></b>");g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateDeletingDatasetsProgressBar:function(){var g=[];g.push('<div class="import_text">');g.push("</div>");g.push('<div class="progress">');g.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');g.push(' <span class="completion_span">0% Complete</span>');g.push(" </div>");g.push("</div>");g.push("");return _.template(g.join(""))},templateBrowserModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<div style="margin-bottom:1em;">');g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting files" type="radio" name="jstree-radio" value="jstree-disable-folders" checked="checked"> Files');g.push("</label>");g.push('<label class="radio-inline">');g.push(' <input title="Switch to selecting folders" type="radio" name="jstree-radio" value="jstree-disable-files"> Folders');g.push("</label>");g.push('<label class="checkbox-inline jstree-preserve-structure" style="display:none;">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files" style="display:none;">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-files-message">All files you select will be imported into the current folder.</div>');g.push('<div class="alert alert-info jstree-folders-message" style="display:none;">All files within the selected folders and their subfolders will be imported into the current folder.</div>');g.push('<div id="jstree_browser">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateImportPathModal:function(){var g=[];g.push('<div id="file_browser_modal">');g.push('<label class="checkbox-inline jstree-preserve-structure">');g.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');g.push("Preserve directory structure");g.push(" </label>");g.push('<label class="checkbox-inline jstree-link-files">');g.push(' <input class="link-checkbox" type="checkbox" value="link_files">');g.push("Link files instead of copying");g.push(" </label>");g.push("</div>");g.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>');g.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>');g.push("</div>");return _.template(g.join(""))},templateAddFilesFromHistory:function(){var g=[];g.push('<div id="add_files_modal">');g.push('<div id="history_modal_combo_bulk">');g.push("Select history: ");g.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');g.push(" <% _.each(histories, function(history) { %>");g.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');g.push(" <% }); %>");g.push("</select>");g.push("</div>");g.push("<br/>");g.push('<div id="selected_history_content">');g.push("</div>");g.push("</div>");return _.template(g.join(""))},templateHistoryContents:function(){var g=[];g.push("<strong>Choose the datasets to import:</strong>");g.push("<ul>");g.push(" <% _.each(history_contents, function(history_item) { %>");g.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');g.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');g.push(" </li>");g.push(" <% }); %>");g.push("</ul>");return _.template(g.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file +define(["galaxy.masthead","utils/utils","libs/toastr","mvc/library/library-model"],function(b,d,e,c){var a=Backbone.View.extend({el:"#center",events:{"click #toolbtn_create_folder":"createFolderFromModal","click #toolbtn_bulk_import":"modalBulkImport","click #include_deleted_datasets_chk":"checkIncludeDeleted","click #toolbtn_show_libinfo":"showLibInfo","click #toolbtn_bulk_delete":"deleteSelectedDatasets"},defaults:{can_add_library_item:false,contains_file:false,chain_call_control:{total_number:0,failed_number:0},disabled_jstree_element:"folders"},modal:null,jstree:null,histories:null,initialize:function(f){this.options=_.defaults(f||{},this.defaults);this.render()},render:function(f){this.options=_.extend(this.options,f);var h=this.templateToolBar();var g={id:this.options.id,is_admin:false,is_anonym:true,user_library_import_dir:Galaxy.config.user_library_import_dir,allow_library_path_paste:Galaxy.config.allow_library_path_paste,library_import_dir:Galaxy.config.library_import_dir,mutiple_add_dataset_options:false};if(Galaxy.currUser){g.is_admin=Galaxy.currUser.isAdmin();g.is_anonym=Galaxy.currUser.isAnonymous();if(g.user_library_import_dir!==null||g.allow_library_path_paste!==false||g.library_import_dir!==null){g.mutiple_add_dataset_options=true}}this.$el.html(h(g))},configureElements:function(f){this.options=_.extend(this.options,f);if(this.options.can_add_library_item===true){$(".add-library-items").show()}else{$(".add-library-items").hide()}if(this.options.contains_file===true){if(Galaxy.currUser){if(!Galaxy.currUser.isAnonymous()){$(".logged-dataset-manipulation").show();$(".dataset-manipulation").show()}else{$(".dataset-manipulation").show();$(".logged-dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}}else{$(".logged-dataset-manipulation").hide();$(".dataset-manipulation").hide()}this.$el.find("[data-toggle]").tooltip()},createFolderFromModal:function(h){h.preventDefault();h.stopPropagation();var f=this;var g=this.templateNewFolderInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Create New Folder",body:g(),buttons:{Create:function(){f.create_new_folder_event()},Close:function(){Galaxy.modal.hide()}}})},create_new_folder_event:function(){var f=this.serialize_new_folder();if(this.validate_new_folder(f)){var g=new c.FolderAsModel();url_items=Backbone.history.fragment.split("/");current_folder_id=url_items[url_items.length-1];g.url=g.urlRoot+"/"+current_folder_id;g.save(f,{success:function(h){Galaxy.modal.hide();e.success("Folder created");h.set({type:"folder"});Galaxy.libraries.folderListView.collection.add(h)},error:function(i,h){Galaxy.modal.hide();if(typeof h.responseJSON!=="undefined"){e.error(h.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})}else{e.error("Folder's name is missing")}return false},serialize_new_folder:function(){return{name:$("input[name='Name']").val(),description:$("input[name='Description']").val()}},validate_new_folder:function(f){return f.name!==""},modalBulkImport:function(){var f=$("#folder_table").find(":checked");if(f.length===0){e.info("You have to select some datasets first")}else{this.refreshUserHistoriesList(function(h){var g=h.templateBulkImportInModal();h.modal=Galaxy.modal;h.modal.show({closing_events:true,title:"Import into History",body:g({histories:h.histories.models}),buttons:{Import:function(){h.importAllIntoHistory()},Close:function(){Galaxy.modal.hide()}}})})}},refreshUserHistoriesList:function(g){var f=this;this.histories=new c.GalaxyHistories();this.histories.fetch({success:function(){g(f)},error:function(i,h){if(typeof h.responseJSON!=="undefined"){e.error(h.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})},importAllIntoHistory:function(){this.modal.disableButton("Import");var j=$("select[name=dataset_import_bulk] option:selected").val();var m=$("select[name=dataset_import_bulk] option:selected").text();this.options.last_used_history_id=j;var g=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){g.push(this.parentElement.parentElement.id)}});var l=[];for(var h=g.length-1;h>=0;h--){var f=g[h];var k=new c.HistoryItem();k.url=k.urlRoot+j+"/contents";k.content=f;k.source="library";l.push(k)}this.initChainCallControl({length:l.length,action:"to_history",history_name:m});jQuery.getJSON(galaxy_config.root+"history/set_as_current?id="+j);this.chainCallImportingIntoHistory(l,m)},updateProgress:function(){this.progress+=this.progressStep;$(".progress-bar-import").width(Math.round(this.progress)+"%");txt_representation=Math.round(this.progress)+"% Complete";$(".completion_span").text(txt_representation)},download:function(f,j){var h=[];$("#folder_table").find(":checked").each(function(){if(this.parentElement.parentElement.id!==""){h.push(this.parentElement.parentElement.id)}});var g="/api/libraries/datasets/download/"+j;var i={ldda_ids:h};this.processDownload(g,i,"get")},processDownload:function(g,h,i){if(g&&h){h=typeof h==="string"?h:$.param(h);var f="";$.each(h.split("&"),function(){var j=this.split("=");f+='<input type="hidden" name="'+j[0]+'" value="'+j[1]+'" />'});$('<form action="'+g+'" method="'+(i||"post")+'">'+f+"</form>").appendTo("body").submit().remove();e.info("Your download will begin soon")}else{e.error("An error occurred :(")}},addFilesFromHistoryModal:function(){this.refreshUserHistoriesList(function(f){f.modal=Galaxy.modal;var g=f.templateAddFilesFromHistory();var h=f.options.full_path[f.options.full_path.length-1][1];f.modal.show({closing_events:true,title:"Adding datasets from your history to folder "+h,body:g({histories:f.histories.models}),buttons:{Add:function(){f.addAllDatasetsFromHistory()},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.back()}});if(f.histories.models.length>0){f.fetchAndDisplayHistoryContents(f.histories.models[0].id);$("#dataset_add_bulk").change(function(i){f.fetchAndDisplayHistoryContents(i.target.value)})}else{e.error("An error ocurred :(")}})},importFilesFromPathModal:function(){var g=this;this.modal=Galaxy.modal;var f=this.templateImportPathModal();this.modal.show({closing_events:true,title:"Enter paths relative to Galaxy root",body:f({}),buttons:{Import:function(){g.importFromPathsClicked(g)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+g.id,{trigger:true})}})},importFilesFromUserdirModal:function(){var g=this;this.modal=Galaxy.modal;var f=this.templateBrowserModal();this.modal.show({closing_events:true,title:"Select folders or files to import",body:f({}),buttons:{Import:function(){g.importFromUserdirClicked(g)},Close:function(){Galaxy.modal.hide()}},closing_callback:function(){Galaxy.libraries.library_router.navigate("folders/"+g.id,{trigger:true})}});this.renderJstree({disabled_jstree_element:"folders"});$("input[type=radio]").change(function(h){if(h.target.value==="jstree-disable-folders"){g.renderJstree({disabled_jstree_element:"folders"});$(".jstree-folders-message").hide();$(".jstree-preserve-structure").hide();$(".jstree-link-files").hide();$(".jstree-files-message").show()}else{if(h.target.value==="jstree-disable-files"){$(".jstree-files-message").hide();$(".jstree-folders-message").show();$(".jstree-link-files").show();$(".jstree-preserve-structure").show();g.renderJstree({disabled_jstree_element:"files"})}}})},renderJstree:function(f){var h=this;this.options=_.extend(this.options,f);var g=this.options.disabled_jstree_element;this.jstree=new c.Jstree();this.jstree.url=this.jstree.urlRoot+"?target=userdir&format=jstree&disable="+g;this.jstree.fetch({success:function(j,i){define("jquery",function(){return jQuery});require(["libs/jquery/jstree"],function(k){$("#jstree_browser").jstree("destroy");$("#jstree_browser").jstree({core:{data:j},plugins:["types","checkbox"],types:{folder:{icon:"jstree-folder"},file:{icon:"jstree-file"}},checkbox:{three_state:false}})})},error:function(j,i){if(typeof i.responseJSON!=="undefined"){e.error(i.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})},importFromPathsClicked:function(){var f=this.modal.$el.find(".preserve-checkbox").is(":checked");var k=this.modal.$el.find(".link-checkbox").is(":checked");var j=$("textarea#import_paths").val();var h=[];if(!j){e.info("Please enter a path relative to Galaxy root")}else{this.modal.disableButton("Import");j=j.split("\n");for(var g=j.length-1;g>=0;g--){trimmed=j[g].trim();if(trimmed.length!==0){h.push(trimmed)}}this.initChainCallControl({length:h.length,action:"adding_datasets"});this.chainCallImportingFolders(h,f,k,"admin_path")}},initChainCallControl:function(f){var g;switch(f.action){case"adding_datasets":g=this.templateAddingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(g({folder_name:this.options.folder_name}));break;case"deleting_datasets":g=this.templateDeletingDatasetsProgressBar();this.modal.$el.find(".modal-body").html(g());break;case"to_history":g=this.templateImportIntoHistoryProgressBar();this.modal.$el.find(".modal-body").html(g({history_name:f.history_name}));break;default:console.error("Wrong action specified.");break}this.progress=0;this.progressStep=100/f.length;this.options.chain_call_control.total_number=f.length;this.options.chain_call_control.failed_number=0},importFromUserdirClicked:function(k){var g=$("#jstree_browser").jstree().get_selected(true);var f=this.modal.$el.find(".preserve-checkbox").is(":checked");var m=this.modal.$el.find(".link-checkbox").is(":checked");var j=g[0].type;var l=[];if(g.length<1){e.info("You have to select some items first")}else{this.modal.disableButton("Import");for(var h=g.length-1;h>=0;h--){if(g[h].li_attr.full_path!==undefined){l.push(g[h].li_attr.full_path)}}this.initChainCallControl({length:l.length,action:"adding_datasets"});if(j==="folder"){this.chainCallImportingFolders(l,f,m,"userdir_folder")}else{if(j==="file"){this.chainCallImportingUserdirFiles(l)}}}},fetchAndDisplayHistoryContents:function(h){var g=new c.HistoryContents({id:h});var f=this;g.fetch({success:function(j){var i=f.templateHistoryContents();f.histories.get(h).set({contents:j});f.modal.$el.find("#selected_history_content").html(i({history_contents:j.models.reverse()}))},error:function(j,i){if(typeof i.responseJSON!=="undefined"){e.error(i.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})},addAllDatasetsFromHistory:function(){var k=this.modal.$el.find("#selected_history_content").find(":checked");var f=[];var j=[];if(k.length<1){e.info("You have to select some datasets first")}else{this.modal.disableButton("Add");k.each(function(){var i=$(this.parentElement).data("id");if(i){f.push(i)}});for(var h=f.length-1;h>=0;h--){history_dataset_id=f[h];var g=new c.Item();g.url="/api/folders/"+this.options.id+"/contents";g.set({from_hda_id:history_dataset_id});j.push(g)}this.initChainCallControl({length:j.length,action:"adding_datasets"});this.chainCallAddingHdas(j)}},chainCallImportingIntoHistory:function(g,j){var f=this;var h=g.pop();if(typeof h=="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets imported into history. Click this to start analysing it.","",{onclick:function(){window.location="/"}})}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were imported into history.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be imported into history. Click this to see what was imported.","",{onclick:function(){window.location="/"}})}}}Galaxy.modal.hide();return true}var i=$.when(h.save({content:h.content,source:h.source}));i.done(function(){f.updateProgress();f.chainCallImportingIntoHistory(g,j)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallImportingIntoHistory(g,j)})},chainCallImportingUserdirFiles:function(i){var f=this;var g=i.pop();if(typeof g==="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected files imported into the current folder");Galaxy.modal.hide()}else{e.error("Something went wrong :(")}return true}var h=$.when($.post("/api/libraries/datasets?encoded_folder_id="+f.id+"&source=userdir_file&path="+g));h.done(function(j){f.updateProgress();f.chainCallImportingUserdirFiles(i)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallImportingUserdirFiles(i)})},chainCallImportingFolders:function(k,f,l,i){var g=this;var h=k.pop();if(typeof h=="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected folders and their contents imported into the current folder");Galaxy.modal.hide()}else{e.error("Something went wrong :(")}return true}var j=$.when($.post("/api/libraries/datasets?encoded_folder_id="+g.id+"&source="+i+"&path="+h+"&preserve_dirs="+f+"&link_data="+l));j.done(function(m){g.updateProgress();g.chainCallImportingFolders(k,f,l,i)}).fail(function(){g.options.chain_call_control.failed_number+=1;g.updateProgress();g.chainCallImportingFolders(k,f,l,i)})},chainCallAddingHdas:function(g){var f=this;this.added_hdas=new c.Folder();var h=g.pop();if(typeof h=="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets from history added to the folder")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were added to the folder.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be added to the folder")}}}Galaxy.modal.hide();return this.added_hdas}var i=$.when(h.save({from_hda_id:h.get("from_hda_id")}));i.done(function(j){Galaxy.libraries.folderListView.collection.add(j);f.updateProgress();f.chainCallAddingHdas(g)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallAddingHdas(g)})},chainCallDeletingHdas:function(g){var f=this;this.deleted_lddas=new c.Folder();var h=g.pop();if(typeof h==="undefined"){if(this.options.chain_call_control.failed_number===0){e.success("Selected datasets deleted")}else{if(this.options.chain_call_control.failed_number===this.options.chain_call_control.total_number){e.error("There was an error and no datasets were deleted.")}else{if(this.options.chain_call_control.failed_number<this.options.chain_call_control.total_number){e.warning("Some of the datasets could not be deleted")}}}Galaxy.modal.hide();return this.deleted_lddas}var i=$.when(h.destroy());i.done(function(k){Galaxy.libraries.folderListView.collection.remove(h.id);f.updateProgress();if(Galaxy.libraries.folderListView.options.include_deleted){var j=new c.Item(k);Galaxy.libraries.folderListView.collection.add(j)}f.chainCallDeletingHdas(g)}).fail(function(){f.options.chain_call_control.failed_number+=1;f.updateProgress();f.chainCallDeletingHdas(g)})},checkIncludeDeleted:function(f){if(f.target.checked){Galaxy.libraries.folderListView.fetchFolder({include_deleted:true})}else{Galaxy.libraries.folderListView.fetchFolder({include_deleted:false})}},deleteSelectedDatasets:function(){var f=$("#folder_table").find(":checked");if(f.length===0){e.info("You have to select some datasets first")}else{var j=this.templateDeletingDatasetsProgressBar();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Deleting selected datasets",body:j({}),buttons:{Close:function(){Galaxy.modal.hide()}}});this.options.chain_call_control.total_number=0;this.options.chain_call_control.failed_number=0;var g=[];f.each(function(){if(this.parentElement.parentElement.id!==""){g.push(this.parentElement.parentElement.id)}});this.progressStep=100/g.length;this.progress=0;var l=[];for(var h=g.length-1;h>=0;h--){var k=new c.Item({id:g[h]});l.push(k)}this.options.chain_call_control.total_number=g.length;this.chainCallDeletingHdas(l)}},showLibInfo:function(){var g=Galaxy.libraries.folderListView.folderContainer.attributes.metadata.parent_library_id;var f=null;var h=this;if(Galaxy.libraries.libraryListView!==null){f=Galaxy.libraries.libraryListView.collection.get(g);this.showLibInfoModal(f)}else{f=new c.Library({id:g});f.fetch({success:function(){h.showLibInfoModal(f)},error:function(j,i){if(typeof i.responseJSON!=="undefined"){e.error(i.responseJSON.err_msg)}else{e.error("An error ocurred :(")}}})}},showLibInfoModal:function(f){var g=this.templateLibInfoInModal();this.modal=Galaxy.modal;this.modal.show({closing_events:true,title:"Library Information",body:g({library:f}),buttons:{Close:function(){Galaxy.modal.hide()}}})},showImportModal:function(f){switch(f.source){case"history":this.addFilesFromHistoryModal();break;case"importdir":break;case"path":this.importFilesFromPathModal();break;case"userdir":this.importFilesFromUserdirModal();break;default:Galaxy.libraries.library_router.back();e.error("Invalid import source.");break}},templateToolBar:function(){tmpl_array=[];tmpl_array.push('<div class="library_style_container">');tmpl_array.push(' <div id="library_toolbar">');tmpl_array.push(" <span><strong>DATA LIBRARIES</strong></span>");tmpl_array.push(' <span data-toggle="tooltip" data-placement="top" class="logged-dataset-manipulation" title="Include deleted datasets" style="display:none;"> | <input id="include_deleted_datasets_chk" style="margin: 0;" type="checkbox"> include deleted | </input></span>');tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Create New Folder" id="toolbtn_create_folder" class="btn btn-default primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-folder"></span></button>');tmpl_array.push("<% if(mutiple_add_dataset_options) { %>");tmpl_array.push(' <div class="btn-group add-library-items" style="display:none;">');tmpl_array.push(' <button title="Add Datasets to Current Folder" id="" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-plus"></span><span class="fa fa-file"></span><span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#folders/<%= id %>/import/history"> from History</a></li>');tmpl_array.push("<% if(user_library_import_dir !== null) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/userdir"> from User Directory</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li class="divider"></li>');tmpl_array.push(' <li class="dropdown-header">Admins only</li>');tmpl_array.push("<% if(allow_library_path_paste) { %>");tmpl_array.push(' <li><a href="#folders/<%= id %>/import/path">from Path</a></li>');tmpl_array.push("<% } %>");tmpl_array.push("<% } %>");tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push("<% } else { %>");tmpl_array.push(' <button style="display:none;" data-toggle="tooltip" data-placement="top" title="Add Datasets to Current Folder" id="toolbtn_add_files" class="btn btn-default toolbtn_add_files primary-button add-library-items" type="button"><span class="fa fa-plus"></span><span class="fa fa-file"></span></span></button>');tmpl_array.push("<% } %>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Import selected datasets into history" id="toolbtn_bulk_import" class="primary-button dataset-manipulation" style="margin-left: 0.5em; display:none;" type="button"><span class="fa fa-book"></span> to History</button>');tmpl_array.push(' <div id="toolbtn_dl" class="btn-group dataset-manipulation" style="margin-left: 0.5em; display:none; ">');tmpl_array.push(' <button title="Download selected datasets as archive" id="drop_toggle" type="button" class="primary-button dropdown-toggle" data-toggle="dropdown">');tmpl_array.push(' <span class="fa fa-download"></span> Download <span class="caret"></span>');tmpl_array.push(" </button>");tmpl_array.push(' <ul class="dropdown-menu" role="menu">');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tgz">.tar.gz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/tbz">.tar.bz</a></li>');tmpl_array.push(' <li><a href="#/folders/<%= id %>/download/zip">.zip</a></li>');tmpl_array.push(" </ul>");tmpl_array.push(" </div>");tmpl_array.push(' <button data-toggle="tooltip" data-placement="top" title="Mark selected datasets deleted" id="toolbtn_bulk_delete" class="primary-button logged-dataset-manipulation" style="margin-left: 0.5em; display:none; " type="button"><span class="fa fa-times"></span> Delete</button>');tmpl_array.push(' <button data-id="<%- id %>" data-toggle="tooltip" data-placement="top" title="Show library information" id="toolbtn_show_libinfo" class="primary-button" style="margin-left: 0.5em;" type="button"><span class="fa fa-info-circle"></span> Library Info</button>');tmpl_array.push(' <span class="help-button" data-toggle="tooltip" data-placement="top" title="Visit Libraries Wiki"><a href="https://wiki.galaxyproject.org/DataLibraries/screen/FolderContents" target="_blank"><button class="primary-button btn-xs" type="button"><span class="fa fa-question-circle"></span> Help</button></a></span>');tmpl_array.push(" </div>");tmpl_array.push(' <div id="folder_items_element">');tmpl_array.push(" </div>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateLibInfoInModal:function(){tmpl_array=[];tmpl_array.push('<div id="lif_info_modal">');tmpl_array.push("<h2>Library name:</h2>");tmpl_array.push('<p><%- library.get("name") %></p>');tmpl_array.push("<h3>Library description:</h3>");tmpl_array.push('<p><%- library.get("description") %></p>');tmpl_array.push("<h3>Library synopsis:</h3>");tmpl_array.push('<p><%- library.get("synopsis") %></p>');tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateNewFolderInModal:function(){tmpl_array=[];tmpl_array.push('<div id="new_folder_modal">');tmpl_array.push("<form>");tmpl_array.push('<input type="text" name="Name" value="" placeholder="Name">');tmpl_array.push('<input type="text" name="Description" value="" placeholder="Description">');tmpl_array.push("</form>");tmpl_array.push("</div>");return _.template(tmpl_array.join(""))},templateBulkImportInModal:function(){var f=[];f.push('<span id="history_modal_combo_bulk" style="width:90%; margin-left: 1em; margin-right: 1em; ">');f.push("Select history: ");f.push('<select id="dataset_import_bulk" name="dataset_import_bulk" style="width:50%; margin-bottom: 1em; "> ');f.push(" <% _.each(histories, function(history) { %>");f.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');f.push(" <% }); %>");f.push("</select>");f.push("</span>");return _.template(f.join(""))},templateImportIntoHistoryProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("Importing selected datasets to history <b><%= _.escape(history_name) %></b>");f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateAddingDatasetsProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("Adding selected datasets to library folder <b><%= _.escape(folder_name) %></b>");f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateDeletingDatasetsProgressBar:function(){var f=[];f.push('<div class="import_text">');f.push("</div>");f.push('<div class="progress">');f.push(' <div class="progress-bar progress-bar-import" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">');f.push(' <span class="completion_span">0% Complete</span>');f.push(" </div>");f.push("</div>");f.push("");return _.template(f.join(""))},templateBrowserModal:function(){var f=[];f.push('<div id="file_browser_modal">');f.push('<div style="margin-bottom:1em;">');f.push('<label class="radio-inline">');f.push(' <input title="Switch to selecting files" type="radio" name="jstree-radio" value="jstree-disable-folders" checked="checked"> Files');f.push("</label>");f.push('<label class="radio-inline">');f.push(' <input title="Switch to selecting folders" type="radio" name="jstree-radio" value="jstree-disable-files"> Folders');f.push("</label>");f.push('<label class="checkbox-inline jstree-preserve-structure" style="display:none;">');f.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');f.push("Preserve directory structure");f.push(" </label>");f.push('<label class="checkbox-inline jstree-link-files" style="display:none;">');f.push(' <input class="link-checkbox" type="checkbox" value="link_files">');f.push("Link files instead of copying");f.push(" </label>");f.push("</div>");f.push('<div class="alert alert-info jstree-files-message">All files you select will be imported into the current folder.</div>');f.push('<div class="alert alert-info jstree-folders-message" style="display:none;">All files within the selected folders and their subfolders will be imported into the current folder.</div>');f.push('<div id="jstree_browser">');f.push("</div>");f.push("</div>");return _.template(f.join(""))},templateImportPathModal:function(){var f=[];f.push('<div id="file_browser_modal">');f.push('<label class="checkbox-inline jstree-preserve-structure">');f.push(' <input class="preserve-checkbox" type="checkbox" value="preserve_directory_structure">');f.push("Preserve directory structure");f.push(" </label>");f.push('<label class="checkbox-inline jstree-link-files">');f.push(' <input class="link-checkbox" type="checkbox" value="link_files">');f.push("Link files instead of copying");f.push(" </label>");f.push("</div>");f.push('<div class="alert alert-info jstree-folders-message">All files within the given folders and their subfolders will be imported into the current folder.</div>');f.push('<textarea id="import_paths" class="form-control" rows="5" placeholder="Paths separated by newline"></textarea>');f.push("</div>");return _.template(f.join(""))},templateAddFilesFromHistory:function(){var f=[];f.push('<div id="add_files_modal">');f.push('<div id="history_modal_combo_bulk">');f.push("Select history: ");f.push('<select id="dataset_add_bulk" name="dataset_add_bulk" style="width:66%; "> ');f.push(" <% _.each(histories, function(history) { %>");f.push(' <option value="<%= _.escape(history.get("id")) %>"><%= _.escape(history.get("name")) %></option>');f.push(" <% }); %>");f.push("</select>");f.push("</div>");f.push("<br/>");f.push('<div id="selected_history_content">');f.push("</div>");f.push("</div>");return _.template(f.join(""))},templateHistoryContents:function(){var f=[];f.push("<strong>Choose the datasets to import:</strong>");f.push("<ul>");f.push(" <% _.each(history_contents, function(history_item) { %>");f.push(' <li data-id="<%= _.escape(history_item.get("id")) %>">');f.push(' <input style="margin: 0;" type="checkbox"><%= _.escape(history_item.get("hid")) %>: <%= _.escape(history_item.get("name")) %>');f.push(" </li>");f.push(" <% }); %>");f.push("</ul>");return _.template(f.join(""))}});return{FolderToolbarView:a}}); \ No newline at end of file diff -r aec146e3828b16812ca24c5f8651ba3d0d483a6a -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 templates/webapps/galaxy/galaxy.panels.mako --- a/templates/webapps/galaxy/galaxy.panels.mako +++ b/templates/webapps/galaxy/galaxy.panels.mako @@ -32,7 +32,6 @@ 'libs/jquery/jquery', 'libs/jquery/jquery-ui', "libs/jquery/select2", - "libs/jquery/jstree", 'libs/bootstrap', 'libs/underscore', 'libs/backbone/backbone', https://bitbucket.org/galaxy/galaxy-central/commits/c059c1061efa/ Changeset: c059c1061efa User: martenson Date: 2014-09-16 22:03:05+00:00 Summary: Merge Affected #: 7 files diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 client/GruntFile.js --- a/client/GruntFile.js +++ b/client/GruntFile.js @@ -2,8 +2,10 @@ // Project configuration. grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), + pkg: grunt.file.readJSON( 'package.json' ), + // default task + // use 'grunt copy' to copy the entire <galaxy>/client/galaxy/scripts dir into <galaxy>/static/scripts copy: { main: { expand: true, @@ -11,11 +13,18 @@ src: '**', dest: '../static/scripts/' } + }, + + // use 'grunt watch' (from a new tab in your terminal) to have grunt re-copy changed files automatically + watch: { + // watch for changes in the src dir + files: [ 'galaxy/scripts/**' ], + tasks: [ 'default' ] } - }); - grunt.loadNpmTasks('grunt-contrib-copy'); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-copy'); - grunt.registerTask('default', ['copy']); + grunt.registerTask( 'default', [ 'copy' ] ); }; diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 client/package.json --- a/client/package.json +++ b/client/package.json @@ -6,6 +6,8 @@ "galaxy" ], "devDependencies": { - "grunt-contrib-copy": "^0.5.0" + "grunt": "^0.4.5", + "grunt-contrib-copy": "^0.5.0", + "grunt-contrib-watch": "^0.6.1" } } diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 lib/galaxy/config.py --- a/lib/galaxy/config.py +++ b/lib/galaxy/config.py @@ -137,7 +137,6 @@ self.collect_outputs_from = [ x.strip() for x in kwargs.get( 'collect_outputs_from', 'new_file_path,job_working_directory' ).lower().split(',') ] self.template_path = resolve_path( kwargs.get( "template_path", "templates" ), self.root ) self.template_cache = resolve_path( kwargs.get( "template_cache_path", "database/compiled_templates" ), self.root ) - self.dependency_resolvers_config_file = resolve_path( kwargs.get( 'dependency_resolvers_config_file', 'dependency_resolvers_conf.xml' ), self.root ) self.local_job_queue_workers = int( kwargs.get( "local_job_queue_workers", "5" ) ) self.cluster_job_queue_workers = int( kwargs.get( "cluster_job_queue_workers", "3" ) ) self.job_queue_cleanup_interval = int( kwargs.get("job_queue_cleanup_interval", "5") ) @@ -384,6 +383,7 @@ external_service_type_config_file = [ 'external_service_types_conf.xml', 'config/external_service_types_conf.xml.sample', 'config/external_service_types_conf.xml.sample' ], job_config_file = [ 'job_conf.xml', 'config/job_conf.xml' ], job_metrics_config_file = [ 'job_metrics_conf.xml', 'config/job_metrics_conf.xml' ], + dependency_resolvers_config_file = [ 'dependency_resolvers_conf.xml', 'config/dependency_resolvers_conf.xml' ], job_resource_params_file = [ 'job_resource_params_conf.xml', 'config/job_resource_params_conf.xml' ], migrated_tools_config = [ 'migrated_tools_conf.xml', 'config/migrated_tools_conf.xml' ], object_store_config_file = [ 'object_store_conf.xml', 'config/object_store_conf.xml' ], diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 static/scripts/mvc/ui/ui-checkbox.js --- /dev/null +++ b/static/scripts/mvc/ui/ui-checkbox.js @@ -0,0 +1,91 @@ +// dependencies +define(['utils/utils'], function(Utils) { + +// plugin +var View = Backbone.View.extend({ + // options + optionsDefault: { + value : '', + visible : true, + cls : '', + data : [], + id : Utils.uuid() + }, + + // initialize + initialize : function(options) { + // configure options + this.options = Utils.merge(options, this.optionsDefault); + + // create new element + this.setElement(this._template(this.options)); + + // hide input field + if (!this.options.visible) { + this.$el.hide(); + } + + // set initial value + if (this.options.value) { + this.value(this.options.value); + } + + // current value + this.current = this.options.value; + + // onchange event handler. fires on user activity. + var self = this; + this.$el.find('input').on('change', function() { + self.value(self._getValue()); + }); + }, + + // value + value : function (new_val) { + // get current value + var before = this.current; + + // set new value + if (new_val !== undefined) { + this.$el.find('label').removeClass('active'); + this.$el.find('[value="' + new_val + '"]').closest('label').addClass('active'); + this.current = new_val; + } + + // check value + var after = this.current; + if (after != before && this.options.onchange) { + this.options.onchange(this.current); + } + + // get and return value + return this.current; + }, + + // get value + _getValue: function() { + var selected = this.$el.find(':checked'); + var value = null; + if (selected.length > 0) { + value = selected.val(); + } + return value; + }, + + // element + _template: function(options) { + var tmpl = '<div class="ui-checkbox">'; + for (key in options.data) { + var pair = options.data[key]; + tmpl += '<input type="checkbox" name="' + options.id + '" value="' + pair.value + '" selected>' + pair.label + '<br>'; + } + tmpl += '</div>'; + return tmpl; + } +}); + +return { + View : View +}; + +}); diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 static/scripts/mvc/ui/ui-radiobutton.js --- /dev/null +++ b/static/scripts/mvc/ui/ui-radiobutton.js @@ -0,0 +1,93 @@ +// dependencies +define(['utils/utils'], function(Utils) { + +// plugin +var View = Backbone.View.extend({ + // options + optionsDefault: { + value : '', + visible : true, + cls : '', + data : [], + id : Utils.uuid() + }, + + // initialize + initialize : function(options) { + // configure options + this.options = Utils.merge(options, this.optionsDefault); + + // create new element + this.setElement(this._template(this.options)); + + // hide input field + if (!this.options.visible) { + this.$el.hide(); + } + + // set initial value + if (this.options.value) { + this.value(this.options.value); + } + + // current value + this.current = this.options.value; + + // onchange event handler. fires on user activity. + var self = this; + this.$el.find('input').on('change', function() { + self.value(self._getValue()); + }); + }, + + // value + value : function (new_val) { + // get current value + var before = this.current; + + // set new value + if (new_val !== undefined) { + this.$el.find('label').removeClass('active'); + this.$el.find('[value="' + new_val + '"]').closest('label').addClass('active'); + this.current = new_val; + } + + // check value + var after = this.current; + if (after != before && this.options.onchange) { + this.options.onchange(this.current); + } + + // get and return value + return this.current; + }, + + // get value + _getValue: function() { + var selected = this.$el.find(':checked'); + var value = null; + if (selected.length > 0) { + value = selected.val(); + } + return value; + }, + + // element + _template: function(options) { + var tmpl = '<div class="btn-group ui-radiobutton" data-toggle="buttons">'; + for (key in options.data) { + var pair = options.data[key]; + tmpl += '<label class="btn btn-default">' + + '<input type="radio" name="' + options.id + '" value="' + pair.value + '" selected>' + pair.label + + '</label>'; + } + tmpl += '</div>'; + return tmpl; + } +}); + +return { + View : View +}; + +}); diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 static/scripts/packed/mvc/ui/ui-checkbox.js --- /dev/null +++ b/static/scripts/packed/mvc/ui/ui-checkbox.js @@ -0,0 +1,1 @@ +define(["utils/utils"],function(a){var b=Backbone.View.extend({optionsDefault:{value:"",visible:true,cls:"",data:[],id:a.uuid()},initialize:function(d){this.options=a.merge(d,this.optionsDefault);this.setElement(this._template(this.options));if(!this.options.visible){this.$el.hide()}if(this.options.value){this.value(this.options.value)}this.current=this.options.value;var c=this;this.$el.find("input").on("change",function(){c.value(c._getValue())})},value:function(c){var d=this.current;if(c!==undefined){this.$el.find("label").removeClass("active");this.$el.find('[value="'+c+'"]').closest("label").addClass("active");this.current=c}var e=this.current;if(e!=d&&this.options.onchange){this.options.onchange(this.current)}return this.current},_getValue:function(){var c=this.$el.find(":checked");var d=null;if(c.length>0){d=c.val()}return d},_template:function(d){var c='<div class="ui-checkbox">';for(key in d.data){var e=d.data[key];c+='<input type="checkbox" name="'+d.id+'" value="'+e.value+'" selected>'+e.label+"<br>"}c+="</div>";return c}});return{View:b}}); \ No newline at end of file diff -r f163dd7c2ccdd908b4f1f4e30defbbd20ee0da58 -r c059c1061efa625d6ad1ff2fc298db03b01e2c61 static/scripts/packed/mvc/ui/ui-radiobutton.js --- /dev/null +++ b/static/scripts/packed/mvc/ui/ui-radiobutton.js @@ -0,0 +1,1 @@ +define(["utils/utils"],function(a){var b=Backbone.View.extend({optionsDefault:{value:"",visible:true,cls:"",data:[],id:a.uuid()},initialize:function(d){this.options=a.merge(d,this.optionsDefault);this.setElement(this._template(this.options));if(!this.options.visible){this.$el.hide()}if(this.options.value){this.value(this.options.value)}this.current=this.options.value;var c=this;this.$el.find("input").on("change",function(){c.value(c._getValue())})},value:function(c){var d=this.current;if(c!==undefined){this.$el.find("label").removeClass("active");this.$el.find('[value="'+c+'"]').closest("label").addClass("active");this.current=c}var e=this.current;if(e!=d&&this.options.onchange){this.options.onchange(this.current)}return this.current},_getValue:function(){var c=this.$el.find(":checked");var d=null;if(c.length>0){d=c.val()}return d},_template:function(d){var c='<div class="btn-group ui-radiobutton" data-toggle="buttons">';for(key in d.data){var e=d.data[key];c+='<label class="btn btn-default"><input type="radio" name="'+d.id+'" value="'+e.value+'" selected>'+e.label+"</label>"}c+="</div>";return c}});return{View:b}}); \ No newline at end of file https://bitbucket.org/galaxy/galaxy-central/commits/7ddb0d7b4b12/ Changeset: 7ddb0d7b4b12 User: jmchilton Date: 2014-09-17 01:40:35+00:00 Summary: Merged in martenson/galaxy-central-marten (pull request #497) importing into library folders from Galaxy filesystem Affected #: 37 files diff -r 38be704a932fafd27b01034ae9daf83a465062bf -r 7ddb0d7b4b128089322b441c77eceaea5d993312 client/galaxy/scripts/galaxy.library.js --- a/client/galaxy/scripts/galaxy.library.js +++ b/client/galaxy/scripts/galaxy.library.js @@ -47,7 +47,8 @@ "folders/:folder_id/datasets/:dataset_id" : "dataset_detail", "folders/:folder_id/datasets/:dataset_id/permissions" : "dataset_permissions", "folders/:folder_id/datasets/:dataset_id/versions/:ldda_id" : "dataset_version", - "folders/:folder_id/download/:format" : "download" + "folders/:folder_id/download/:format" : "download", + "folders/:folder_id/import/:source" : "import_datasets" }, back: function() { @@ -147,6 +148,15 @@ } Galaxy.libraries.folderView = new mod_library_folder_view.FolderView({id: folder_id, show_permissions: true}); }); + this.library_router.on('route:import_datasets', function(folder_id, source){ + if (Galaxy.libraries.folderToolbarView && Galaxy.libraries.folderListView){ + Galaxy.libraries.folderToolbarView.showImportModal({source:source}); + } else { + Galaxy.libraries.folderToolbarView = new mod_foldertoolbar_view.FolderToolbarView({id: folder_id}); + Galaxy.libraries.folderListView = new mod_folderlist_view.FolderListView({id: folder_id}); + Galaxy.libraries.folderToolbarView.showImportModal({source: source}); + } + }); Backbone.history.start({pushState: false}); } This diff is so big that we needed to truncate the remainder. Repository URL: https://bitbucket.org/galaxy/galaxy-central/ -- This is a commit notification from bitbucket.org. You are receiving this because you have the service enabled, addressing the recipient of this email.