Exemplo n.º 1
0
    def delete_selected_items_db_cols(self):
        wtree = cp.cmwdbtree
        if wtree is None :
            logger.warning('delete_selected_items_db_cols - CMWDBTree object does not exist?')
            return
        # dict of pairs {<item-name> : <item-parent-name>}
        # where <item-parent-name> is None for DB item or DB name for collection item.

        list_name_parent = [(item.text(), None if item.parent() is None else item.parent().text())\
                            for item in wtree.selected_items()]

        if not len(list_name_parent) :
            logger.warning('delete_selected_items: selected nothing - nothing to delete...')
            return

        #for k,v in list_name_parent :
        #    logger.debug('  %s : %s' % (k.ljust(20),v))

        # Define del_mode = COLS or DBS if at least one DB is selected
        del_mode = cp.COLS if all([p is not None for n,p in list_name_parent]) else cp.DBS

        list_db_names = [] # list of DB names
        dic_db_cols = {}   # dict {DBname : list of collection names} 
        msg = 'Delete %s:\n  ' % del_mode

        if del_mode == cp.DBS : 
            list_db_names = [n for n,p in list_name_parent if p is None]
            msg += '\n  '.join(list_db_names)
        else :
            for n,p in list_name_parent :
                if p not in dic_db_cols :
                    dic_db_cols[p] = [n,]
                else :
                    dic_db_cols[p].append(n)

            for dbname, lstcols in dic_db_cols.items() :
                msg += '\nfrom DB: %s\n    ' % dbname
                msg += '\n    '.join(lstcols)

        logger.info(msg)
        resp = confirm_or_cancel_dialog_box(parent=self.but_del, text=msg, title='Confirm or cancel')
        logger.debug('delete_selected_items_db_cols response: %s' % resp)

        if resp :
           if del_mode == cp.DBS : dbu.delete_databases(list_db_names)
           else                  : dbu.delete_collections(dic_db_cols)

           # Regenerate tree model
           self.on_edi_db_filter_finished()

        else :
            logger.warning('Command "Delete" is cancelled')
Exemplo n.º 2
0
    def add_db(self):
        """Adds DB from file
        """
        logger.debug('TBD: In add_db - Adds DB from file')

        path0 = '.'
        path = get_open_fname_through_dialog_box(self, path0, 'Select file with DB to add', filter='*')
        if path is None : 
            logger.warning('DB file selection is cancelled')
            return

        host = cp.cdb_host.value()
        port = cp.cdb_port.value()

        dbname = os.path.basename(path) # ????????????????????? split file extension?

        logger.info('Add DB "%s" from file %s' % (dbname, path))
        dbu.importdb(host, port, dbname, path) #, **kwa)
Exemplo n.º 3
0
    def add_doc(self):
        """Adds document from editor to DB
        """
        logger.debug('In add_doc')
        wdoce = cp.cmwdbdoceditor
        if wdoce is None or wdoce.data_nda is None:
            logger.warning(
                'Document is not selected. Select collection in DB then document in List mode.'
            )
            return

        dicdoc = wdoce.get_model_dicdoc()
        nda = wdoce.get_data_nda()

        msg = '\n  '.join(['%12s : %s' % (k, v) for k, v in dicdoc.items()])
        logger.debug('add_doc \n%s  \n%s' %
                     (msg, info_ndarr(nda, 'data n-d array ')))

        dbnexp = dbu.db_prefixed_name(dicdoc.get('experiment', 'exp_def'))
        dbndet = dbu.db_prefixed_name(dicdoc.get('detector', 'det_def'))
        colname = dicdoc.get('detector', None)

        d = {dbnexp: True, dbndet: True}
        resp = change_check_box_dict_in_popup_menu(
            d, msg='Add constants\nand metadata to DB', parent=self.but_add)
        logger.debug('add_doc resp: %s' % resp)

        if resp == 1:
            if d[dbnexp]:
                _, _ = dbu.insert_document_and_data(dbnexp, colname, dicdoc,
                                                    nda)
            if d[dbndet]:
                _, _ = dbu.insert_document_and_data(dbndet, colname, dicdoc,
                                                    nda)

            wdocs = cp.cmwdbdocswidg
            if wdocs is None: return
            cp.cmwdbdocs.show_documents(wdocs.dbname,
                                        wdocs.colname,
                                        force_update=True)

        else:
            logger.warning(
                'Uploading of calibration constants in DB is cancelled')
