Ejemplo n.º 1
0
    def init_help_menu(self):
        # please keep the Help menu in Mac Os even if empty. It will
        # automatically contain a search field to search inside menus and
        # please keep it spelled in English, as long as Qt Doesn't support
        # a QAction.MenuRole like HelpMenuRole otherwise it will lose
        # this search field functionality

        self.help_menu = self.menuBar().addMenu("&Help")

        # Help Menu

        self.intro_active_frontend_action = QtGui.QAction(
            "&Intro to IPython", self, triggered=self.intro_active_frontend)
        self.add_menu_action(self.help_menu, self.intro_active_frontend_action)

        self.quickref_active_frontend_action = QtGui.QAction(
            "IPython &Cheat Sheet",
            self,
            triggered=self.quickref_active_frontend)
        self.add_menu_action(self.help_menu,
                             self.quickref_active_frontend_action)

        self.guiref_active_frontend_action = QtGui.QAction(
            "&Qt Console", self, triggered=self.guiref_active_frontend)
        self.add_menu_action(self.help_menu,
                             self.guiref_active_frontend_action)

        self.onlineHelpAct = QtGui.QAction("Open Online &Help",
                                           self,
                                           triggered=self._open_online_help)
        self.add_menu_action(self.help_menu, self.onlineHelpAct)
Ejemplo n.º 2
0
def get_font(family, fallback=None):
    """Return a font of the requested family, using fallback as alternative.

    If a fallback is provided, it is used in case the requested family isn't
    found.  If no fallback is given, no alternative is chosen and Qt's internal
    algorithms may automatically choose a fallback font.

    Parameters
    ----------
    family : str
      A font name.
    fallback : str
      A font name.

    Returns
    -------
    font : QFont object
    """
    font = QtGui.QFont(family)
    # Check whether we got what we wanted using QFontInfo, since exactMatch()
    # is overly strict and returns false in too many cases.
    font_info = QtGui.QFontInfo(font)
    if fallback is not None and font_info.family() != family:
        font = QtGui.QFont(fallback)
    return font
Ejemplo n.º 3
0
def svg_to_image(string, size=None):
    """ Convert a SVG document to a QImage.

    Parameters
    ----------
    string : basestring
        A Python string containing a SVG document.

    size : QSize, optional
        The size of the image that is produced. If not specified, the SVG
        document's default size is used.
    
    Raises
    ------
    ValueError
        If an invalid SVG string is provided.

    Returns
    -------
    A QImage of format QImage.Format_ARGB32.
    """
    if isinstance(string, unicode_type):
        string = string.encode('utf-8')

    renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
    if not renderer.isValid():
        raise ValueError('Invalid SVG data.')

    if size is None:
        size = renderer.defaultSize()
    image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
    painter = QtGui.QPainter(image)
    renderer.render(painter)
    return image
Ejemplo n.º 4
0
    def paintEvent(self, event):
        """ Reimplemented to paint the background panel.
        """
        painter = QtGui.QStylePainter(self)
        option = QtGui.QStyleOptionFrame()
        option.initFrom(self)
        painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option)
        painter.end()

        super(CallTipWidget, self).paintEvent(event)
