Esempio n. 1
0
    def delete(self):
        QtGui.QMessageBox.critical(self, "Delete",
                                   "This feature is not functional in the "
                                   "current version of VisTrails and has been "
                                   "disabled for this release.")
        return

        from init import PersistentPath
        info_list = self.ref_search.ref_widget.get_info_list()
        if len(info_list) < 1:
            return

        delete_str = "This will permanently delete the selected data " + \
            "from the peristent store.  This cannot be undone.  Proceed?"
        question_f = QtGui.QMessageBox.question
        ret_val = question_f(self, "Delete", delete_str, \
                                 QtGui.QMessageBox.Cancel | \
                                 QtGui.QMessageBox.Ok)
        if ret_val != QtGui.QMessageBox.Ok:
            return
            
        git_util = PersistentPath()
        db_access = DatabaseAccessSingleton()
        # FIXME keep entry in database with flag for deleted?
        # NEED TO update the model...
        for info in info_list:
            delete_where = {'id': info[0]}
            if info[1] is None:
                git_util.git_remove_path(info[0])
                db_access.delete_from_database(delete_where)
            else:
                # FIXME implement delete for versions...
                delete_where['version'] = info[1]
                print "NOT IMPLEMENTED FOR VERSIONS!!"
Esempio n. 2
0
    def delete(self):
        from init import PersistentPath
        info_list = self.ref_search.ref_widget.get_info_list()
        if len(info_list) < 1:
            return

        delete_str = "This will permanently delete the selected data " + \
            "from the peristent store.  This cannot be undone.  Proceed?"
        question_f = QtGui.QMessageBox.question
        ret_val = question_f(self, "Delete", delete_str, \
                                 QtGui.QMessageBox.Cancel | \
                                 QtGui.QMessageBox.Ok)
        if ret_val != QtGui.QMessageBox.Ok:
            return

        git_util = PersistentPath()
        db_access = DatabaseAccessSingleton()
        # FIXME keep entry in database with flag for deleted?
        # NEED TO update the model...
        for info in info_list:
            delete_where = {'id': info[0]}
            if info[1] is None:
                git_util.git_remove_path(info[0])
                db_access.delete_from_database(delete_where)
            else:
                # FIXME implement delete for versions...
                delete_where['version'] = info[1]
                print "NOT IMPLEMENTED FOR VERSIONS!!"
Esempio n. 3
0
    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.cols = {
            0: "name",
            1: "tags",
            2: "user",
            3: "date_created",
            4: "date_modified",
            5: "id",
            6: "version",
            7: "content_hash",
            8: "signature",
            9: "type"
        }
        self.idxs = dict((v, k) for (k, v) in self.cols.iteritems())
        self.headers = {
            "id": "ID",
            "name": "Name",
            "tags": "Tags",
            "user": "******",
            "date_created": "Date Created",
            "date_modified": "Date Modified",
            "content_hash": "Content Hash",
            "version": "Version",
            "signature": "Signature"
        }

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.file_idxs = set()
        self.dir_idxs = set()
        for i, key in enumerate(self.id_lists_keys):
            if self.id_lists[key][0][self.idxs["type"]] == "blob":
                self.file_idxs.add(i)
            elif self.id_lists[key][0][self.idxs["type"]] == "tree":
                self.dir_idxs.add(i)

        print 'file:', self.file_idxs
        print 'dir:', self.dir_idxs
        self.integer_wrappers = {}