Exemplo n.º 4
0
    def delete_selected_items_docs(self):
        logger.debug('delete_selected_items_docs')
        wdocs = cp.cmwdbdocswidg
        if wdocs is None :
            logger.warning('Window with a List of documents does not exist?')
            return

        msg = 'From db: %s\n  col: %s\n  delete docs:\n    ' % (wdocs.dbname, wdocs.colname)
        doc_ids = [item.accessibleText() for item in wdocs.selected_items()]
        msg_recs = ['%s : %s'%(id, dbu.timestamp_id(id)) for id in doc_ids]
        msg += '\n    '.join(msg_recs)

        logger.info(msg)
        resp = confirm_or_cancel_dialog_box(parent=self.but_del, text=msg, title='Confirm or cancel')
        logger.debug('delete_selected_items_docs response: %s' % resp)

        if resp :
            dbu.delete_documents(wdocs.dbname, wdocs.colname, doc_ids)
            cp.cmwdbdocs.show_documents(wdocs.dbname, wdocs.colname, force_update=True)
        else :
            logger.warning('Command "Delete" is cancelled')
Exemplo n.º 5
0
    def fill_tree_model_for_client(self):
        #client = dbu.connect_client()
        client = self.thread.client()
        stat = self.thread.quit()

        if client is None:
            host = cp.cdb_host.value()
            port = cp.cdb_port.value()
            logger.warning("Can't connect to host: %s port: %d" % (host, port))
            return

        #pattern = 'cdb_xcs'
        #pattern = 'cspad'
        pattern = self._pattern
        dbnames = dbu.database_names(client)

        logger.debug('CMWDBTree.fill_tree_model_for_client dbnames: %s' %
                     str(dbnames))

        if pattern:
            dbnames = [name for name in dbnames if pattern in name]

        for dbname in dbnames:
            parentItem = self.model.invisibleRootItem()
            #parentItem.setIcon(icon.icon_folder_open)

            itdb = QStandardItem(dbname)
            itdb.setIcon(icon.icon_folder_closed)
            itdb.setEditable(False)
            #itdb.setCheckable(True)
            parentItem.appendRow(itdb)

            db = dbu.database(client, dbname)

            for col in dbu.collection_names(db):
                if not col: continue
                itcol = QStandardItem(col)
                itcol.setIcon(icon.icon_folder_closed)
                itcol.setEditable(False)
                itdb.appendRow(itcol)
Exemplo n.º 6
0
    def save_db(self):
        """Saves selected DBs in files
        """
        bdnames = self.selected_db_names()
        if len(bdnames) == 0 :
            logger.warning('DB is not selected. Click on DB(s) before "Save" button.')
            return

        logger.debug('In save_db bdnames:\n    %s' % '\n    '.join(bdnames))
        host = cp.cdb_host.value()
        port = cp.cdb_port.value()

        path0 = '.'
        #resp = get_open_fname_through_dialog_box(self, path0, title='Select directory for DB files', filter='*')
        resp = get_existing_directory_through_dialog_box(self, path0, title='Select directory for DB files')

        if resp is None : 
            logger.warning('Saving of DBs is cancelled')
            return

        for dbname in bdnames :
            fname = '%s/%s' % (resp, dbname)
            dbu.exportdb(host, port, dbname, fname) #, **kwa)
Exemplo n.º 7
0
    def show_document(self, dbname, colname, doc):
        """Implementation of the abstract method in CMWDBDocsBase
        """
        #CMWDBDocsBase.show_documents(self, dbname, colname, docs)
        msg = 'Show document for db: %s col: %s' % (dbname, colname)
        logger.debug(msg)

        if doc.get('id_data', None) is not None: doc[self.data_fname] = ''
        #for doc in docs : print(doc)
        self.fill_table_model(doc)

        self.data_nda = dbu.get_data_for_doc(dbname, doc)
        logger.debug(
            info_ndarr(self.data_nda, 'array from DB linked to the document'))