Ejemplo n.º 5
0
    def __init__(self, *args, **kw):
        super(FrontendWidget, self).__init__(*args, **kw)
        # FIXME: remove this when PySide min version is updated past 1.0.7
        # forcefully disable calltips if PySide is < 1.0.7, because they crash
        if qt.QT_API == qt.QT_API_PYSIDE:
            import PySide
            if PySide.__version_info__ < (1, 0, 7):
                self.log.warn(
                    "PySide %s < 1.0.7 detected, disabling calltips" %
                    PySide.__version__)
                self.enable_calltips = False

        # FrontendWidget protected variables.
        self._bracket_matcher = BracketMatcher(self._control)
        self._call_tip_widget = CallTipWidget(self._control)
        self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
        self._hidden = False
        self._highlighter = FrontendHighlighter(self, lexer=self.lexer)
        self._input_splitter = self._input_splitter_class()
        self._kernel_manager = None
        self._kernel_client = None
        self._request_info = {}
        self._request_info['execute'] = {}
        self._callback_dict = {}
        self._display_banner = True

        # Configure the ConsoleWidget.
        self.tab_width = 4
        self._set_continuation_prompt('... ')

        # Configure the CallTipWidget.
        self._call_tip_widget.setFont(self.font)
        self.font_changed.connect(self._call_tip_widget.setFont)

        # Configure actions.
        action = self._copy_raw_action
        key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
        action.setEnabled(False)
        action.setShortcut(QtGui.QKeySequence(key))
        action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
        action.triggered.connect(self.copy_raw)
        self.copy_available.connect(action.setEnabled)
        self.addAction(action)

        # Connect signal handlers.
        document = self._control.document()
        document.contentsChange.connect(self._document_contents_change)

        # Set flag for whether we are connected via localhost.
        self._local_kernel = kw.get('local_kernel',
                                    FrontendWidget._local_kernel)

        # Whether or not a clear_output call is pending new output.
        self._pending_clearoutput = False
Ejemplo n.º 6
0
    def __init__(self, name, parent):
        super(MagicHelper, self).__init__(name, parent)

        self.data = None

        class MinListWidget(QtGui.QListWidget):
            """Temp class to overide the default QListWidget size hint
               in order to make MagicHelper narrow
            """
            def sizeHint(self):
                s = QtCore.QSize()
                s.setHeight(super(MinListWidget,self).sizeHint().height())
                s.setWidth(self.sizeHintForColumn(0))
                return s

        # construct content
        self.frame = QtGui.QFrame()
        self.search_label = QtGui.QLabel("Search:")
        self.search_line = QtGui.QLineEdit()
        self.search_class = QtGui.QComboBox()
        self.search_list = MinListWidget()
        self.paste_button = QtGui.QPushButton("Paste")
        self.run_button = QtGui.QPushButton("Run")
        
        # layout all the widgets
        main_layout = QtGui.QVBoxLayout()
        search_layout = QtGui.QHBoxLayout()
        search_layout.addWidget(self.search_label)
        search_layout.addWidget(self.search_line, 10)
        main_layout.addLayout(search_layout)
        main_layout.addWidget(self.search_class)
        main_layout.addWidget(self.search_list, 10)
        action_layout = QtGui.QHBoxLayout()
        action_layout.addWidget(self.paste_button)
        action_layout.addWidget(self.run_button)
        main_layout.addLayout(action_layout)

        self.frame.setLayout(main_layout)
        self.setWidget(self.frame)

        # connect all the relevant signals to handlers
        self.visibilityChanged[bool].connect( self._update_magic_helper )
        self.search_class.activated[int].connect( 
            self.class_selected
        )
        self.search_line.textChanged[str].connect(
            self.search_changed
        )
        self.search_list.itemDoubleClicked.connect(
            self.paste_requested
        )
        self.paste_button.clicked[bool].connect(
            self.paste_requested
        )
        self.run_button.clicked[bool].connect(
            self.run_requested
        )
Ejemplo n.º 7
0
    def __init__(self, text_edit):
        """ Create a call tip manager that is attached to the specified Qt
            text edit widget.
        """
        assert isinstance(text_edit, (QtGui.QTextEdit, QtGui.QPlainTextEdit))
        super(BracketMatcher, self).__init__()

        # The format to apply to matching brackets.
        self.format = QtGui.QTextCharFormat()
        self.format.setBackground(QtGui.QColor('silver'))

        self._text_edit = text_edit
        text_edit.cursorPositionChanged.connect(self._cursor_position_changed)