Esempio n. 4
0
    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])
        rows = map(self.fix_dates, rows)

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.integer_wrappers = {}
Esempio n. 5
0
def initialize():
    global global_db, local_db, search_dbs, compress_by_default, db_access, \
        git_bin, debug

    if configuration.check('git_bin'):
        git_bin = configuration.git_bin
    if git_bin.startswith("@executable_path/"):
        non_expand_path = git_bin
        git_bin = get_executable_path(git_bin[len("@executable_path/"):])
        if git_bin is not None:
            configuration.git_bin = non_expand_path
    if git_bin is None:
        git_bin = 'git'
        configuration.git_bin = git_bin

    if configuration.check('compress_by_default'):
        compress_by_default = configuration.compress_by_default
    if configuration.check('debug'):
        debug = configuration.debug
    if configuration.check('global_db'):
        global_db = configuration.global_db
    if configuration.check('local_db'):
        local_db = configuration.local_db
        if not os.path.exists(local_db):
            raise RuntimeError('local_db "%s" does not exist' % local_db)
    else:
        local_db = os.path.join(current_dot_vistrails(), 'persistent_files')
        if not os.path.exists(local_db):
            try:
                os.mkdir(local_db)
            except OSError:
                raise RuntimeError('local_db "%s" does not exist' % local_db)

    local_repo = repo.get_repo(local_db)
    repo.set_current_repo(local_repo)

    debug_print('creating DatabaseAccess')
    db_path = os.path.join(local_db, '.files.db')
    db_access = DatabaseAccessSingleton(db_path)
    debug_print('done', db_access)

    search_dbs = [
        local_db,
    ]
    if configuration.check('search_dbs'):
        try:
            check_paths = literal_eval(configuration.search_dbs)
        except Exception:
            print "*** persistence error: cannot parse search_dbs ***"
        else:
            for path in check_paths:
                if os.path.exists(path):
                    search_dbs.append(path)
                else:
                    print '*** persistence warning: cannot find path "%s"' % path
    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.cols = {
            0: "name",
            1: "tags",
            2: "user",
            3: "date_created",
            4: "date_modified",
            5: "id",
            6: "version",
            7: "content_hash",
            8: "signature",
            9: "type",
        }
        self.idxs = dict((v, k) for (k, v) in self.cols.iteritems())
        self.headers = {
            "id": "ID",
            "name": "Name",
            "tags": "Tags",
            "user": "******",
            "date_created": "Date Created",
            "date_modified": "Date Modified",
            "content_hash": "Content Hash",
            "version": "Version",
            "signature": "Signature",
        }

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database([c[1] for c in sorted(self.cols.iteritems())])

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs["id"]] not in self.id_lists:
                self.id_lists[ref[self.idxs["id"]]] = []
            self.id_lists[ref[self.idxs["id"]]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.file_idxs = set()
        self.dir_idxs = set()
        for i, key in enumerate(self.id_lists_keys):
            if self.id_lists[key][0][self.idxs["type"]] == "blob":
                self.file_idxs.add(i)
            elif self.id_lists[key][0][self.idxs["type"]] == "tree":
                self.dir_idxs.add(i)

        print "file:", self.file_idxs
        print "dir:", self.dir_idxs
        self.integer_wrappers = {}
Esempio n. 7
0
    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])
        rows = map(self.fix_dates, rows)

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.integer_wrappers = {}
Esempio n. 8
0
class PersistentRefModel(QtCore.QAbstractItemModel):

    _instance = None

    # 2013-09-03 18:57:53.133000
    _DATE_FORMAT = re.compile(r'^(?P<y>[0-9]{4})-'
                              r'(?P<m>[0-9]{2})-'
                              r'(?P<d>[0-9]{2}) '
                              r'(?P<H>[0-9]{2}):'
                              r'(?P<M>[0-9]{2}):'
                              r'(?P<S>[0-9]{2}).'
                              r'(?P<ms>[0-9]+)$')

    cols = {0: "name",
            1: "type",
            2: "tags",
            3: "user",
            4: "date_created",
            5: "date_modified",
            6: "id",
            7: "version",
            8: "content_hash",
            9: "signature"}
    idxs = dict((v,k) for (k,v) in cols.iteritems())
    headers = {"id": "ID",
               "name": "Name",
               "tags": "Tags",
               "user": "******",
               "date_created": "Date Created",
               "date_modified": "Date Modified",
               "content_hash": "Content Hash",
               "version": "Version",
               "signature": "Signature",
               "type": "Type"}

    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])
        rows = map(self.fix_dates, rows)

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.integer_wrappers = {}

    @staticmethod
    def fix_dates(row):
        row = list(row)
        for c in ('date_created', 'date_modified'):
            c = PersistentRefModel.idxs[c]
            m = PersistentRefModel._DATE_FORMAT.match(row[c])
            if m is not None:
                row[c] = '{y}-{m}-{d} {H}:{M}'.format(**m.groupdict())
        return tuple(row)

    def rowCount(self, parent=QtCore.QModelIndex()):
        if not parent.isValid():
            # print 'rowCount:', len(self.id_lists_keys)
            return len(self.id_lists_keys)
        # print 'parentValid rowCount:', \
        #     len(self.id_lists[self.id_lists_keys[parent.row()]])
        return len(self.id_lists[self.id_lists_keys[parent.row()]])
 
    def columnCount(self, parent=QtCore.QModelIndex()):
        # print 'columnCount:', len(self.headers)
        return len(self.headers)
    
    def hasChildren(self, parent=QtCore.QModelIndex()):
        # print 'hasChildren:'
        if not parent.isValid():
            # print '  True'
            return True
        else:
            # print '  PARENT:', parent.row(), parent.column(), \
            #     parent.internalPointer()
            if not parent.parent().isValid():
                # print '  TRUE'
                return True
        # print '  False'
        return False

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return None
        if section in self.cols:
            return self.headers[self.cols[section]]
        return None
    
    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return None
        # if index.parent().isValid():
        #     print 'data', index.row(), index.column(), index.parent().row()
        if index.parent().isValid():
            # have a child node
            # print 'got child node!', index.parent().row()
            id_list = self.id_lists[self.id_lists_keys[index.parent().row()]]
            data = id_list[index.row()]
        else:
            # have a parent node    
            id_list = self.id_lists[self.id_lists_keys[index.row()]]
            data = id_list[0]
            # want to have the earliest created date and latest modified date
            if index.column() == self.idxs['date_created']:
                dates = [l[index.column()] for l in id_list]
                return min(dates)
            if index.column() == self.idxs['date_modified']:
                dates = [l[index.column()] for l in id_list]
                return max(dates)
            if index.column() == self.idxs['version'] or \
                    index.column() == self.idxs['signature'] or \
                    index.column() == self.idxs['content_hash'] or \
                    index.column() == self.idxs['user']:
                return None

        if index.column() < len(data):
            return data[index.column()]
        return None
    
    def parent(self, index):
        # print 'calling parent() method'
        if index.isValid():
            # print '  index is valid', index.row(), index.column()
            if index.internalPointer():
                parent_item = index.internalPointer().idx
                # print '  parent_item:', parent_item
                return self.createIndex(parent_item, 0, None)
