def show_mouse_toast(message):
    # Creates a text with empty space to get the height of the rendered text - this is used
    # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom.
    font_metrics = QFontMetrics(QFont(" "))
    # The height itself is divided by 2 just to reduce the offset so that the tooltip is
    # reasonably position relative to the cursor
    QToolTip.showText(QCursor.pos() + QPoint(font_metrics.height() / 2, 0), message)
Exemple #2
0
    def mouseMoveEvent(self, ev):
        if not self._image_item.width() or not self._image_item.height():
            super().mouseMoveEvent(ev)
            return
        pos = ev.pos()
        posaux = self._image_item.mapFromDevice(ev.pos())
        if posaux.x() < 0 or posaux.x() >= self._image_item.width() or \
                posaux.y() < 0 or posaux.y() >= self._image_item.height():
            super().mouseMoveEvent(ev)
            return

        pos_scene = self._view.mapSceneToView(pos)
        x = round(pos_scene.x())
        y = round(pos_scene.y())

        if self.xAxisChannel and self._last_xaxis_data is not None:
            maxx = len(self._last_xaxis_data) - 1
            x = x if x < maxx else maxx
            valx = self._last_xaxis_data[x]
        else:
            valx = x

        if self.yAxisChannel and self._last_yaxis_data is not None:
            maxy = len(self._last_yaxis_data) - 1
            y = y if y < maxy else maxy
            valy = self._last_yaxis_data[y]
        else:
            valy = y

        txt = self.format_tooltip.format(valx, valy)
        QToolTip.showText(self.mapToGlobal(pos), txt, self, self.geometry(),
                          5000)
        super().mouseMoveEvent(ev)
Exemple #3
0
    def show_state_channel(self, event):
        """
        Show the State Channel Tooltip and copy address to clipboard

        This is intended to replicate the behavior of the "middle click" from
        EDM. If the parent is not PCDSSymbolBase and does not have a valid
        State Channel nothing will be displayed.
        """
        from ..vacuum.base import PCDSSymbolBase

        p = find_ancestor_for_widget(self, PCDSSymbolBase)
        if not p:
            return

        state_suffix = getattr(p, '_state_suffix', None)
        if not state_suffix:
            return

        addr = "{}{}".format(p.channelsPrefix, state_suffix)
        QToolTip.showText(event.globalPos(), addr)
        # If the address has a protocol, strip it out before putting it on the
        # clipboard.
        copy_text = remove_protocol(addr)

        clipboard = QApplication.clipboard()
        clipboard.setText(copy_text)
        event = QEvent(QEvent.Clipboard)
        QApplication.instance().sendEvent(clipboard, event)
Exemple #4
0
 def _show_step_tooltip(self):
     QToolTip.showText(
         self.mapToGlobal(
             QPoint(self.x()+self.width()/2, self.y()-2*self.height())),
         'Single step: '+str(self.singleStep) +
         '\nPage step: '+str(self.pageStep),
         self, self.rect(), 1000)
Exemple #5
0
    def _show_tooltip(self, pos, pln='x'):
        unit = 'rad'
        if self.is_orb:
            names = self._csorb.bpm_nicknames
            posi = self._csorb.bpm_pos
            unit = 'm'
        elif pln == 'x':
            names = self._csorb.ch_nicknames
            posi = self._csorb.ch_pos
        else:
            names = self._csorb.cv_nicknames
            posi = self._csorb.cv_pos

        graph = self.graph[pln]
        curve = graph.curveAtIndex(0)
        posx = curve.scatter.mapFromScene(pos).x()
        if self._csorb.isring:
            posx = posx % self._csorb.circum
        ind = _np.argmin(_np.abs(_np.array(posi) - posx))
        posy = curve.scatter.mapFromScene(pos).y()

        sca, prf = functions.siScale(posy)
        txt = '{0:s}, y = {1:.3f} {2:s}'.format(names[ind], sca * posy,
                                                prf + unit)
        QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph,
                          graph.geometry(), 500)
Exemple #6
0
    def enterEvent(self, event):
        """Override to show tooltips instantly."""
        if self.toolTip():
            pos = self.mapToGlobal(self.contentsRect().center())
            QToolTip.showText(pos, self.toolTip(), self)

        super().enterEvent(event)