Ejemplo n.º 8
0
    def init_edit_menu(self):
        self.edit_menu = self.menuBar().addMenu("&Edit")

        self.undo_action = QtGui.QAction(
            "&Undo",
            self,
            shortcut=QtGui.QKeySequence.Undo,
            statusTip="Undo last action if possible",
            triggered=self.undo_active_frontend)
        self.add_menu_action(self.edit_menu, self.undo_action)

        self.redo_action = QtGui.QAction(
            "&Redo",
            self,
            shortcut=QtGui.QKeySequence.Redo,
            statusTip="Redo last action if possible",
            triggered=self.redo_active_frontend)
        self.add_menu_action(self.edit_menu, self.redo_action)

        self.edit_menu.addSeparator()

        self.cut_action = QtGui.QAction("&Cut",
                                        self,
                                        shortcut=QtGui.QKeySequence.Cut,
                                        triggered=self.cut_active_frontend)
        self.add_menu_action(self.edit_menu, self.cut_action, True)

        self.copy_action = QtGui.QAction("&Copy",
                                         self,
                                         shortcut=QtGui.QKeySequence.Copy,
                                         triggered=self.copy_active_frontend)
        self.add_menu_action(self.edit_menu, self.copy_action, True)

        self.copy_raw_action = QtGui.QAction(
            "Copy (&Raw Text)",
            self,
            shortcut="Ctrl+Shift+C",
            triggered=self.copy_raw_active_frontend)
        self.add_menu_action(self.edit_menu, self.copy_raw_action, True)

        self.paste_action = QtGui.QAction("&Paste",
                                          self,
                                          shortcut=QtGui.QKeySequence.Paste,
                                          triggered=self.paste_active_frontend)
        self.add_menu_action(self.edit_menu, self.paste_action, True)

        self.edit_menu.addSeparator()

        selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
        if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
            # Only override the default if there is a collision.
            # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
            selectall = "Ctrl+Shift+A"
        self.select_all_action = QtGui.QAction(
            "Select &All",
            self,
            shortcut=selectall,
            triggered=self.select_all_active_frontend)
        self.add_menu_action(self.edit_menu, self.select_all_action, True)
Ejemplo n.º 9
0
 def setUpClass(cls):
     """ Create the application for the test case.
     """
     cls._app = QtGui.QApplication.instance()
     if cls._app is None:
         cls._app = QtGui.QApplication([])
     cls._app.setQuitOnLastWindowClosed(False)
Ejemplo n.º 10
0
 def _get_color(self, color):
     """ Returns a QColor built from a Pygments color string.
     """
     qcolor = QtGui.QColor()
     qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16),
                   int(color[4:6], base=16))
     return qcolor
Ejemplo n.º 11
0
 def _insert_img(self, cursor, img, fmt, metadata=None):
     """ insert a raw image, jpg or png """
     if metadata:
         width = metadata.get('width', None)
         height = metadata.get('height', None)
     else:
         width = height = None
     try:
         image = QtGui.QImage()
         image.loadFromData(img, fmt.upper())
         if width and height:
             image = image.scaled(
                 width,
                 height,
                 transformMode=QtCore.Qt.SmoothTransformation)
         elif width and not height:
             image = image.scaledToWidth(
                 width, transformMode=QtCore.Qt.SmoothTransformation)
         elif height and not width:
             image = image.scaledToHeight(
                 height, transformMode=QtCore.Qt.SmoothTransformation)
     except ValueError:
         self._insert_plain_text(cursor, 'Received invalid %s data.' % fmt)
     else:
         format = self._add_image(image)
         cursor.insertBlock()
         cursor.insertImage(format)
         cursor.insertBlock()
Ejemplo n.º 12
0
def save_svg(string, parent=None):
    """ Prompts the user to save an SVG document to disk.

    Parameters
    ----------
    string : basestring
        A Python string containing a SVG document.

    parent : QWidget, optional
        The parent to use for the file dialog.

    Returns
    -------
    The name of the file to which the document was saved, or None if the save
    was cancelled.
    """
    if isinstance(string, unicode_type):
        string = string.encode('utf-8')

    dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
    dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
    dialog.setDefaultSuffix('svg')
    dialog.setNameFilter('SVG document (*.svg)')
    if dialog.exec_():
        filename = dialog.selectedFiles()[0]
        f = open(filename, 'wb')
        try:
            f.write(string)
        finally:
            f.close()
        return filename
    return None