#             else:
#                 # print '  internalPointer is not valid'
#         else:
#             # print 'index not valid for parent call'
        return QtCore.QModelIndex()

    def index(self, row, column, parent):
        # print 'index:', row, column
        if not parent.isValid():
            if len(self.id_lists_keys) > row:
                # print '  no parent item'
                return self.createIndex(row, column, None)
        else:
            # print '  **** parent_item', row, column, parent.row()
            if len(self.id_lists[self.id_lists_keys[parent.row()]]) > row:
                # print '  ++++ creating index'
                # !!! internalPointer is a weakref in PyQt !!!
                if parent.row() not in self.integer_wrappers:
                    integer_wrapper = IntegerWrapper(parent.row())
                    self.integer_wrappers[parent.row()] = integer_wrapper
                else:
                    integer_wrapper = self.integer_wrappers[parent.row()]
                # print '  ---- created parent wrapper'
                return self.createIndex(row, column, integer_wrapper)
        return QtCore.QModelIndex()

    def sort(self, column, order=QtCore.Qt.AscendingOrder):
        self.emit(QtCore.SIGNAL('layoutAboutToBeChanged()'))
        if column == -1:
            return
        self.id_lists_keys.sort(key=lambda x: self.id_lists[x][0][column], 
                                reverse=(order==QtCore.Qt.AscendingOrder))
        self.emit(QtCore.SIGNAL('layoutChanged()'))

    def find_row(self, id, version=None):
        if id in self.id_lists:
            i = self.id_lists_keys.index(id)
            if version is not None:
                for j, data in enumerate(self.id_lists[id]):
                    if data[self.idxs['version']] == version:
                        if i not in self.integer_wrappers:
                            integer_wrapper = IntegerWrapper(i)
                            self.integer_wrappers[i] = integer_wrapper
                        else:
                            integer_wrapper = self.integer_wrappers[i]
                        return self.createIndex(j, 0, integer_wrapper)
            return self.createIndex(i, 0, 0)
#             for i, id in enumerate(self.id_lists_keys):
            