def show_mouse_toast(message):
    # Creates a text with empty space to get the height of the rendered text - this is used
    # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom.
    font_metrics = QFontMetrics(QFont(" "))
    # The height itself is divided by 2 just to reduce the offset so that the tooltip is
    # reasonably position relative to the cursor
    QToolTip.showText(QCursor.pos() + QPoint(font_metrics.height() / 2, 0),
                      message)
Exemple #8
0
 def mouseMoveEvent(self, event):
     """Reimplement mouseMoveEvent."""
     pos = event.pos()
     posx = self.curve.scatter.mapFromScene(pos).x()
     posx = posx % self._c0
     ind = _np.argmin(_np.abs(_np.array(self._x_data)-posx))
     txt = '{0:s}, x = {1:.3f} m'.format(self.tooltips[ind], posx)
     QToolTip.showText(
         self.mapToGlobal(pos), txt, self, self.geometry(), 500)
     super().mouseMoveEvent(event)
Exemple #9
0
 def eventFilter(self, obj, event):
     ret = super(BasePlot, self).eventFilter(obj, event)
     if utilities.is_qt_designer():
         if event.type() == QEvent.Enter:
             QToolTip.showText(
                 self.mapToGlobal(self.rect().center()),
                 'Edit plot curves via Right-Click and select "Edit Curves..."',
                 self,
                 QRect(0, 0, 200, 100),
                 4000)
     return ret
Exemple #10
0
 def _show_tooltip_time(self, pos):
     graph = self.graph_time
     curve = graph.curveAtIndex(0)
     posx = curve.scatter.mapFromScene(pos).x()
     times = curve.getData()[0]
     if times is None:
         return
     ind = _np.argmin(_np.abs(times - posx))
     txt = f'index = {ind:d}'
     QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph,
                       graph.geometry(), 500)
Exemple #11
0
    def show_calltip(self,
                     title,
                     text,
                     signature=False,
                     color='#2D62FF',
                     at_line=None,
                     at_position=None,
                     at_point=None):
        """Show calltip"""
        if text is None or len(text) == 0:
            return

        # Saving cursor position:
        if at_position is None:
            at_position = self.get_position('cursor')
        self.calltip_position = at_position

        # Preparing text:
        if signature:
            text, wrapped_textlines = self._format_signature(text)
        else:
            if isinstance(text, list):
                text = "\n    ".join(text)
            text = text.replace('\n', '<br>')
            if len(text) > self.calltip_size:
                text = text[:self.calltip_size] + " ..."

        # Formatting text
        font = self.font()
        size = font.pointSize()
        family = font.family()
        format1 = '<div style=\'font-family: "%s"; font-size: %spt; color: %s\'>'\
                  % (family, size, color)
        format2 = '<div style=\'font-family: "%s"; font-size: %spt\'>'\
                  % (family, size-1 if size > 9 else size)
        tiptext = format1 + ('<b>%s</b></div>' % title) + '<hr>' + \
                  format2 + text + "</div>"

        # Showing tooltip at cursor position:
        cx, cy = self.get_coordinates('cursor')
        if at_point is not None:
            cx, cy = at_point.x(), at_point.y()
        if at_line is not None:
            cx = 5
            cursor = QTextCursor(self.document().findBlockByNumber(at_line -
                                                                   1))
            cy = self.cursorRect(cursor).top()
        point = self.mapToGlobal(QPoint(cx, cy))
        point = self.calculate_real_position(point)
        point.setY(point.y() + font.pointSize() + 5)
        if signature:
            self.calltip_widget.show_tip(point, tiptext, wrapped_textlines)
        else:
            QToolTip.showText(point, tiptext)
 def event(self, event: QEvent):
     if event.type() == QEvent.ToolTip and self.components:
         # text = str(self.component)
         text_list = []
         for el in self.components:
             if self.settings.component_is_chosen(el):
                 text_list.append("☑{}".format(el))
             else:
                 text_list.append("☐{}".format(el))
         QToolTip.showText(event.globalPos(), " ".join(text_list))
     return super().event(event)