Ejemplo n.º 13
0
 def _get_brush(self, color):
     """ Returns a brush for the color.
     """
     result = self._brushes.get(color)
     if result is None:
         qcolor = self._get_color(color)
         result = QtGui.QBrush(qcolor)
         self._brushes[color] = result
     return result
Ejemplo n.º 14
0
    def init_file_menu(self):
        self.file_menu = self.menuBar().addMenu("&File")

        self.new_kernel_tab_act = QtGui.QAction(
            "New Tab with &New kernel",
            self,
            shortcut="Ctrl+T",
            triggered=self.create_tab_with_new_frontend)
        self.add_menu_action(self.file_menu, self.new_kernel_tab_act)

        self.slave_kernel_tab_act = QtGui.QAction(
            "New Tab with Sa&me kernel",
            self,
            shortcut="Ctrl+Shift+T",
            triggered=self.create_tab_with_current_kernel)
        self.add_menu_action(self.file_menu, self.slave_kernel_tab_act)

        self.file_menu.addSeparator()

        self.close_action = QtGui.QAction("&Close Tab",
                                          self,
                                          shortcut=QtGui.QKeySequence.Close,
                                          triggered=self.close_active_frontend)
        self.add_menu_action(self.file_menu, self.close_action)

        self.export_action = QtGui.QAction(
            "&Save to HTML/XHTML",
            self,
            shortcut=QtGui.QKeySequence.Save,
            triggered=self.export_action_active_frontend)
        self.add_menu_action(self.file_menu, self.export_action, True)

        self.file_menu.addSeparator()

        printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
        if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
            # Only override the default if there is a collision.
            # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
            printkey = "Ctrl+Shift+P"
        self.print_action = QtGui.QAction(
            "&Print",
            self,
            shortcut=printkey,
            triggered=self.print_action_active_frontend)
        self.add_menu_action(self.file_menu, self.print_action, True)

        if sys.platform != 'darwin':
            # OSX always has Quit in the Application menu, only add it
            # to the File menu elsewhere.

            self.file_menu.addSeparator()

            self.quit_action = QtGui.QAction(
                "&Quit",
                self,
                shortcut=QtGui.QKeySequence.Quit,
                triggered=self.close,
            )
            self.add_menu_action(self.file_menu, self.quit_action)
Ejemplo n.º 15
0
    def closeEvent(self, event):
        """ Forward the close event to every tabs contained by the windows
        """
        if self.tab_widget.count() == 0:
            # no tabs, just close
            event.accept()
            return
        # Do Not loop on the widget count as it change while closing
        title = self.window().windowTitle()
        cancel = QtGui.QMessageBox.Cancel
        okay = QtGui.QMessageBox.Ok
        accept_role = QtGui.QMessageBox.AcceptRole

        if self.confirm_exit:
            if self.tab_widget.count() > 1:
                msg = "Close all tabs, stop all kernels, and Quit?"
            else:
                msg = "Close console, stop kernel, and Quit?"
            info = "Kernels not started here (e.g. notebooks) will be left alone."
            closeall = QtGui.QPushButton("&Quit", self)
            closeall.setShortcut('Q')
            box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg)
            box.setInformativeText(info)
            box.addButton(cancel)
            box.addButton(closeall, QtGui.QMessageBox.YesRole)
            box.setDefaultButton(closeall)
            box.setEscapeButton(cancel)
            pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64, 64)))
            box.setIconPixmap(pixmap)
            reply = box.exec_()
        else:
            reply = okay

        if reply == cancel:
            event.ignore()
            return
        if reply == okay or reply == accept_role:
            while self.tab_widget.count() >= 1:
                # prevent further confirmations:
                widget = self.active_frontend
                widget._confirm_exit = False
                self.close_tab(widget)
            event.accept()
Ejemplo n.º 16
0
 def _add_image(self, image):
     """ Adds the specified QImage to the document and returns a
         QTextImageFormat that references it.
     """
     document = self._control.document()
     name = str(image.cacheKey())
     document.addResource(QtGui.QTextDocument.ImageResource,
                          QtCore.QUrl(name), image)
     format = QtGui.QTextImageFormat()
     format.setName(name)
     return format