Exemplo n.º 8
0
    def save_doc(self):
        """Saves document metadata and data in files
        """
        logger.debug('In save_doc')

        wdoce = cp.cmwdbdoceditor
        if wdoce is None  or wdoce.data_nda is None :
            logger.warning('Document editor is not available. Select collection in DB then document in List mode.')
            return

        doc  = wdoce.get_model_dicdoc(discard_id_ts=False)
        data = wdoce.get_data_nda()

        prefix = dbu.out_fname_prefix(**doc)

        control = {'data' : True, 'meta' : True}
        resp = change_check_box_dict_in_popup_menu(control, 'Select and confirm',\
               msg='Save current document in file\n%s\nfor types:'%prefix, parent=self.but_add)

        if resp==1 :
            logger.info('Save document data and metadata in file(s) with prefix: %s' % prefix)
            dbu.save_doc_and_data_in_file(doc, data, prefix, control)
        else : 
            logger.warning('Command "Save" is cancelled')
Exemplo n.º 9
0
    def get_model_dicdoc(self, discard_id_ts=True):
        """Returns dictionary of key-values of current model
        """
        m = self.model
        d = dict([(m.item(r, 0).text(), m.item(r, 1).text())
                  for r in range(m.rowCount())])
        if d[self.data_fname] == self.data_fname_value:
            d[self.data_fname] = None
        d['time_sec'] = dbu.time_and_timestamp(
            **d)[0]  # 'time_stamp' is used to fill 'time_sec'

        # remove info items added for display purpose
        if discard_id_ts:
            for k in ('_id_ts', 'id_data_ts', 'id_exp_ts'):
                if d.get(k, None) is not None: del d[k]

        return d
Exemplo n.º 10
0
    def fill_table_model(self, doc=None):
        """Re-implementation of the method in QWList.fill_table_model
        """
        self.disconnect_item_changed_from(self.on_item_changed)

        self.clear_model()

        if doc is None:
            self.model.setVerticalHeaderLabels(['Select document'])
            #self.model.setHorizontalHeaderLabels(['col0', 'col1', 'col2'])
            #for row in range(0, 3):
            #  for col in range(0, 6):
            #    item = QStandardItem("itemA %d %d"%(row,col))
            #    item.setIcon(icon.icon_table)
            #    item.setCheckable(True)
            #    self.model.setItem(row,col,item)
            #    if col==2 : item.setIcon(icon.icon_folder_closed)
            #    if col==3 : item.setText('Some text')
            #    #self.model.appendRow(item)
        else:

            self.model.setHorizontalHeaderLabels(('key', 'value'))
            self.horizontalHeader().setSectionResizeMode(
                1, QHeaderView.Stretch)

            # add items with timestamp for id-s as '_id_ts', 'id_data_ts', 'id_exp_ts'
            for k in ('_id', 'id_data', 'id_exp'):
                v = doc.get(k, None)
                if v is not None: doc['%s_ts' % k] = dbu.timestamp_id(v)

            for r, k in enumerate(sorted(doc.keys())):
                v = doc[k]

                # set key item
                item = QStandardItem(k)
                item.setEnabled(True)
                item.setEditable(False)
                self.model.setItem(r, 0, item)

                # set value item
                cond = any([isinstance(v, o) for o in (str, dict, ObjectId)])
                s = str(v) if (
                    cond and len(str(v)) < 512) else 'str longer 512 chars'
                #if k in ('_id', 'id_data') :
                #    s = dbu.timestamp_id(v)
                #    msg = '%s = %s converted to %s' % (('doc["%s"]'%k).ljust(16), v, s)
                #    logger.debug(msg)
                item = QStandardItem(s)

                editable = self.item_is_editable_for_key(
                    k)  # and k!=self.data_fname
                #item.setCheckable(editable)
                #if editable : item.setCheckState(1)
                item.setEditable(editable)
                item.setEnabled(editable)
                item.setToolTip('Double-click on item\nor click on checkbox\nto change value' if editable else\
                                'This field is auto-generated')

                self.model.setItem(r, 1, item)

                if k == self.data_fname:
                    item.setText(self.data_fname_value)
                    item.setEnabled(False)
                    #item.setCheckable(True)
                    #item.setCheckState(1)
                    item.setToolTip('Data file name - click to change')
                    item.setBackground(QBrush(Qt.yellow))
                    #self.widg = QPushButton('Select file')
                    #self.widg = CMWDBDocEditorItem('file-name')
                    #index = self.model.indexFromItem(item)
                    #self.setIndexWidget(index, self.widg)

        self.setColumnWidth(1, 300)  # QTableView
        #self.horizontalHeader().setResizeMode(1, 1) # (index, mode)

        self.connect_item_changed_to(self.on_item_changed)