Exemple #13
0
 def update_warning(self):
     """
     Updates the icon and tip based on the validity of the array content.
     """
     widget = self._button_warning
     if not self.is_valid():
         tip = _('Array dimensions not valid')
         widget.setIcon(ima.icon('MessageBoxWarning'))
         widget.setToolTip(tip)
         QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)
     else:
         self._button_warning.setToolTip('')
Exemple #14
0
 def update_warning(self):
     """
     Updates the icon and tip based on the validity of the array content.
     """
     widget = self._button_warning
     if not self.is_valid():
         tip = _('Array dimensions not valid')
         widget.setIcon(ima.icon('MessageBoxWarning'))
         widget.setToolTip(tip)
         QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)
     else:
         self._button_warning.setToolTip('')
Exemple #15
0
    def eventFilter(self, obj, event):
        ret = super(BasePlot, self).eventFilter(obj, event)
        if utilities.is_qt_designer():
            if event.type() == QEvent.Enter:
                QToolTip.showText(
                    self.mapToGlobal(self.rect().center()),
                    'Edit plot curves via Right-Click and select "Edit Curves..."',
                    self, QRect(0, 0, 200, 100), 4000)
        else:
            # Somehow super here is not invoking the PyDMPrimitiveWidget
            # eventFilter
            ret = PyDMPrimitiveWidget.eventFilter(self, obj, event)

        return ret
Exemple #16
0
    def mouseMoveEvent(self, ev):
        unit = 'urad'
        pos = ev.pos()

        posx = self.curve.scatter.mapFromScene(pos).x()
        posx = posx % self.c0
        ind = _np.argmin(_np.abs(_np.array(self.xdata) - posx))
        posy = self.curve.scatter.mapFromScene(pos).y()

        sca, prf = functions.siScale(posy)
        txt = '{0:s}, y = {1:.3f} {2:s}'.format(self.tooltip_names[ind],
                                                sca * posy, prf + unit)
        QToolTip.showText(self.mapToGlobal(pos), txt, self, self.geometry(),
                          500)
Exemple #17
0
    def show_calltip(self, title, text, signature=False, color='#2D62FF',
                     at_line=None, at_position=None, at_point=None):
        """Show calltip"""
        if text is None or len(text) == 0:
            return

        # Saving cursor position:
        if at_position is None:
            at_position = self.get_position('cursor')
        self.calltip_position = at_position

        # Preparing text:
        if signature:
            text, wrapped_textlines = self._format_signature(text)
        else:
            if isinstance(text, list):
                text = "\n    ".join(text)
            text = text.replace('\n', '<br>')
            if len(text) > self.calltip_size:
                text = text[:self.calltip_size] + " ..."

        # Formatting text
        font = self.font()
        size = font.pointSize()
        family = font.family()
        format1 = '<div style=\'font-family: "%s"; font-size: %spt; color: %s\'>'\
                  % (family, size, color)
        format2 = '<div style=\'font-family: "%s"; font-size: %spt\'>'\
                  % (family, size-1 if size > 9 else size)
        tiptext = format1 + ('<b>%s</b></div>' % title) + '<hr>' + \
                  format2 + text + "</div>"

        # Showing tooltip at cursor position:
        cx, cy = self.get_coordinates('cursor')
        if at_point is not None:
            cx, cy = at_point.x(), at_point.y()
        if at_line is not None:
            cx = 5
            cursor = QTextCursor(self.document().findBlockByNumber(at_line-1))
            cy = self.cursorRect(cursor).top()
        point = self.mapToGlobal(QPoint(cx, cy))
        point = self.calculate_real_position(point)
        point.setY(point.y()+font.pointSize()+5)
        if signature:
            self.calltip_widget.show_tip(point, tiptext, wrapped_textlines)
        else:
            QToolTip.showText(point, tiptext)