Ejemplo n.º 17
0
 def _save_image(self, name, format='PNG'):
     """ Shows a save dialog for the ImageResource with 'name'.
     """
     dialog = QtGui.QFileDialog(self._control, 'Save Image')
     dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
     dialog.setDefaultSuffix(format.lower())
     dialog.setNameFilter('%s file (*.%s)' % (format, format.lower()))
     if dialog.exec_():
         filename = dialog.selectedFiles()[0]
         image = self._get_image(name)
         image.save(filename, format)
Ejemplo n.º 18
0
    def test_qt_cursor(self):
        """ Does the Qt kill ring maintain state with cursor movement?
        """
        text_edit = QtGui.QPlainTextEdit()
        ring = QtKillRing(text_edit)

        ring.kill('foo')
        ring.kill('bar')
        ring.yank()
        text_edit.moveCursor(QtGui.QTextCursor.Left)
        ring.rotate()
        self.assertEqual(text_edit.toPlainText(), 'bar')
Ejemplo n.º 19
0
    def get_color(self, color, intensity=0):
        """ Returns a QColor for a given color code, or None if one cannot be
            constructed.
        """
        if color is None:
            return None

        # Adjust for intensity, if possible.
        if color < 8 and intensity > 0:
            color += 8

        constructor = self.color_map.get(color, None)
        if isinstance(constructor, string_types):
            # If this is an X11 color name, we just hope there is a close SVG
            # color name. We could use QColor's static method
            # 'setAllowX11ColorNames()', but this is global and only available
            # on X11. It seems cleaner to aim for uniformity of behavior.
            return QtGui.QColor(constructor)

        elif isinstance(constructor, (tuple, list)):
            return QtGui.QColor(*constructor)

        return None
Ejemplo n.º 20
0
    def init_window_menu(self):
        self.window_menu = self.menuBar().addMenu("&Window")
        if sys.platform == 'darwin':
            # add min/maximize actions to OSX, which lacks default bindings.
            self.minimizeAct = QtGui.QAction(
                "Mini&mize",
                self,
                shortcut="Ctrl+m",
                statusTip="Minimize the window/Restore Normal Size",
                triggered=self.toggleMinimized)
            # maximize is called 'Zoom' on OSX for some reason
            self.maximizeAct = QtGui.QAction(
                "&Zoom",
                self,
                shortcut="Ctrl+Shift+M",
                statusTip="Maximize the window/Restore Normal Size",
                triggered=self.toggleMaximized)

            self.add_menu_action(self.window_menu, self.minimizeAct)
            self.add_menu_action(self.window_menu, self.maximizeAct)
            self.window_menu.addSeparator()

        prev_key = "Ctrl+Shift+Left" if sys.platform == 'darwin' else "Ctrl+PgUp"
        self.prev_tab_act = QtGui.QAction("Pre&vious Tab",
                                          self,
                                          shortcut=prev_key,
                                          statusTip="Select previous tab",
                                          triggered=self.prev_tab)
        self.add_menu_action(self.window_menu, self.prev_tab_act)

        next_key = "Ctrl+Shift+Right" if sys.platform == 'darwin' else "Ctrl+PgDown"
        self.next_tab_act = QtGui.QAction("Ne&xt Tab",
                                          self,
                                          shortcut=next_key,
                                          statusTip="Select next tab",
                                          triggered=self.next_tab)
        self.add_menu_action(self.window_menu, self.next_tab_act)