#             if version is not None:
#                 for data in enumerate(self.id_lists[id]):
#                     if
#         for i, data in enumerate(self.id_lists):
#             if data[self.idxs['id']] == id and \
#                     (not version or data[self.idxs['version']] == version):
#                 return self.createIndex(i, 0, 0)
        return QtCore.QModelIndex()

    def add_data(self, value_dict):
        id = value_dict['id']
        value_list = []
        for _, c in sorted(self.cols.iteritems()):
            if c in value_dict:
                value_list.append(str(value_dict[c]))
            else:
                value_list.append(None)
        if id not in self.id_lists:
            self.id_lists[id] = []
            self.id_lists_keys.append(id)
        self.id_lists[id].append(self.fix_dates(value_list))
        self.reset()

    def remove_data(self, where_dict):
        id = where_dict['id']
        version = where_dict.get('version', None)
        if version is not None:
            for idx, value_tuple in enumerate(self.id_lists[id]):
                if value_tuple[self.idxs['version']] == version:
                    del self.id_lists[id][idx]
                    break
        else:
            path_type = self.id_lists[id][0][self.idxs['type']]
            for idx, key_id in enumerate(self.id_lists_keys):
                if key_id == id:
                    del self.id_lists_keys[idx]
                    break
            del self.id_lists[id]
        self.reset()
Esempio n. 9
0
class ManagedRefModel(QtCore.QAbstractItemModel):

    _instance = None

    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.cols = {
            0: "name",
            1: "tags",
            2: "user",
            3: "date_created",
            4: "date_modified",
            5: "id",
            6: "version",
            7: "content_hash",
            8: "signature",
            9: "type"
        }
        self.idxs = dict((v, k) for (k, v) in self.cols.iteritems())
        self.headers = {
            "id": "ID",
            "name": "Name",
            "tags": "Tags",
            "user": "******",
            "date_created": "Date Created",
            "date_modified": "Date Modified",
            "content_hash": "Content Hash",
            "version": "Version",
            "signature": "Signature"
        }

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.file_idxs = set()
        self.dir_idxs = set()
        for i, key in enumerate(self.id_lists_keys):
            if self.id_lists[key][0][self.idxs["type"]] == "blob":
                self.file_idxs.add(i)
            elif self.id_lists[key][0][self.idxs["type"]] == "tree":
                self.dir_idxs.add(i)

        print 'file:', self.file_idxs
        print 'dir:', self.dir_idxs
        self.integer_wrappers = {}

    def rowCount(self, parent=QtCore.QModelIndex()):
        if not parent.isValid():
            # print 'rowCount:', len(self.id_lists_keys)
            return len(self.id_lists_keys)
        # print 'parentValid rowCount:', \
        #     len(self.id_lists[self.id_lists_keys[parent.row()]])
        return len(self.id_lists[self.id_lists_keys[parent.row()]])

    def columnCount(self, parent=QtCore.QModelIndex()):
        # print 'columnCount:', len(self.headers)
        return len(self.headers)

    def hasChildren(self, parent=QtCore.QModelIndex()):
        # print 'hasChildren:'
        if not parent.isValid():
            # print '  True'
            return True
        else:
            # print '  PARENT:', parent.row(), parent.column(), \
            #     parent.internalPointer()
            if not parent.parent().isValid():
                # print '  TRUE'
                return True
        # print '  False'
        return False

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if section in self.cols:
            return QtCore.QVariant(self.headers[self.cols[section]])
        return QtCore.QVariant()

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        # if index.parent().isValid():
        #     print 'data', index.row(), index.column(), index.parent().row()
        if index.parent().isValid():
            # have a child node
            # print 'got child node!', index.parent().row()
            id_list = self.id_lists[self.id_lists_keys[index.parent().row()]]
            data = id_list[index.row()]
        else:
            # have a parent node
            # want to have the earliest created date and latest modified date
            id_list = self.id_lists[self.id_lists_keys[index.row()]]
            data = id_list[0]
            if index.column() == self.idxs['version'] or \
                    index.column() == self.idxs['signature'] or \
                    index.column() == self.idxs['content_hash'] or \
                    index.column() == self.idxs['date_created'] or \
                    index.column() == self.idxs['date_modified'] or \
                    index.column() == self.idxs['user']:
                return QtCore.QVariant()

        if index.column() < len(data):
            return QtCore.QVariant(data[index.column()])
        return QtCore.QVariant()

    def parent(self, index):
        # print 'calling parent() method'
        if index.isValid():
            # print '  index is valid', index.row(), index.column()
            if index.internalPointer():
                parent_item = index.internalPointer().idx
                # print '  parent_item:', parent_item
                return self.createIndex(parent_item, 0, None)