Exemple #18
0
 def event(self, e):
     if (e.type() == QEvent.ToolTip
             and self._qt_viewer.viewer.tooltip.visible):
         QToolTip.showText(e.globalPos(),
                           self._qt_viewer.viewer.tooltip.text, self)
     if e.type() == QEvent.Close:
         # when we close the MainWindow, remove it from the instances list
         try:
             _QtMainWindow._instances.remove(self)
         except ValueError:
             pass
     if e.type() in {QEvent.WindowActivate, QEvent.ZOrderChange}:
         # upon activation or raise_, put window at the end of _instances
         try:
             inst = _QtMainWindow._instances
             inst.append(inst.pop(inst.index(self)))
         except ValueError:
             pass
     return super().event(e)
Exemple #19
0
    def show_address_tooltip(self, event):
        """
        Show the PyDMTooltip and copy address to clipboard

        This is intended to replicate the behavior of the "middle click" from
        EDM. If the QWidget does not have a valid PyDMChannel nothing will be
        displayed
        """
        channels_method = getattr(self, 'channels', None)
        if channels_method is None:
            return
        channels = channels_method()
        if not channels:
            logger.debug('Widget has no channels to display tooltip')
            return

        addrs = []
        no_proto_addrs = []
        for ch in channels:
            addr = ch.address
            if not addr:
                continue
            addrs.append(addr)
            no_proto_addrs.append(remove_protocol(addr))

        tooltip = os.linesep.join(addrs)
        clipboard_text = " ".join(no_proto_addrs)
        QToolTip.showText(event.globalPos(), tooltip)
        # If the address has a protocol, strip it out before putting it on the
        # clipboard.

        clipboard = QApplication.clipboard()

        mode = clipboard.Clipboard
        if platform.system() == 'Linux':
            # Mode Selection is only valid for X11.
            mode = clipboard.Selection

        clipboard.setText(clipboard_text, mode=mode)
        event = QEvent(QEvent.Clipboard)
        self.app.sendEvent(clipboard, event)
Exemple #20
0
    def show_address_tooltip(self, event):
        """
        Show the PyDMTooltip and copy address to clipboard

        This is intended to replicate the behavior of the "middle click" from
        EDM. If the QWidget does not have a valid PyDMChannel nothing will be
        displayed
        """
        if not len(self._channels):
            logger.warning("Object %r has no PyDM Channels", self)
            return
        addr = self.channels()[0].address
        QToolTip.showText(event.globalPos(), addr)
        # If the address has a protocol, strip it out before putting it on the
        # clipboard.
        copy_text = remove_protocol(addr)

        clipboard = QApplication.clipboard()
        clipboard.setText(copy_text)
        event = QEvent(QEvent.Clipboard)
        self.app.sendEvent(clipboard, event)
Exemple #21
0
    def show_address_tooltip(self, event):
        """
        Show the PyDMTooltip and copy address to clipboard

        This is intended to replicate the behavior of the "middle click" from
        EDM. If the QWidget does not have a valid PyDMChannel nothing will be
        displayed
        """
        if not len(self._channels):
            logger.warning("Object %r has no PyDM Channels", self)
            return
        addr = self.channels()[0].address
        QToolTip.showText(event.globalPos(), addr)
        # If the address has a protocol, strip it out before putting it on the
        # clipboard.
        copy_text = remove_protocol(addr)

        clipboard = QApplication.clipboard()
        clipboard.setText(copy_text)
        event = QEvent(QEvent.Clipboard)
        self.app.sendEvent(clipboard, event)
Exemple #22
0
    def _show_tooltip(self, pos):
        names = self._csorb.bpm_nicknames
        cname = self._csorb.ch_nicknames + self._csorb.cv_nicknames
        if self._csorb.isring:
            cname += [
                'RF',
            ]
        posi = self._csorb.bpm_pos

        graph = self.graph
        curve = graph.curveAtIndex(0)
        posx = curve.scatter.mapFromScene(pos).x()
        if self._csorb.isring:
            posx = posx % self._csorb.circum
        ind = _np.argmin(_np.abs(_np.array(posi) - posx))
        posy = curve.scatter.mapFromScene(pos).y()

        indy = int(posy // self.spbox.value())
        indy = max(min(indy, len(cname) - 1), 0)
        # sca, prf = functions.siScale(posy)
        txt = 'BPM = {0:s}, Corr = {1:s}'.format(names[ind], cname[indy])
        QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph,
                          graph.geometry(), 500)