Ejemplo n.º 21
0
    def init_kernel_menu(self):
        self.kernel_menu = self.menuBar().addMenu("&Kernel")
        # Qt on OSX maps Ctrl to Cmd, and Meta to Ctrl
        # keep the signal shortcuts to ctrl, rather than
        # platform-default like we do elsewhere.

        ctrl = "Meta" if sys.platform == 'darwin' else "Ctrl"

        self.interrupt_kernel_action = QtGui.QAction(
            "&Interrupt current Kernel",
            self,
            triggered=self.interrupt_kernel_active_frontend,
            shortcut=ctrl + "+C",
        )
        self.add_menu_action(self.kernel_menu, self.interrupt_kernel_action)

        self.restart_kernel_action = QtGui.QAction(
            "&Restart current Kernel",
            self,
            triggered=self.restart_kernel_active_frontend,
            shortcut=ctrl + "+.",
        )
        self.add_menu_action(self.kernel_menu, self.restart_kernel_action)

        self.kernel_menu.addSeparator()

        self.confirm_restart_kernel_action = QtGui.QAction(
            "&Confirm kernel restart",
            self,
            checkable=True,
            checked=self.active_frontend.confirm_restart,
            triggered=self.toggle_confirm_restart_active_frontend)

        self.add_menu_action(self.kernel_menu,
                             self.confirm_restart_kernel_action)
        self.tab_widget.currentChanged.connect(self.update_restart_checkbox)
Ejemplo n.º 22
0
    def init_magic_menu(self):
        self.magic_menu = self.menuBar().addMenu("&Magic")

        self.add_menu_action(self.magic_menu,
                             self.magic_helper.toggleViewAction())

        self.magic_menu_separator = self.magic_menu.addSeparator()

        self.reset_action = QtGui.QAction(
            "&Reset",
            self,
            statusTip="Clear all variables from workspace",
            triggered=self.reset_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.reset_action)

        self.history_action = QtGui.QAction(
            "&History",
            self,
            statusTip="show command history",
            triggered=self.history_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.history_action)

        self.save_action = QtGui.QAction(
            "E&xport History ",
            self,
            statusTip="Export History as Python File",
            triggered=self.save_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.save_action)

        self.who_action = QtGui.QAction(
            "&Who",
            self,
            statusTip="List interactive variables",
            triggered=self.who_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.who_action)

        self.who_ls_action = QtGui.QAction(
            "Wh&o ls",
            self,
            statusTip="Return a list of interactive variables",
            triggered=self.who_ls_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.who_ls_action)

        self.whos_action = QtGui.QAction(
            "Who&s",
            self,
            statusTip="List interactive variables with details",
            triggered=self.whos_magic_active_frontend)
        self.add_menu_action(self.magic_menu, self.whos_action)
Ejemplo n.º 23
0
    def test_qt_basic(self):
        """ Does the Qt kill ring work?
        """
        text_edit = QtGui.QPlainTextEdit()
        ring = QtKillRing(text_edit)

        ring.kill('foo')
        ring.kill('bar')
        ring.yank()
        ring.rotate()
        ring.yank()
        self.assertEqual(text_edit.toPlainText(), 'foobar')

        text_edit.clear()
        ring.kill('baz')
        ring.yank()
        ring.rotate()
        ring.rotate()
        ring.rotate()
        self.assertEqual(text_edit.toPlainText(), 'foo')
Ejemplo n.º 24
0
    def _context_menu_make(self, pos):
        """ Reimplemented to return a custom context menu for images.
        """
        format = self._control.cursorForPosition(pos).charFormat()
        name = format.stringProperty(QtGui.QTextFormat.ImageName)
        if name:
            menu = QtGui.QMenu()

            menu.addAction('Copy Image', lambda: self._copy_image(name))
            menu.addAction('Save Image As...', lambda: self._save_image(name))
            menu.addSeparator()

            svg = self._name_to_svg_map.get(name, None)
            if svg is not None:
                menu.addSeparator()
                menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg))
                menu.addAction('Save SVG As...',
                               lambda: save_svg(svg, self._control))
        else:
            menu = super(RichIPythonWidget, self)._context_menu_make(pos)
        return menu