#             else:
#                 # print '  internalPointer is not valid'
#         else:
#             # print 'index not valid for parent call'
        return QtCore.QModelIndex()

    def index(self, row, column, parent):
        # print 'index:', row, column
        if not parent.isValid():
            if len(self.id_lists_keys) > row:
                # print '  no parent item'
                return self.createIndex(row, column, None)
        else:
            # print '  **** parent_item', row, column, parent.row()
            if len(self.id_lists[self.id_lists_keys[parent.row()]]) > row:
                # print '  ++++ creating index'
                # !!! internalPointer is a weakref in PyQt !!!
                if parent.row() not in self.integer_wrappers:
                    integer_wrapper = IntegerWrapper(parent.row())
                    self.integer_wrappers[parent.row()] = integer_wrapper
                else:
                    integer_wrapper = self.integer_wrappers[parent.row()]
                # print '  ---- created parent wrapper'
                return self.createIndex(row, column, integer_wrapper)
        return QtCore.QModelIndex()

    def sort(self, column, order=QtCore.Qt.AscendingOrder):
        self.emit(QtCore.SIGNAL('layoutAboutToBeChanged()'))
        if column == -1:
            return
        self.id_lists_keys.sort(key=lambda x: self.id_lists[x][0][column],
                                reverse=(order == QtCore.Qt.AscendingOrder))
        self.emit(QtCore.SIGNAL('layoutChanged()'))

    def find_row(self, id, version=None):
        if id in self.id_lists:
            i = self.id_lists_keys.index(id)
            if version is not None:
                for j, data in enumerate(self.id_lists[id]):
                    if data[self.idxs['version']] == version:
                        if i not in self.integer_wrappers:
                            integer_wrapper = IntegerWrapper(i)
                            self.integer_wrappers[i] = integer_wrapper
                        else:
                            integer_wrapper = self.integer_wrappers[i]
                        return self.createIndex(j, 0, integer_wrapper)
            return self.createIndex(i, 0, 0)


#             for i, id in enumerate(self.id_lists_keys):

#             if version is not None:
#                 for data in enumerate(self.id_lists[id]):
#                     if
#         for i, data in enumerate(self.id_lists):
#             if data[self.idxs['id']] == id and \
#                     (not version or data[self.idxs['version']] == version):
#                 return self.createIndex(i, 0, 0)
        return QtCore.QModelIndex()

    def add_data(self, value_dict):
        id = value_dict['id']
        value_list = []
        for _, c in sorted(self.cols.iteritems()):
            if c in value_dict:
                value_list.append(value_dict[c])
            else:
                value_list.append(None)
        if id not in self.id_lists:
            self.id_lists[id] = []
            if "type" in value_dict:
                type = value_dict["type"]
                if type == "blob":
                    self.file_idxs.add(len(self.id_lists_keys))
                elif type == "tree":
                    self.dir_idxs.add(len(self.id_lists_keys))
            self.id_lists_keys.append(id)
        self.id_lists[id].append(tuple(value_list))
        self.reset()
Esempio n. 10
0
 def __init__(self, parent=None):
     QtGui.QDialog.__init__(self, parent)
     self.setModal(False)
     self.build_gui()
     self.db_access = DatabaseAccessSingleton()