Exemple #23
0
    def wheelEvent(self, event: QWheelEvent) -> None:
        """Switch function by mouse wheel.

        + Set zoom bar value.
        + Set select mode.
        """
        p = event.angleDelta()
        if QApplication.keyboardModifiers() == Qt.ShiftModifier:
            value = p.y()
        elif p.x() != 0:
            value = p.x()
        elif p.y() != 0:
            value = self.prefer.scale_factor_option * (1 if p.y() > 0 else -1)
            value += self.zoom_value()
            self.set_zoom_bar(value)
            return
        else:
            return
        tags = ("Points", "Links")
        mode = (self.selection_mode() + (-1 if value > 0 else 1)) % len(tags)
        self.selection_mode_wheel(mode)
        QToolTip.showText(event.globalPos(), f"Selection mode: {tags[mode]}", self)
        event.accept()
Exemple #24
0
 def show_tip(self, tip=""):
     """Show tip"""
     QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
Exemple #25
0
    def show_mouse_toast(self, message):
        if not sys.platform == "win32":
            # There is no reason to draw tooltips for OSs that don't display anything
            return

        QToolTip.showText(self._get_mouse_position(), message)
Exemple #26
0
 def mouseReleaseEvent(self, event):
     QToolTip.showText(self.mapToGlobal(QPoint(0, self.height())),
                       self._tip_text)
Exemple #27
0
 def show_tip(self, tip=""):
     """Show tip"""
     QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
Exemple #28
0
 def mouseReleaseEvent(self, event):
     QToolTip.showText(self.mapToGlobal(QPoint(0, self.height())),
                       self._tip_text)
Exemple #29
0
 def mouseMoveEvent(self, event):
     """Display a position of media if the mouse is on the progressbar."""
     x_pos = event.pos().x()
     position_ms = self.convert_mouse_pos_to_media_pos(x_pos)
     QToolTip.showText(event.globalPos(), ms2min_sec(position_ms))
     super().mouseMoveEvent(event)
Exemple #30
0
 def event(self, event: QEvent):
     if event.type() == QEvent.ToolTip and self.components:
         text = self.get_tool_tip_text()
         if text:
             QToolTip.showText(event.globalPos(), text)
     return super().event(event)
Exemple #31
0
 def on_editor_text_edited():
     if not editor.hasAcceptableInput():
         QToolTip.showText(editor.mapToGlobal(QPoint()), msg)
     else:
         QToolTip.hideText()