Ejemplo n.º 25
0
    def __init__(
        self,
        app,
        confirm_exit=True,
        new_frontend_factory=None,
        slave_frontend_factory=None,
    ):
        """ Create a tabbed MainWindow for managing IPython FrontendWidgets
        
        Parameters
        ----------
        
        app : reference to QApplication parent
        confirm_exit : bool, optional
            Whether we should prompt on close of tabs
        new_frontend_factory : callable
            A callable that returns a new IPythonWidget instance, attached to
            its own running kernel.
        slave_frontend_factory : callable
            A callable that takes an existing IPythonWidget, and  returns a new 
            IPythonWidget instance, attached to the same kernel.
        """

        super(MainWindow, self).__init__()
        self._kernel_counter = 0
        self._app = app
        self.confirm_exit = confirm_exit
        self.new_frontend_factory = new_frontend_factory
        self.slave_frontend_factory = slave_frontend_factory

        self.tab_widget = QtGui.QTabWidget(self)
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested[int].connect(self.close_tab)

        self.setCentralWidget(self.tab_widget)
        # hide tab bar at first, since we have no tabs:
        self.tab_widget.tabBar().setVisible(False)
        # prevent focus in tab bar
        self.tab_widget.setFocusPolicy(QtCore.Qt.NoFocus)
Ejemplo n.º 26
0
    def _show_interpreter_prompt_for_reply(self, msg):
        """ Reimplemented for IPython-style prompts.
        """
        # Update the old prompt number if necessary.
        content = msg['content']
        # abort replies do not have any keys:
        if content['status'] == 'aborted':
            if self._previous_prompt_obj:
                previous_prompt_number = self._previous_prompt_obj.number
            else:
                previous_prompt_number = 0
        else:
            previous_prompt_number = content['execution_count']
        if self._previous_prompt_obj and \
                self._previous_prompt_obj.number != previous_prompt_number:
            block = self._previous_prompt_obj.block

            # Make sure the prompt block has not been erased.
            if block.isValid() and block.text():

                # Remove the old prompt and insert a new prompt.
                cursor = QtGui.QTextCursor(block)
                cursor.movePosition(QtGui.QTextCursor.Right,
                                    QtGui.QTextCursor.KeepAnchor,
                                    self._previous_prompt_obj.length)
                prompt = self._make_in_prompt(previous_prompt_number)
                self._prompt = self._insert_html_fetching_plain_text(
                    cursor, prompt)

                # When the HTML is inserted, Qt blows away the syntax
                # highlighting for the line, so we need to rehighlight it.
                self._highlighter.rehighlightBlock(cursor.block())

            self._previous_prompt_obj = None

        # Show a new prompt with the kernel's estimated prompt number.
        self._show_interpreter_prompt(previous_prompt_number + 1)
Ejemplo n.º 27
0
    def init_qt_elements(self):
        # Create the widget.

        base_path = os.path.abspath(os.path.dirname(__file__))
        icon_path = os.path.join(base_path, 'resources', 'icon',
                                 'IPythonConsole.svg')
        self.app.icon = QtGui.QIcon(icon_path)
        QtGui.QApplication.setWindowIcon(self.app.icon)

        ip = self.ip
        local_kernel = (not self.existing) or is_local_ip(ip)
        self.widget = self.widget_factory(config=self.config,
                                          local_kernel=local_kernel)
        self.init_colors(self.widget)
        self.widget._existing = self.existing
        self.widget._may_close = not self.existing
        self.widget._confirm_exit = self.confirm_exit
        self.widget._display_banner = self.display_banner

        self.widget.kernel_manager = self.kernel_manager
        self.widget.kernel_client = self.kernel_client
        self.window = MainWindow(
            self.app,
            confirm_exit=self.confirm_exit,
            new_frontend_factory=self.new_frontend_master,
            slave_frontend_factory=self.new_frontend_slave,
        )
        self.window.log = self.log
        self.window.add_tab_with_frontend(self.widget)
        self.window.init_magic_helper()
        self.window.init_menu_bar()

        # Ignore on OSX, where there is always a menu bar
        if sys.platform != 'darwin' and self.hide_menubar:
            self.window.menuBar().setVisible(False)

        self.window.setWindowTitle('IPython')
