Example #1
0
    def _updateUrl(self):
        # overloaded to filter for datasets
        nodes = list(self._tree.selectedH5Nodes())
        newDatasetName = self._lineEditNewItem.text()
        isDatasetSelected = False
        if nodes:
            node = nodes[0]
            if silx.io.is_dataset(node.h5py_object):
                data_path = node.local_name
                isDatasetSelected = True
            elif silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if newDatasetName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += newDatasetName.lstrip("/")
                    isDatasetSelected = True

            if isDatasetSelected:
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(
                        self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText(self._selectDatasetStatusText)
Example #2
0
 def setUrl(self, url: DataUrl) -> None:
     assert isinstance(url, DataUrl)
     sel_items = self._listWidget.findItems(url.path(), qt.Qt.MatchExactly)
     if sel_items is None:
         _logger.warning(url.path(), ' is not registered in the list.')
     elif len(sel_items) > 0:
         item = sel_items[0]
         self._listWidget.setCurrentItem(item)
         self.sigCurrentUrlChanged.emit(item.text())
Example #3
0
 def dropEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasFormat("application/x-silx-uri"):
         byteString = event.mimeData().data("application/x-silx-uri")
         path = byteString.data().decode("utf-8")
         url = DataUrl(path)
         self.setText(url.data_path())
     else:
         qt.QMessageBox.critical(self, "Drop cancelled", "A HDF5 path is expected")
         return
Example #4
0
 def dropEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasFormat("application/x-silx-uri"):
         byteString = event.mimeData().data("application/x-silx-uri")
         path = byteString.data().decode("utf-8")
         url = DataUrl(path)
         self.setText(url.data_path())
     else:
         qt.QMessageBox.critical(self, "Drop cancelled",
                                 "A HDF5 path is expected")
         return
 def _updateUrl(self):
     nodes = list(self._tree.selectedH5Nodes())
     subgroupName = self._lineEditNewItem.text()
     if nodes:
         node = nodes[0]
         data_path = node.local_name
         if subgroupName.lstrip("/"):
             if not data_path.endswith("/"):
                 data_path += "/"
             data_path += subgroupName.lstrip("/")
         self._selectedUrl = DataUrl(file_path=node.local_filename,
                                     data_path=data_path)
         self._okButton.setEnabled(True)
         self._labelSelection.setText(self._selectedUrl.path())
Example #6
0
class GroupDialog(_Hdf5ItemSelectionDialog):
    """This :class:`QDialog` uses a :class:`silx.gui.hdf5.Hdf5TreeView` to
    provide a HDF5 group selection dialog.

    The information identifying the selected node is provided as a
    :class:`silx.io.url.DataUrl`.

    Example:

    .. code-block:: python

        dialog = GroupDialog()
        dialog.addFile(filepath1)
        dialog.addFile(filepath2)

        if dialog.exec_():
            print("File path: %s" % dialog.getSelectedDataUrl().file_path())
            print("HDF5 group path : %s " % dialog.getSelectedDataUrl().data_path())
        else:
            print("Operation cancelled :(")

    """
    def __init__(self, parent=None):
        _Hdf5ItemSelectionDialog.__init__(self, parent)

        # customization for groups
        self.setWindowTitle("HDF5 group selection")

        self._header.setSections([self._model.NAME_COLUMN,
                                  self._model.NODE_COLUMN,
                                  self._model.LINK_COLUMN])

    def _onActivation(self, idx):
        # double-click or enter press: filter for groups
        nodes = list(self._tree.selectedH5Nodes())
        node = nodes[0]
        if silx.io.is_group(node.h5py_object):
            self.accept()

    def _updateUrl(self):
        # overloaded to filter for groups
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditNewItem.text()
        if nodes:
            node = nodes[0]
            if silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if subgroupName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += subgroupName.lstrip("/")
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(
                        self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText("Select a group")
Example #7
0
    def setCurrentUrl(self, url: typing.Union[DataUrl, str]) -> None:
        """
        Define the url to be displayed

        :param url: url to be displayed
        :type: DataUrl
        """
        assert isinstance(url, (DataUrl, str))
        if isinstance(url, str):
            url = DataUrl(path=url)
        if url != self._current_url:
            self._current_url = url
            self.sigCurrentUrlChanged.emit(url.path())

        old_url_table = self._urlsTable.blockSignals(True)
        old_slider = self._slider.blockSignals(True)

        self._urlsTable.setUrl(url)
        self._slider.setUrlIndex(self._urlIndexes[url.path()])
        if self._current_url is None:
            self._plot.clear()
        else:
            if self._current_url.path() in self._urlData:
                self._plot.setData(self._urlData[url.path()])
            else:
                self._load(url)
                self._notifyLoading()
            self._preFetch(self._getNNextUrls(self.__n_prefetch, url))
            self._preFetch(self._getNPreviousUrls(self.__n_prefetch, url))
        self._urlsTable.blockSignals(old_url_table)
        self._slider.blockSignals(old_slider)
Example #8
0
def create_edf_url(file_name):
    """ create a simple DataUrl with a .edf file"""
    dsc = fabio.edfimage.EdfImage(data=create_random_image(), header={})
    dsc.write(file_name)
    return [
        DataUrl(file_path=file_name, data_slice=(0, ), scheme='fabio'),
    ]
    def setUp(self):
        TestCaseQt.setUp(self)
        self.urls = OrderedDict()
        self._raw_data = {}
        self._folder = tempfile.mkdtemp()
        self._n_urls = 10
        file_name = os.path.join(self._folder, 'test_inage_stack_file.h5')
        with h5py.File(file_name, 'w') as h5f:
            for i in range(self._n_urls):
                width = numpy.random.randint(10, 40)
                height = numpy.random.randint(10, 40)
                raw_data = numpy.random.random((width, height))
                self._raw_data[i] = raw_data
                h5f[str(i)] = raw_data
                self.urls[i] = DataUrl(file_path=file_name,
                                       data_path=str(i),
                                       scheme='silx')
        self.widget = ImageStack()

        self.urlLoadedListener = SignalListener()
        self.widget.sigLoaded.connect(self.urlLoadedListener)

        self.currentUrlChangedListener = SignalListener()
        self.widget.sigCurrentUrlChanged.connect(
            self.currentUrlChangedListener)
class GroupDialog(_Hdf5ItemSelectionDialog):
    """This :class:`QDialog` uses a :class:`silx.gui.hdf5.Hdf5TreeView` to
    provide a HDF5 group selection dialog.

    The information identifying the selected node is provided as a
    :class:`silx.io.url.DataUrl`.

    Example:

    .. code-block:: python

        dialog = GroupDialog()
        dialog.addFile(filepath1)
        dialog.addFile(filepath2)

        if dialog.exec_():
            print("File path: %s" % dialog.getSelectedDataUrl().file_path())
            print("HDF5 group path : %s " % dialog.getSelectedDataUrl().data_path())
        else:
            print("Operation cancelled :(")

    """
    def __init__(self, parent=None):
        _Hdf5ItemSelectionDialog.__init__(self, parent)

        # customization for groups
        self.setWindowTitle("HDF5 group selection")

        self._header.setSections([
            self._model.NAME_COLUMN, self._model.NODE_COLUMN,
            self._model.LINK_COLUMN
        ])

    def _onActivation(self, idx):
        # double-click or enter press: filter for groups
        nodes = list(self._tree.selectedH5Nodes())
        node = nodes[0]
        if silx.io.is_group(node.h5py_object):
            self.accept()

    def _updateUrl(self):
        # overloaded to filter for groups
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditNewItem.text()
        if nodes:
            node = nodes[0]
            if silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if subgroupName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += subgroupName.lstrip("/")
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText("Select a group")
Example #11
0
def create_h5py_urls(n_url, file_name):
    """ creates n urls based on h5py"""
    res = []
    with h5py.File(file_name, 'w') as h5f:
        for i in range(n_url):
            h5f[str(i)] = create_random_image()
            res.append(
                DataUrl(file_path=file_name, data_path=str(i), scheme='silx'))
    return res
Example #12
0
 def setFiles(self, files):
     urls = list()
     for _file in files:
         if os.path.isfile(_file):
             urls.append(DataUrl(file_path=_file, scheme=None))
     urls.sort(key=lambda url: url.path())
     window.setUrls(urls)
     window._selectionTable.setSelection(url_img_a=urls[0].path(),
                                         url_img_b=urls[1].path())
Example #13
0
 def _updateUrl(self):
     nodes = list(self._tree.selectedH5Nodes())
     subgroupName = self._lineEditSubgroup.text()
     if nodes:
         node = nodes[0]
         if silx.io.is_group(node.h5py_object):
             data_path = node.local_name
             if subgroupName.lstrip("/"):
                 if not data_path.endswith("/"):
                     data_path += "/"
                 data_path += subgroupName.lstrip("/")
             self._selectedUrl = DataUrl(file_path=node.local_filename,
                                         data_path=data_path)
             self._okButton.setEnabled(True)
             self._labelSelection.setText(self._selectedUrl.path())
         else:
             self._selectedUrl = None
             self._okButton.setEnabled(False)
             self._labelSelection.setText("Select a group")
Example #14
0
 def _updateUrl(self):
     nodes = list(self._tree.selectedH5Nodes())
     subgroupName = self._lineEditNewItem.text()
     if nodes:
         node = nodes[0]
         data_path = node.local_name
         if subgroupName.lstrip("/"):
             if not data_path.endswith("/"):
                 data_path += "/"
             data_path += subgroupName.lstrip("/")
         self._selectedUrl = DataUrl(file_path=node.local_filename,
                                     data_path=data_path)
         self._okButton.setEnabled(True)
         self._labelSelection.setText(
                 self._selectedUrl.path())
Example #15
0
    def _getPreviousUrl(self, url: DataUrl) -> typing.Union[None, DataUrl]:
        """
        return the previous url in the stack

        :param url: url for which we want the previous url
        :type: DataUrl
        :return: next url in the stack or None if `url` is the last one
        :rtype: Union[None, DataUrl]
        """
        if self._urls is None:
            return None
        else:
            index = self._urlIndexes[url.path()]
            indexes = list(self._urls.keys())
            res = list(filter(lambda x: x < index, indexes))
            if len(res) == 0:
                return None
            else:
                return self._urls[res[-1]]
Example #16
0
 def _updateUrl(self):
     nodes = list(self._tree.selectedH5Nodes())
     subgroupName = self._lineEditSubgroup.text()
     if nodes:
         node = nodes[0]
         if silx.io.is_group(node.h5py_object):
             data_path = node.local_name
             if subgroupName.lstrip("/"):
                 if not data_path.endswith("/"):
                     data_path += "/"
                 data_path += subgroupName.lstrip("/")
             self._selectedUrl = DataUrl(file_path=node.local_filename,
                                         data_path=data_path)
             self._okButton.setEnabled(True)
             self._labelSelection.setText(
                     self._selectedUrl.path())
         else:
             self._selectedUrl = None
             self._okButton.setEnabled(False)
             self._labelSelection.setText("Select a group")
Example #17
0
class DatasetDialog(_Hdf5ItemSelectionDialog):
    """This :class:`QDialog` uses a :class:`silx.gui.hdf5.Hdf5TreeView` to
    provide a HDF5 dataset selection dialog.

    The information identifying the selected node is provided as a
    :class:`silx.io.url.DataUrl`.

    Example:

    .. code-block:: python

        dialog = DatasetDialog()
        dialog.addFile(filepath1)
        dialog.addFile(filepath2)

        if dialog.exec_():
            print("File path: %s" % dialog.getSelectedDataUrl().file_path())
            print("HDF5 dataset path : %s " % dialog.getSelectedDataUrl().data_path())
        else:
            print("Operation cancelled :(")

    """
    def __init__(self, parent=None):
        _Hdf5ItemSelectionDialog.__init__(self, parent)

        # customization for groups
        self.setWindowTitle("HDF5 dataset selection")

        self._header.setSections([self._model.NAME_COLUMN,
                                  self._model.NODE_COLUMN,
                                  self._model.LINK_COLUMN,
                                  self._model.TYPE_COLUMN,
                                  self._model.SHAPE_COLUMN])
        self._selectDatasetStatusText = "Select a dataset or type a new dataset name"

    def setMode(self, mode):
        """Set dialog mode DatasetDialog.SaveMode or DatasetDialog.LoadMode

        :param mode: DatasetDialog.SaveMode or DatasetDialog.LoadMode
        """
        _Hdf5ItemSelectionDialog.setMode(self, mode)
        if mode == DatasetDialog.SaveMode:
            self._selectDatasetStatusText = "Select a dataset or type a new dataset name"
        elif mode == DatasetDialog.LoadMode:
            self._selectDatasetStatusText = "Select a dataset"

    def _onActivation(self, idx):
        # double-click or enter press: filter for datasets
        nodes = list(self._tree.selectedH5Nodes())
        node = nodes[0]
        if silx.io.is_dataset(node.h5py_object):
            self.accept()

    def _updateUrl(self):
        # overloaded to filter for datasets
        nodes = list(self._tree.selectedH5Nodes())
        newDatasetName = self._lineEditNewItem.text()
        isDatasetSelected = False
        if nodes:
            node = nodes[0]
            if silx.io.is_dataset(node.h5py_object):
                data_path = node.local_name
                isDatasetSelected = True
            elif silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if newDatasetName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += newDatasetName.lstrip("/")
                    isDatasetSelected = True

            if isDatasetSelected:
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(
                        self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText(self._selectDatasetStatusText)
Example #18
0
def create_numpy_url(file_name):
    """ create a simple DataUrl with a .npy file """
    numpy.save(file=file_name, arr=create_random_image())
    return [
        DataUrl(file_path=file_name, scheme='numpy'),
    ]
Example #19
0
class GroupDialog(qt.QDialog):
    """This :class:`QDialog` uses a :class:`silx.gui.hdf5.Hdf5TreeView` to
    provide a HDF5 group selection dialog.

    The information identifying the selected node is provided as a
    :class:`silx.io.url.DataUrl`.

    Example:

    .. code-block:: python

        dialog = GroupDialog()
        dialog.addFile(filepath1)
        dialog.addFile(filepath2)

        if dialog.exec_():
            print("File path: %s" % dialog.getSelectedDataUrl().file_path())
            print("HDF5 group path : %s " % dialog.getSelectedDataUrl().data_path())
        else:
            print("Operation cancelled :(")

    """
    def __init__(self, parent=None):
        qt.QDialog.__init__(self, parent)
        self.setWindowTitle("HDF5 group selection")

        self._tree = Hdf5TreeView(self)
        self._tree.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._tree.activated.connect(self._onActivation)
        self._tree.selectionModel().selectionChanged.connect(
            self._onSelectionChange)

        self._model = self._tree.findHdf5TreeModel()

        self._header = self._tree.header()
        self._header.setSections([self._model.NAME_COLUMN,
                                  self._model.NODE_COLUMN,
                                  self._model.LINK_COLUMN])

        _labelSubgroup = qt.QLabel(self)
        _labelSubgroup.setText("Subgroup name (optional)")
        self._lineEditSubgroup = qt.QLineEdit(self)
        self._lineEditSubgroup.setToolTip(
                "Specify the name of a new subgroup "
                "to be created in the selected group.")
        self._lineEditSubgroup.textChanged.connect(
                self._onSubgroupNameChange)

        _labelSelectionTitle = qt.QLabel(self)
        _labelSelectionTitle.setText("Current selection")
        self._labelSelection = qt.QLabel(self)
        self._labelSelection.setStyleSheet("color: gray")
        self._labelSelection.setWordWrap(True)
        self._labelSelection.setText("Select a group")

        buttonBox = qt.QDialogButtonBox()
        self._okButton = buttonBox.addButton(qt.QDialogButtonBox.Ok)
        self._okButton.setEnabled(False)
        buttonBox.addButton(qt.QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        vlayout = qt.QVBoxLayout(self)
        vlayout.addWidget(self._tree)
        vlayout.addWidget(_labelSubgroup)
        vlayout.addWidget(self._lineEditSubgroup)
        vlayout.addWidget(_labelSelectionTitle)
        vlayout.addWidget(self._labelSelection)
        vlayout.addWidget(buttonBox)
        self.setLayout(vlayout)

        self.setMinimumWidth(400)

        self._selectedUrl = None

    def addFile(self, path):
        """Add a HDF5 file to the tree.
        All groups it contains will be selectable in the dialog.

        :param str path: File path
        """
        self._model.insertFile(path)

    def addGroup(self, group):
        """Add a HDF5 group to the tree. This group and all its subgroups
        will be selectable in the dialog.

        :param h5py.Group group: HDF5 group
        """
        self._model.insertH5pyObject(group)

    def _onActivation(self, idx):
        # double-click or enter press
        nodes = list(self._tree.selectedH5Nodes())
        node = nodes[0]
        if silx.io.is_group(node.h5py_object):
            self.accept()

    def _onSelectionChange(self, old, new):
        self._updateUrl()

    def _onSubgroupNameChange(self, text):
        self._updateUrl()

    def _updateUrl(self):
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditSubgroup.text()
        if nodes:
            node = nodes[0]
            if silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if subgroupName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += subgroupName.lstrip("/")
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(
                        self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText("Select a group")

    def getSelectedDataUrl(self):
        """Return a :class:`DataUrl` with a file path and a data path.
        Return None if the dialog was cancelled.

        :return: :class:`silx.io.url.DataUrl` object pointing to the
            selected group.
        """
        return self._selectedUrl
class _Hdf5ItemSelectionDialog(qt.QDialog):
    SaveMode = 1
    """Mode used to set the HDF5 item selection dialog to *save* mode.
    This adds a text field to type in a new item name."""

    LoadMode = 2
    """Mode used to set the HDF5 item selection dialog to *load* mode.
    Only existing items of the HDF5 file can be selected in this mode."""
    def __init__(self, parent=None):
        qt.QDialog.__init__(self, parent)
        self.setWindowTitle("HDF5 item selection")

        self._tree = Hdf5TreeView(self)
        self._tree.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._tree.activated.connect(self._onActivation)
        self._tree.selectionModel().selectionChanged.connect(
            self._onSelectionChange)

        self._model = self._tree.findHdf5TreeModel()

        self._header = self._tree.header()

        self._newItemWidget = qt.QWidget(self)
        newItemLayout = qt.QVBoxLayout(self._newItemWidget)
        self._labelNewItem = qt.QLabel(self._newItemWidget)
        self._labelNewItem.setText(
            "Create new item in selected group (optional):")
        self._lineEditNewItem = qt.QLineEdit(self._newItemWidget)
        self._lineEditNewItem.setToolTip(
            "Specify the name of a new item "
            "to be created in the selected group.")
        self._lineEditNewItem.textChanged.connect(self._onNewItemNameChange)
        newItemLayout.addWidget(self._labelNewItem)
        newItemLayout.addWidget(self._lineEditNewItem)

        _labelSelectionTitle = qt.QLabel(self)
        _labelSelectionTitle.setText("Current selection")
        self._labelSelection = qt.QLabel(self)
        self._labelSelection.setStyleSheet("color: gray")
        self._labelSelection.setWordWrap(True)
        self._labelSelection.setText("Select an item")

        buttonBox = qt.QDialogButtonBox()
        self._okButton = buttonBox.addButton(qt.QDialogButtonBox.Ok)
        self._okButton.setEnabled(False)
        buttonBox.addButton(qt.QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        vlayout = qt.QVBoxLayout(self)
        vlayout.addWidget(self._tree)
        vlayout.addWidget(self._newItemWidget)
        vlayout.addWidget(_labelSelectionTitle)
        vlayout.addWidget(self._labelSelection)
        vlayout.addWidget(buttonBox)
        self.setLayout(vlayout)

        self.setMinimumWidth(400)

        self._selectedUrl = None

    def _onSelectionChange(self, old, new):
        self._updateUrl()

    def _onNewItemNameChange(self, text):
        self._updateUrl()

    def _onActivation(self, idx):
        # double-click or enter press
        self.accept()

    def setMode(self, mode):
        """Set dialog mode DatasetDialog.SaveMode or DatasetDialog.LoadMode

        :param mode: DatasetDialog.SaveMode or DatasetDialog.LoadMode
        """
        if mode == self.LoadMode:
            # hide "Create new item" field
            self._lineEditNewItem.clear()
            self._newItemWidget.hide()
        elif mode == self.SaveMode:
            self._newItemWidget.show()
        else:
            raise ValueError("Invalid DatasetDialog mode %s" % mode)

    def addFile(self, path):
        """Add a HDF5 file to the tree.
        All groups it contains will be selectable in the dialog.

        :param str path: File path
        """
        self._model.insertFile(path)

    def addGroup(self, group):
        """Add a HDF5 group to the tree. This group and all its subgroups
        will be selectable in the dialog.

        :param h5py.Group group: HDF5 group
        """
        self._model.insertH5pyObject(group)

    def _updateUrl(self):
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditNewItem.text()
        if nodes:
            node = nodes[0]
            data_path = node.local_name
            if subgroupName.lstrip("/"):
                if not data_path.endswith("/"):
                    data_path += "/"
                data_path += subgroupName.lstrip("/")
            self._selectedUrl = DataUrl(file_path=node.local_filename,
                                        data_path=data_path)
            self._okButton.setEnabled(True)
            self._labelSelection.setText(self._selectedUrl.path())

    def getSelectedDataUrl(self):
        """Return a :class:`DataUrl` with a file path and a data path.
        Return None if the dialog was cancelled.

        :return: :class:`silx.io.url.DataUrl` object pointing to the
            selected HDF5 item.
        """
        return self._selectedUrl
Example #21
0
class GroupDialog(qt.QDialog):
    """This :class:`QDialog` uses a :class:`silx.gui.hdf5.Hdf5TreeView` to
    provide a HDF5 group selection dialog.

    The information identifying the selected node is provided as a
    :class:`silx.io.url.DataUrl`.

    Example:

    .. code-block:: python

        dialog = GroupDialog()
        dialog.addFile(filepath1)
        dialog.addFile(filepath2)

        if dialog.exec_():
            print("File path: %s" % dialog.getSelectedDataUrl().file_path())
            print("HDF5 group path : %s " % dialog.getSelectedDataUrl().data_path())
        else:
            print("Operation cancelled :(")

    """
    def __init__(self, parent=None):
        qt.QDialog.__init__(self, parent)
        self.setWindowTitle("HDF5 group selection")

        self._tree = Hdf5TreeView(self)
        self._tree.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._tree.activated.connect(self._onActivation)
        self._tree.selectionModel().selectionChanged.connect(
            self._onSelectionChange)

        self._model = self._tree.findHdf5TreeModel()

        self._header = self._tree.header()
        self._header.setSections([
            self._model.NAME_COLUMN, self._model.NODE_COLUMN,
            self._model.LINK_COLUMN
        ])

        _labelSubgroup = qt.QLabel(self)
        _labelSubgroup.setText("Subgroup name (optional)")
        self._lineEditSubgroup = qt.QLineEdit(self)
        self._lineEditSubgroup.setToolTip(
            "Specify the name of a new subgroup "
            "to be created in the selected group.")
        self._lineEditSubgroup.textChanged.connect(self._onSubgroupNameChange)

        _labelSelectionTitle = qt.QLabel(self)
        _labelSelectionTitle.setText("Current selection")
        self._labelSelection = qt.QLabel(self)
        self._labelSelection.setStyleSheet("color: gray")
        self._labelSelection.setWordWrap(True)
        self._labelSelection.setText("Select a group")

        buttonBox = qt.QDialogButtonBox()
        self._okButton = buttonBox.addButton(qt.QDialogButtonBox.Ok)
        self._okButton.setEnabled(False)
        buttonBox.addButton(qt.QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        vlayout = qt.QVBoxLayout(self)
        vlayout.addWidget(self._tree)
        vlayout.addWidget(_labelSubgroup)
        vlayout.addWidget(self._lineEditSubgroup)
        vlayout.addWidget(_labelSelectionTitle)
        vlayout.addWidget(self._labelSelection)
        vlayout.addWidget(buttonBox)
        self.setLayout(vlayout)

        self.setMinimumWidth(400)

        self._selectedUrl = None

    def addFile(self, path):
        """Add a HDF5 file to the tree.
        All groups it contains will be selectable in the dialog.

        :param str path: File path
        """
        self._model.insertFile(path)

    def addGroup(self, group):
        """Add a HDF5 group to the tree. This group and all its subgroups
        will be selectable in the dialog.

        :param h5py.Group group: HDF5 group
        """
        self._model.insertH5pyObject(group)

    def _onActivation(self, idx):
        # double-click or enter press
        nodes = list(self._tree.selectedH5Nodes())
        node = nodes[0]
        if silx.io.is_group(node.h5py_object):
            self.accept()

    def _onSelectionChange(self, old, new):
        self._updateUrl()

    def _onSubgroupNameChange(self, text):
        self._updateUrl()

    def _updateUrl(self):
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditSubgroup.text()
        if nodes:
            node = nodes[0]
            if silx.io.is_group(node.h5py_object):
                data_path = node.local_name
                if subgroupName.lstrip("/"):
                    if not data_path.endswith("/"):
                        data_path += "/"
                    data_path += subgroupName.lstrip("/")
                self._selectedUrl = DataUrl(file_path=node.local_filename,
                                            data_path=data_path)
                self._okButton.setEnabled(True)
                self._labelSelection.setText(self._selectedUrl.path())
            else:
                self._selectedUrl = None
                self._okButton.setEnabled(False)
                self._labelSelection.setText("Select a group")

    def getSelectedDataUrl(self):
        """Return a :class:`DataUrl` with a file path and a data path.
        Return None if the dialog was cancelled.

        :return: :class:`silx.io.url.DataUrl` object pointing to the
            selected group.
        """
        return self._selectedUrl
Example #22
0
 def test_silx_url(self):
     abs_a = os.path.abspath(self.a)
     url = DataUrl(abs_a).path()
     image = image_mdl.read_image_data(url)
     self.assertIsNotNone(image)
Example #23
0
class _Hdf5ItemSelectionDialog(qt.QDialog):
    SaveMode = 1
    """Mode used to set the HDF5 item selection dialog to *save* mode.
    This adds a text field to type in a new item name."""

    LoadMode = 2
    """Mode used to set the HDF5 item selection dialog to *load* mode.
    Only existing items of the HDF5 file can be selected in this mode."""

    def __init__(self, parent=None):
        qt.QDialog.__init__(self, parent)
        self.setWindowTitle("HDF5 item selection")

        self._tree = Hdf5TreeView(self)
        self._tree.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        self._tree.activated.connect(self._onActivation)
        self._tree.selectionModel().selectionChanged.connect(
            self._onSelectionChange)

        self._model = self._tree.findHdf5TreeModel()

        self._header = self._tree.header()

        self._newItemWidget = qt.QWidget(self)
        newItemLayout = qt.QVBoxLayout(self._newItemWidget)
        self._labelNewItem = qt.QLabel(self._newItemWidget)
        self._labelNewItem.setText("Create new item in selected group (optional):")
        self._lineEditNewItem = qt.QLineEdit(self._newItemWidget)
        self._lineEditNewItem.setToolTip(
                "Specify the name of a new item "
                "to be created in the selected group.")
        self._lineEditNewItem.textChanged.connect(
                self._onNewItemNameChange)
        newItemLayout.addWidget(self._labelNewItem)
        newItemLayout.addWidget(self._lineEditNewItem)

        _labelSelectionTitle = qt.QLabel(self)
        _labelSelectionTitle.setText("Current selection")
        self._labelSelection = qt.QLabel(self)
        self._labelSelection.setStyleSheet("color: gray")
        self._labelSelection.setWordWrap(True)
        self._labelSelection.setText("Select an item")

        buttonBox = qt.QDialogButtonBox()
        self._okButton = buttonBox.addButton(qt.QDialogButtonBox.Ok)
        self._okButton.setEnabled(False)
        buttonBox.addButton(qt.QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        vlayout = qt.QVBoxLayout(self)
        vlayout.addWidget(self._tree)
        vlayout.addWidget(self._newItemWidget)
        vlayout.addWidget(_labelSelectionTitle)
        vlayout.addWidget(self._labelSelection)
        vlayout.addWidget(buttonBox)
        self.setLayout(vlayout)

        self.setMinimumWidth(400)

        self._selectedUrl = None

    def _onSelectionChange(self, old, new):
        self._updateUrl()

    def _onNewItemNameChange(self, text):
        self._updateUrl()

    def _onActivation(self, idx):
        # double-click or enter press
        self.accept()

    def setMode(self, mode):
        """Set dialog mode DatasetDialog.SaveMode or DatasetDialog.LoadMode

        :param mode: DatasetDialog.SaveMode or DatasetDialog.LoadMode
        """
        if mode == self.LoadMode:
            # hide "Create new item" field
            self._lineEditNewItem.clear()
            self._newItemWidget.hide()
        elif mode == self.SaveMode:
            self._newItemWidget.show()
        else:
            raise ValueError("Invalid DatasetDialog mode %s" % mode)

    def addFile(self, path):
        """Add a HDF5 file to the tree.
        All groups it contains will be selectable in the dialog.

        :param str path: File path
        """
        self._model.insertFile(path)

    def addGroup(self, group):
        """Add a HDF5 group to the tree. This group and all its subgroups
        will be selectable in the dialog.

        :param h5py.Group group: HDF5 group
        """
        self._model.insertH5pyObject(group)

    def _updateUrl(self):
        nodes = list(self._tree.selectedH5Nodes())
        subgroupName = self._lineEditNewItem.text()
        if nodes:
            node = nodes[0]
            data_path = node.local_name
            if subgroupName.lstrip("/"):
                if not data_path.endswith("/"):
                    data_path += "/"
                data_path += subgroupName.lstrip("/")
            self._selectedUrl = DataUrl(file_path=node.local_filename,
                                        data_path=data_path)
            self._okButton.setEnabled(True)
            self._labelSelection.setText(
                    self._selectedUrl.path())

    def getSelectedDataUrl(self):
        """Return a :class:`DataUrl` with a file path and a data path.
        Return None if the dialog was cancelled.

        :return: :class:`silx.io.url.DataUrl` object pointing to the
            selected HDF5 item.
        """
        return self._selectedUrl