Exemple #32
0
    def mouse_move(self, event):
        """
        Event handler for matplotlib motion_notify_event.
        Updates coord display and vars.
        :param event: matplotlib event.
        """
        # Check if mouse is in widget but not on plot
        if not event.inaxes:
            self.is_mouse_over = False
            self.clear_coords()
            return
        mouse_pos = QCursor.pos()
        self.is_mouse_over = True

        # If hold_coords is active, return
        if self.hold_coords:
            return

        # Get x and y of the pixel under the mouse
        x, y = [int(event.xdata + 0.5), int(event.ydata + 0.5)]
        self.x_mouse, self.y_mouse = [x, y]

        # Create coord display string
        if self._slice_index is not None:
            string = "({:1.0f}, {:1.0f}, {:1.0f})".format(
                x, y, self._slice_index)
        else:
            string = "({:1.0f}, {:1.0f})".format(x, y)

        self.mouse_value = ""

        # If viewer has a layer.
        if len(self.visible_layers()) > 0:

            arr = self.first_visible_layer().state.get_sliced_data()

            if 0 <= y < arr.shape[0] and 0 <= x < arr.shape[1]:
                # if x and y are in bounds. Note: x and y are swapped in array.
                # get value and check if wcs is obtainable
                # WCS:
                if len(self.figure.axes) > 0:
                    wcs = self.figure.axes[0].wcs.celestial
                    if wcs is not None:
                        # Check the number of axes in the WCS and add to string
                        ra = dec = None
                        if wcs.naxis == 3 and self.slice_index is not None:
                            ra, dec, wave = wcs.wcs_pix2world(
                                [[x, y, self._slice_index]], 0)[0]
                        elif wcs.naxis == 2:
                            ra, dec = wcs.wcs_pix2world([[x, y]], 0)[0]

                        if ra is not None and dec is not None:
                            string = string + " " + self._coords_format_function(
                                ra, dec)
                # Pixel Value:
                v = arr[y][x]
                if self.cubeviz_unit is not None:
                    wave = self.cubeviz_layout.get_wavelength(self.slice_index)
                    v = self.cubeviz_unit.convert_value(v, wave=wave)

                unit_string = ""
                if self.component_unit_label:
                    unit_string = "[{0}]".format(self.component_unit_label)

                if 0.001 <= abs(v) <= 1000 or abs(v) == 0.0:
                    value_string = "{0:.3f} ".format(v)
                else:
                    value_string = "{0:.3e} ".format(v)

                self.mouse_value = value_string + unit_string
                string = value_string + string
        # Add a gap to string and add to viewer.
        string += " "
        self._dont_update_status = True
        self.statusBar().clearMessage()
        self._dont_update_status = False
        self.coord_label.setText(string)

        if self._is_tooltip_on:
            if self.mouse_value:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, self.mouse_value, self)
            else:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, " ", self)

        return
    def mouse_move(self, event):
        """
        Event handler for matplotlib motion_notify_event.
        Updates coord display and vars.
        :param event: matplotlib event.
        """
        # Check if mouse is in widget but not on plot
        if not event.inaxes:
            self.is_mouse_over = False
            self.clear_coords()
            return
        mouse_pos = QCursor.pos()
        self.is_mouse_over = True

        # If hold_coords is active, return
        if self.hold_coords:
            return

        # Get x and y of the pixel under the mouse
        x, y = [int(event.xdata + 0.5), int(event.ydata + 0.5)]
        self.x_mouse, self.y_mouse = [x, y]

        # Create coord display string
        if self._slice_index is not None:
            string = "({:1.0f}, {:1.0f}, {:1.0f})".format(x, y, self._slice_index)
        else:
            string = "({:1.0f}, {:1.0f})".format(x, y)

        self.mouse_value = ""

        # If viewer has a layer.
        if len(self.visible_layers()) > 0:

            arr = self.first_visible_layer().state.get_sliced_data()

            if 0 <= y < arr.shape[0] and 0 <= x < arr.shape[1]:
                # if x and y are in bounds. Note: x and y are swapped in array.
                # get value and check if wcs is obtainable
                # WCS:
                if len(self.figure.axes) > 0:
                    wcs = self.figure.axes[0].wcs.celestial
                    if wcs is not None:
                        # Check the number of axes in the WCS and add to string
                        ra = dec = None
                        if wcs.naxis == 3 and self.slice_index is not None:
                            ra, dec, wave = wcs.wcs_pix2world([[x, y, self._slice_index]], 0)[0]
                        elif wcs.naxis == 2:
                            ra, dec = wcs.wcs_pix2world([[x, y]], 0)[0]

                        if ra is not None and dec is not None:
                            string = string + " " + self._coords_format_function(ra, dec)
                # Pixel Value:
                v = arr[y][x]
                if self.cubeviz_unit is not None:
                    wave = self.cubeviz_layout.get_wavelength(self.slice_index)
                    v = self.cubeviz_unit.convert_value(v, wave=wave)

                unit_string = ""
                if self.component_unit_label:
                    unit_string = "[{0}]".format(self.component_unit_label)

                if 0.001 <= abs(v) <= 1000 or abs(v) == 0.0:
                    value_string = "{0:.3f} ".format(v)
                else:
                    value_string = "{0:.3e} ".format(v)

                self.mouse_value = value_string + unit_string
                string = value_string + string
        # Add a gap to string and add to viewer.
        string += " "
        self._dont_update_status = True
        self.statusBar().clearMessage()
        self._dont_update_status = False
        self.coord_label.setText(string)

        if self._is_tooltip_on:
            if self.mouse_value:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, self.mouse_value, self)
            else:
                QToolTip.showText(mouse_pos, "...", self)
                QToolTip.showText(mouse_pos, " ", self)

        return