Ejemplo n.º 28
0
 def _get_format_from_style(self, token, style):
     """ Returns a QTextCharFormat for token by reading a Pygments style.
     """
     result = QtGui.QTextCharFormat()
     for key, value in style.style_for_token(token).items():
         if value:
             if key == 'color':
                 result.setForeground(self._get_brush(value))
             elif key == 'bgcolor':
                 result.setBackground(self._get_brush(value))
             elif key == 'bold':
                 result.setFontWeight(QtGui.QFont.Bold)
             elif key == 'italic':
                 result.setFontItalic(True)
             elif key == 'underline':
                 result.setUnderlineStyle(
                     QtGui.QTextCharFormat.SingleUnderline)
             elif key == 'sans':
                 result.setFontStyleHint(QtGui.QFont.SansSerif)
             elif key == 'roman':
                 result.setFontStyleHint(QtGui.QFont.Times)
             elif key == 'mono':
                 result.setFontStyleHint(QtGui.QFont.TypeWriter)
     return result
Ejemplo n.º 29
0
    def get_format(self):
        """ Returns a QTextCharFormat that encodes the current style attributes.
        """
        format = QtGui.QTextCharFormat()

        # Set foreground color
        qcolor = self.get_color(self.foreground_color, self.intensity)
        if qcolor is not None:
            format.setForeground(qcolor)

        # Set background color
        qcolor = self.get_color(self.background_color, self.intensity)
        if qcolor is not None:
            format.setBackground(qcolor)

        # Set font weight/style options
        if self.bold:
            format.setFontWeight(QtGui.QFont.Bold)
        else:
            format.setFontWeight(QtGui.QFont.Normal)
        format.setFontItalic(self.italic)
        format.setFontUnderline(self.underline)

        return format
Ejemplo n.º 30
0
    def init_view_menu(self):
        self.view_menu = self.menuBar().addMenu("&View")

        if sys.platform != 'darwin':
            # disable on OSX, where there is always a menu bar
            self.toggle_menu_bar_act = QtGui.QAction(
                "Toggle &Menu Bar",
                self,
                shortcut="Ctrl+Shift+M",
                statusTip="Toggle visibility of menubar",
                triggered=self.toggle_menu_bar)
            self.add_menu_action(self.view_menu, self.toggle_menu_bar_act)

        fs_key = "Ctrl+Meta+F" if sys.platform == 'darwin' else "F11"
        self.full_screen_act = QtGui.QAction(
            "&Full Screen",
            self,
            shortcut=fs_key,
            statusTip="Toggle between Fullscreen and Normal Size",
            triggered=self.toggleFullScreen)
        self.add_menu_action(self.view_menu, self.full_screen_act)

        self.view_menu.addSeparator()

        self.increase_font_size = QtGui.QAction(
            "Zoom &In",
            self,
            shortcut=QtGui.QKeySequence.ZoomIn,
            triggered=self.increase_font_size_active_frontend)
        self.add_menu_action(self.view_menu, self.increase_font_size, True)

        self.decrease_font_size = QtGui.QAction(
            "Zoom &Out",
            self,
            shortcut=QtGui.QKeySequence.ZoomOut,
            triggered=self.decrease_font_size_active_frontend)
        self.add_menu_action(self.view_menu, self.decrease_font_size, True)

        self.reset_font_size = QtGui.QAction(
            "Zoom &Reset",
            self,
            shortcut="Ctrl+0",
            triggered=self.reset_font_size_active_frontend)
        self.add_menu_action(self.view_menu, self.reset_font_size, True)

        self.view_menu.addSeparator()

        self.clear_action = QtGui.QAction(
            "&Clear Screen",
            self,
            shortcut='Ctrl+L',
            statusTip="Clear the console",
            triggered=self.clear_magic_active_frontend)
        self.add_menu_action(self.view_menu, self.clear_action)

        self.pager_menu = self.view_menu.addMenu("&Pager")

        hsplit_action = QtGui.QAction(
            ".. &Horizontal Split",
            self,
            triggered=lambda: self.set_paging_active_frontend('hsplit'))

        vsplit_action = QtGui.QAction(
            " : &Vertical Split",
            self,
            triggered=lambda: self.set_paging_active_frontend('vsplit'))

        inside_action = QtGui.QAction(
            "   &Inside Pager",
            self,
            triggered=lambda: self.set_paging_active_frontend('inside'))

        self.pager_menu.addAction(hsplit_action)
        self.pager_menu.addAction(vsplit_action)
        self.pager_menu.addAction(inside_action)