class ManagedRefModel(QtCore.QAbstractItemModel):

    _instance = None

    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.cols = {
            0: "name",
            1: "tags",
            2: "user",
            3: "date_created",
            4: "date_modified",
            5: "id",
            6: "version",
            7: "content_hash",
            8: "signature",
            9: "type",
        }
        self.idxs = dict((v, k) for (k, v) in self.cols.iteritems())
        self.headers = {
            "id": "ID",
            "name": "Name",
            "tags": "Tags",
            "user": "******",
            "date_created": "Date Created",
            "date_modified": "Date Modified",
            "content_hash": "Content Hash",
            "version": "Version",
            "signature": "Signature",
        }

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database([c[1] for c in sorted(self.cols.iteritems())])

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs["id"]] not in self.id_lists:
                self.id_lists[ref[self.idxs["id"]]] = []
            self.id_lists[ref[self.idxs["id"]]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.file_idxs = set()
        self.dir_idxs = set()
        for i, key in enumerate(self.id_lists_keys):
            if self.id_lists[key][0][self.idxs["type"]] == "blob":
                self.file_idxs.add(i)
            elif self.id_lists[key][0][self.idxs["type"]] == "tree":
                self.dir_idxs.add(i)

        print "file:", self.file_idxs
        print "dir:", self.dir_idxs
        self.integer_wrappers = {}

    def rowCount(self, parent=QtCore.QModelIndex()):
        if not parent.isValid():
            # print 'rowCount:', len(self.id_lists_keys)
            return len(self.id_lists_keys)
        # print 'parentValid rowCount:', \
        #     len(self.id_lists[self.id_lists_keys[parent.row()]])
        return len(self.id_lists[self.id_lists_keys[parent.row()]])

    def columnCount(self, parent=QtCore.QModelIndex()):
        # print 'columnCount:', len(self.headers)
        return len(self.headers)

    def hasChildren(self, parent=QtCore.QModelIndex()):
        # print 'hasChildren:'
        if not parent.isValid():
            # print '  True'
            return True
        else:
            # print '  PARENT:', parent.row(), parent.column(), \
            #     parent.internalPointer()
            if not parent.parent().isValid():
                # print '  TRUE'
                return True
        # print '  False'
        return False

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if section in self.cols:
            return QtCore.QVariant(self.headers[self.cols[section]])
        return QtCore.QVariant()

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        # if index.parent().isValid():
        #     print 'data', index.row(), index.column(), index.parent().row()
        if index.parent().isValid():
            # have a child node
            # print 'got child node!', index.parent().row()
            id_list = self.id_lists[self.id_lists_keys[index.parent().row()]]
            data = id_list[index.row()]
        else:
            # have a parent node
            # want to have the earliest created date and latest modified date
            id_list = self.id_lists[self.id_lists_keys[index.row()]]
            data = id_list[0]
            if (
                index.column() == self.idxs["version"]
                or index.column() == self.idxs["signature"]
                or index.column() == self.idxs["content_hash"]
                or index.column() == self.idxs["date_created"]
                or index.column() == self.idxs["date_modified"]
                or index.column() == self.idxs["user"]
            ):
                return QtCore.QVariant()

        if index.column() < len(data):
            return QtCore.QVariant(data[index.column()])
        return QtCore.QVariant()

    def parent(self, index):
        # print 'calling parent() method'
        if index.isValid():
            # print '  index is valid', index.row(), index.column()
            if index.internalPointer():
                parent_item = index.internalPointer().idx
                # print '  parent_item:', parent_item
                return self.createIndex(parent_item, 0, None)
        #             else:
        #                 # print '  internalPointer is not valid'
        #         else:
        #             # print 'index not valid for parent call'
        return QtCore.QModelIndex()

    def index(self, row, column, parent):
        # print 'index:', row, column
        if not parent.isValid():
            if len(self.id_lists_keys) > row:
                # print '  no parent item'
                return self.createIndex(row, column, None)
        else:
            # print '  **** parent_item', row, column, parent.row()
            if len(self.id_lists[self.id_lists_keys[parent.row()]]) > row:
                # print '  ++++ creating index'
                # !!! internalPointer is a weakref in PyQt !!!
                if parent.row() not in self.integer_wrappers:
                    integer_wrapper = IntegerWrapper(parent.row())
                    self.integer_wrappers[parent.row()] = integer_wrapper
                else:
                    integer_wrapper = self.integer_wrappers[parent.row()]
                # print '  ---- created parent wrapper'
                return self.createIndex(row, column, integer_wrapper)
        return QtCore.QModelIndex()

    def sort(self, column, order=QtCore.Qt.AscendingOrder):
        self.emit(QtCore.SIGNAL("layoutAboutToBeChanged()"))
        if column == -1:
            return
        self.id_lists_keys.sort(key=lambda x: self.id_lists[x][0][column], reverse=(order == QtCore.Qt.AscendingOrder))
        self.emit(QtCore.SIGNAL("layoutChanged()"))

    def find_row(self, id, version=None):
        if id in self.id_lists:
            i = self.id_lists_keys.index(id)
            if version is not None:
                for j, data in enumerate(self.id_lists[id]):
                    if data[self.idxs["version"]] == version:
                        if i not in self.integer_wrappers:
                            integer_wrapper = IntegerWrapper(i)
                            self.integer_wrappers[i] = integer_wrapper
                        else:
                            integer_wrapper = self.integer_wrappers[i]
                        return self.createIndex(j, 0, integer_wrapper)
            return self.createIndex(i, 0, 0)
        #             for i, id in enumerate(self.id_lists_keys):

        #             if version is not None:
        #                 for data in enumerate(self.id_lists[id]):
        #                     if
        #         for i, data in enumerate(self.id_lists):
        #             if data[self.idxs['id']] == id and \
        #                     (not version or data[self.idxs['version']] == version):
        #                 return self.createIndex(i, 0, 0)
        return QtCore.QModelIndex()

    def add_data(self, value_dict):
        id = value_dict["id"]
        value_list = []
        for _, c in sorted(self.cols.iteritems()):
            if c in value_dict:
                value_list.append(value_dict[c])
            else:
                value_list.append(None)
        if id not in self.id_lists:
            self.id_lists[id] = []
            if "type" in value_dict:
                type = value_dict["type"]
                if type == "blob":
                    self.file_idxs.add(len(self.id_lists_keys))
                elif type == "tree":
                    self.dir_idxs.add(len(self.id_lists_keys))
            self.id_lists_keys.append(id)
        self.id_lists[id].append(tuple(value_list))
        self.reset()
Esempio n. 12
0
class PersistentRefModel(QtCore.QAbstractItemModel):

    _instance = None

    # 2013-09-03 18:57:53.133000
    _DATE_FORMAT = re.compile(r'^(?P<y>[0-9]{4})-'
                              r'(?P<m>[0-9]{2})-'
                              r'(?P<d>[0-9]{2}) '
                              r'(?P<H>[0-9]{2}):'
                              r'(?P<M>[0-9]{2}):'
                              r'(?P<S>[0-9]{2}).'
                              r'(?P<ms>[0-9]+)$')

    cols = {
        0: "name",
        1: "type",
        2: "tags",
        3: "user",
        4: "date_created",
        5: "date_modified",
        6: "id",
        7: "version",
        8: "content_hash",
        9: "signature"
    }
    idxs = dict((v, k) for (k, v) in cols.iteritems())
    headers = {
        "id": "ID",
        "name": "Name",
        "tags": "Tags",
        "user": "******",
        "date_created": "Date Created",
        "date_modified": "Date Modified",
        "content_hash": "Content Hash",
        "version": "Version",
        "signature": "Signature",
        "type": "Type"
    }

    def __init__(self, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)

        self.db_access = DatabaseAccessSingleton()
        self.db_access.set_model(self)
        rows = self.db_access.read_database(
            [c[1] for c in sorted(self.cols.iteritems())])
        rows = map(self.fix_dates, rows)

        self.id_lists = {}
        for ref in rows:
            if ref[self.idxs['id']] not in self.id_lists:
                self.id_lists[ref[self.idxs['id']]] = []
            self.id_lists[ref[self.idxs['id']]].append(ref)

        self.id_lists_keys = self.id_lists.keys()

        self.integer_wrappers = {}

    @staticmethod
    def fix_dates(row):
        row = list(row)
        for c in ('date_created', 'date_modified'):
            c = PersistentRefModel.idxs[c]
            m = PersistentRefModel._DATE_FORMAT.match(row[c])
            if m is not None:
                row[c] = '{y}-{m}-{d} {H}:{M}'.format(**m.groupdict())
        return tuple(row)

    def rowCount(self, parent=QtCore.QModelIndex()):
        if not parent.isValid():
            # print 'rowCount:', len(self.id_lists_keys)
            return len(self.id_lists_keys)
        # print 'parentValid rowCount:', \
        #     len(self.id_lists[self.id_lists_keys[parent.row()]])
        return len(self.id_lists[self.id_lists_keys[parent.row()]])

    def columnCount(self, parent=QtCore.QModelIndex()):
        # print 'columnCount:', len(self.headers)
        return len(self.headers)

    def hasChildren(self, parent=QtCore.QModelIndex()):
        # print 'hasChildren:'
        if not parent.isValid():
            # print '  True'
            return True
        else:
            # print '  PARENT:', parent.row(), parent.column(), \
            #     parent.internalPointer()
            if not parent.parent().isValid():
                # print '  TRUE'
                return True
        # print '  False'
        return False

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return None
        if section in self.cols:
            return self.headers[self.cols[section]]
        return None

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return None
        # if index.parent().isValid():
        #     print 'data', index.row(), index.column(), index.parent().row()
        if index.parent().isValid():
            # have a child node
            # print 'got child node!', index.parent().row()
            id_list = self.id_lists[self.id_lists_keys[index.parent().row()]]
            data = id_list[index.row()]
        else:
            # have a parent node
            id_list = self.id_lists[self.id_lists_keys[index.row()]]
            data = id_list[0]
            # want to have the earliest created date and latest modified date
            if index.column() == self.idxs['date_created']:
                dates = [l[index.column()] for l in id_list]
                return min(dates)
            if index.column() == self.idxs['date_modified']:
                dates = [l[index.column()] for l in id_list]
                return max(dates)
            if index.column() == self.idxs['version'] or \
                    index.column() == self.idxs['signature'] or \
                    index.column() == self.idxs['content_hash'] or \
                    index.column() == self.idxs['user']:
                return None

        if index.column() < len(data):
            return data[index.column()]
        return None

    def parent(self, index):
        # print 'calling parent() method'
        if index.isValid():
            # print '  index is valid', index.row(), index.column()
            if index.internalPointer():
                parent_item = index.internalPointer().idx
                # print '  parent_item:', parent_item
                return self.createIndex(parent_item, 0, None)
#             else:
#                 # print '  internalPointer is not valid'
#         else:
#             # print 'index not valid for parent call'
        return QtCore.QModelIndex()

    def index(self, row, column, parent):
        # print 'index:', row, column
        if not parent.isValid():
            if len(self.id_lists_keys) > row:
                # print '  no parent item'
                return self.createIndex(row, column, None)
        else:
            # print '  **** parent_item', row, column, parent.row()
            if len(self.id_lists[self.id_lists_keys[parent.row()]]) > row:
                # print '  ++++ creating index'
                # !!! internalPointer is a weakref in PyQt !!!
                if parent.row() not in self.integer_wrappers:
                    integer_wrapper = IntegerWrapper(parent.row())
                    self.integer_wrappers[parent.row()] = integer_wrapper
                else:
                    integer_wrapper = self.integer_wrappers[parent.row()]
                # print '  ---- created parent wrapper'
                return self.createIndex(row, column, integer_wrapper)
        return QtCore.QModelIndex()

    def sort(self, column, order=QtCore.Qt.AscendingOrder):
        self.emit(QtCore.SIGNAL('layoutAboutToBeChanged()'))
        if column == -1:
            return
        self.id_lists_keys.sort(key=lambda x: self.id_lists[x][0][column],
                                reverse=(order == QtCore.Qt.AscendingOrder))
        self.emit(QtCore.SIGNAL('layoutChanged()'))

    def find_row(self, id, version=None):
        if id in self.id_lists:
            i = self.id_lists_keys.index(id)
            if version is not None:
                for j, data in enumerate(self.id_lists[id]):
                    if data[self.idxs['version']] == version:
                        if i not in self.integer_wrappers:
                            integer_wrapper = IntegerWrapper(i)
                            self.integer_wrappers[i] = integer_wrapper
                        else:
                            integer_wrapper = self.integer_wrappers[i]
                        return self.createIndex(j, 0, integer_wrapper)
            return self.createIndex(i, 0, 0)


#             for i, id in enumerate(self.id_lists_keys):

#             if version is not None:
#                 for data in enumerate(self.id_lists[id]):
#                     if
#         for i, data in enumerate(self.id_lists):
#             if data[self.idxs['id']] == id and \
#                     (not version or data[self.idxs['version']] == version):
#                 return self.createIndex(i, 0, 0)
        return QtCore.QModelIndex()

    def add_data(self, value_dict):
        id = value_dict['id']
        value_list = []
        for _, c in sorted(self.cols.iteritems()):
            if c in value_dict:
                value_list.append(str(value_dict[c]))
            else:
                value_list.append(None)
        if id not in self.id_lists:
            self.id_lists[id] = []
            self.id_lists_keys.append(id)
        self.id_lists[id].append(self.fix_dates(value_list))
        self.reset()

    def remove_data(self, where_dict):
        id = where_dict['id']
        version = where_dict.get('version', None)
        if version is not None:
            for idx, value_tuple in enumerate(self.id_lists[id]):
                if value_tuple[self.idxs['version']] == version:
                    del self.id_lists[id][idx]
                    break
        else:
            path_type = self.id_lists[id][0][self.idxs['type']]
            for idx, key_id in enumerate(self.id_lists_keys):
                if key_id == id:
                    del self.id_lists_keys[idx]
                    break
            del self.id_lists[id]
        self.reset()