Beispiel #1
0
def tryOpen():
    view = kate.activeView()
    assert('View expected to be valid' and view is not None)
    assert('This action supposed to select some text before' and view.selection())

    doc = view.document()
    doc_url = doc.url()
    new_url = KUrl(_try_make_url_from_text(view.selectionText()))

    kate.kDebug('Current document URI: {}'.format(repr(doc_url)))

    # 0) Make sure it is valid
    if not new_url.isValid():
        kate.ui.popup(
            i18nc('@title:window', 'Error')
          , i18nc('@info:tooltip', "Selected text doesn't looks like a valid URI")
          , 'dialog-error'
          )
        return

    # 1) Is it have some schema? and current document is not 'Untitled'...
    if new_url.isRelative() and not doc_url.isEmpty():
        # Replace filename from the doc_url w/ the current selection
        new_url = doc_url.upUrl()
        new_url.addPath(view.selectionText())

    kate.kDebug('Trying URI: {}'.format(repr(new_url)))
    # Ok, try to open it finally
    _try_open_show_error(new_url)
Beispiel #2
0
def _lint(document, move_cursor, linter_name, linter):
    """extracted part of lint_js that has to be called after the linter is ready"""
    ok = linter(document.text(), {})
    if ok:
        showOk(i18nc('@info:status', '<application>%1</application> OK', linter_name))
        return

    errors = [error for error in linter['errors'] if error]  # sometimes None

    # Prepare errors found for painting
    for error in errors:
        error['message'] = error.pop('reason')  # rename since showErrors has 'message' hardcoded
        error.pop('raw', None)  # Only reason, line, and character are always there
        error.pop('a', None)
        error.pop('b', None)
        error.pop('c', None)
        error.pop('d', None)

    mark_key = '{}-{}'.format(document.url().path(), linter_name)

    showErrors(i18nc('@info:status', '<application>%1</application> Errors:', linter_name),
               errors,
               mark_key, document,
               key_column='character',
               move_cursor=move_cursor)
Beispiel #3
0
    def _updateCacheView(self, build_dir):
        # Do nothing if build dir is not configured
        if not build_dir:
            return

        self.cacheViewPage.cacheItems.clear()               # Remove previously collected cache
        is_advanced = self.cfgPage.mode.isChecked()

        try:
            items = cmake_help_parser.get_cache_content(build_dir, is_advanced)
        except ValueError as error:
            kate.ui.popup(
                i18nc('@title:window', 'Error')
              , i18nc(
                    '@info:tooltip'
                  , 'Unable to get CMake cache content:<nl/><message>%1</message>'
                  , str(error)
                  )
              , 'dialog-error'
              )
            return

        # Add items to a list
        for key, value in items.items():
            item = QTreeWidgetItem(self.cacheViewPage.cacheItems, [key, value[1], value[0]])
            item.setToolTip(0, value[2])

        self.cacheViewPage.cacheItems.resizeColumnToContents(0)
        self.cacheViewPage.cacheItems.resizeColumnToContents(1)
        self.cacheViewPage.cacheItems.resizeColumnToContents(2)
Beispiel #4
0
def _spawn_cmake_grab_stdout(args, cmake_executable = None):
    if cmake_executable is None:
        cmake_utils_conf = kate.configuration.root.get('cmake_utils', {})

        if settings.CMAKE_BINARY in cmake_utils_conf:
            # TODO Set locale "C" before run cmake
            cmake_bin = cmake_utils_conf[settings.CMAKE_BINARY]
        else:
            raise ValueError(
                i18nc(
                    '@item:intext'
                  , 'CMake executable is not configured'
                  )
              )
    else:
        cmake_bin = cmake_executable

    #print('CMakeCC: going to spawn `{} {}`'.format(cmake_bin, ' '.join(args)))
    p = subprocess.Popen([cmake_bin] + args, stdout=subprocess.PIPE)
    out, err = p.communicate()
    if err:
        print('CMake helper: running `{} {}` finished with errors:\n{}'.format(cmake_bin, ' '.join(args), err))
        raise ValueError(
            i18nc(
                '@item:intext'
                , 'Running <command>%1</command> finished with errors:<nl/><message>%2</message>'
                , cmake_bin, err
                )
            )
    return out
Beispiel #5
0
def _ask_for_CMakeLists_location_and_try_open(start_dir_to_show, cur_doc_dir):
    selected_dir = KUrlRequesterDialog.getUrl(
        start_dir_to_show
      , kate.mainInterfaceWindow().window()
      , i18nc('@title:window', '<filename>CMakeLists.txt</filename> location')
      )
    kate.kDebug('CMakeHelper: selected_dir={}'.format(selected_dir))

    if selected_dir.isEmpty():
        return                                              # User pressed 'Cancel'

    selected_dir = selected_dir.toLocalFile()               # Get selected path
    # Is it relative?
    if not os.path.isabs(selected_dir):
        # Yep, join w/ a path of the current doc
        selected_dir = os.path.abspath(os.path.join(cur_doc_dir, selected_dir))

    # Check if there CMakeLists.txt present
    cmakelists = os.path.join(selected_dir, _CMAKE_LISTS)
    if _is_there_CMakeLists(selected_dir):
        # Open it!
        _openDocumentNoCheck(QUrl.fromLocalFile(cmakelists))
    else:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
          , i18nc('@info:tooltip', 'No such file <filename>%1</filename>', cmakelists)
          , 'dialog-error'
          )
Beispiel #6
0
def license_accepted(license):
    """asks to accept a license"""
    return KMessageBox.Yes == KMessageBox.warningYesNo(kate.mainWindow(),
        i18nc('@info:status', '''<p>
            Additionally to free software licenses like GPL and MIT,
            this functionality requires you to accept the following conditions:
            </p><p>%1</p><p>
            Do you want to accept and download the functionality?
            </p>''', license),
        i18nc('@title:window', 'Accept license?'))
Beispiel #7
0
 def __init__(self, parent=None):
     KComboBox.__init__(self, parent)
     self.addItems(
         [
             i18nc("@item:inlistbox mouse button triggered by tapping", "Disabled"),
             i18nc("@item:inlistbox mouse button triggered by tapping", "Left mouse button"),
             i18nc("@item:inlistbox mouse button triggered by tapping", "Middle mouse button"),
             i18nc("@item:inlistbox mouse button triggered by tapping", "Right mouse button"),
         ]
     )
Beispiel #8
0
 def has_selection_checker(selectionState, document):
     view = document.activeView()
     result = selectionState == view.selection()
     if not result:
         if not selectionState:
             should = i18nc('@info:tooltip', "This operation cannot be performed while text is selected")
         else:
             should = i18nc('@info:tooltip', "Text must be selected to perform this operation")
         kate.ui.popup(i18nc('@title:window', 'Alert'), should, 'dialog-information')
     return result
Beispiel #9
0
def openDocument(url):
    local_file = url.toLocalFile()
    kate.kDebug('CMakeCC: going to open the document: {}'.format(local_file))
    if os.access(local_file, os.R_OK):
        _openDocumentNoCheck(url)
    else:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
          , i18nc('@info:tooltip', 'Unable to open the document: <filename>%1</filename>', local_file)
          , 'dialog-error'
          )
Beispiel #10
0
 def __init__(self, parent=None):
     KComboBox.__init__(self, parent)
     self.addItems([
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Disabled'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Left mouse button'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Middle mouse button'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Right mouse button')
     ])
Beispiel #11
0
 def __init__(self, parent=None):
     KComboBox.__init__(self, parent)
     self.addItems([
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Disabled'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Left mouse button'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
               'Middle mouse button'),
         i18nc('@item:inlistbox mouse button triggered by tapping',
                'Right mouse button')
         ])
Beispiel #12
0
 def comment_char_checker(dummy, document):
     doc_type = document.highlightingMode()
     result = common.isKnownCommentStyle(doc_type)
     if not result:
         kate.ui.popup(
             i18nc('@title:window', 'Sorry...')
           , i18nc(
                 '@info:tooltip placeholder is a mime-type'
               , '<command>%1</command> is unsupported document type.', doc_type
               )
           , 'dialog-information'
           )
     return result
Beispiel #13
0
 def doc_type_checker(doc_types, document):
     doc_type = document.highlightingMode()
     if doc_type not in doc_types:
         kate.ui.popup(
             i18nc('@title:window', 'Alert')
           , i18nc(
                 '@info:tooltip placeholder is a mime-type'
               , 'This action has no sense for <command>%1</command> documents', doc_type
               )
           , 'dialog-information'
           )
         return False
     return True
Beispiel #14
0
def _try_open_show_error(uri):
    assert('Sanity check' and uri is not None)
    view = kate.mainInterfaceWindow().openUrl(uri)
    if view is None:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
          , i18nc(
                '@info:tooltip'
              , 'Unable to open the selected document: <filename>%1</filename>'
              , str(uri)
              )
          , 'dialog-error'
          )
Beispiel #15
0
def render_jinja_template(template, data):
    assert(isinstance(data, dict))
    assert(isinstance(template, str))

    # Add some predefined variables
    # - `nl` == new line character
    if 'nl' not in data:
        data['nl'] = '\n'
    # - `tab` == one TAB character
    if 'tab' not in data:
        data['tab'] = '\t'
    # - `space` == one space character
    if 'space' not in data:
        data['space'] = ' '

    result = None
    # Ok, going to render some jinja2 template...
    filename = kate.findApplicationResource('{}/{}'.format(_JINJA_TEMPLATES_BASE_DIR, template))
    if not filename:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
            , i18nc('@info:tooltip', 'Template file not found <filename>%1</filename>', template)
            , 'dialog-error'
            )
        return result

    kate.kDebug('found abs template: {}'.format(filename))

    # Get a corresponding environment for jinja!
    base_dir_pos = filename.find(_JINJA_TEMPLATES_BASE_DIR)
    assert(base_dir_pos != -1)
    basedir = filename[:base_dir_pos + len(_JINJA_TEMPLATES_BASE_DIR)]
    filename = filename[base_dir_pos + len(_JINJA_TEMPLATES_BASE_DIR) + 1:]
    env = _getJinjaEnvironment(basedir)
    kate.kDebug('basedir={}, template_rel={}'.format(basedir, filename))
    try:
        tpl = env.get_template(filename)
        kate.kDebug('data dict={}'.format(data))
        result = tpl.render(data)
    except jinja2.TemplateError as e:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
            , i18nc(
                '@info:tooltip'
                , 'Template file error [<filename>%1</filename>]: <status>%2</status>'
                , template
                , e.message
                )
            , 'dialog-error'
            )
    return result
Beispiel #16
0
 def notify_touchpad_state(self, is_off=None):
     if is_off is None:
         is_off = self.touchpad.off
     # show a notification
     if is_off:
         event_id = 'touchpadOff'
         text = i18nc('touchpad switched notification',
                      'Touchpad switched off')
     else:
         event_id = 'touchpadOn'
         text = i18nc('touchpad switched notification',
                      'Touchpad switched on')
     icon = KIconLoader.global_().loadIcon('synaptiks', KIconLoader.Panel)
     KNotification.event(event_id, text, icon)
Beispiel #17
0
 def treatmentException(self, e):
     if self.invocationType == KTextEditor.CodeCompletionModel.AutomaticInvocation:
         return
     f = e.filename or ""
     text = e.text
     line = e.lineno
     message = i18n("There was a syntax error in this file:")
     if f:
         message = i18nc("%1 is error message", "%1\n  * file: %2", message, f)
     if text:
         message = i18nc("%1 is error message", "%1\n  * text: %2", message, text)
     if line:
         message = i18nc("%1 is error message", "%1\n  * line: %2", message, line)
     showError(message)
Beispiel #18
0
def remove_block():
    ''' Remove a block of code commented with #if0 or #if1-#else'''
    document = kate.activeDocument()
    view = kate.activeView()

    # Make list of ranges of #if*/#endif blocks
    blocksList = buildIfEndifMap(document)

    # Locate a block where cursor currently positioned
    idx = locateBlock(view.cursorPosition().line(), blocksList, False)

    if idx != -1:
        # Get current value
        v = BLOCK_START_SEARCH_RE.search(str(document.line(blocksList[idx][0]))).group(1)
        # Do nothing if it's not a #if0/#if1
        if v not in ('0', 'false', '1', 'true'):
            return

        document.startEditing()                             # Start edit transaction
        # What to remove?
        if v in ('0', 'false'):                             # Remove `then` part
            if blocksList[idx][2] != -1:                    # Is there `#else` part?
                # Yeah! Remove `#endif` line and then from `#if` to `#else` (including)
                document.removeLine(blocksList[idx][1])
                r = KTextEditor.Range(blocksList[idx][0], 0, blocksList[idx][2] + 1, 0)
            else:
                # No! So just remove whole block
                r = KTextEditor.Range(blocksList[idx][0], 0, blocksList[idx][1] + 1, 0)
            document.removeText(r)
        else:
            if blocksList[idx][2] != -1:                    # Is there `#else` part?
                # Yeah! Remove from `#else` to `#endif` block and then `#if` line
                r = KTextEditor.Range(blocksList[idx][2], 0, blocksList[idx][1] + 1, 0)
                document.removeText(r)
                document.removeLine(blocksList[idx][0])
            else:
                # No! Ok just remove `#endif` line and then `#if`
                document.removeLine(blocksList[idx][1])
                document.removeLine(blocksList[idx][0])
        document.endEditing()                                   # End transaction
    else:
        kate.ui.popup(
            i18nc('@title:window', 'Alert')
          , i18nc(
                '@info:tooltip'
              , 'The cursor is not positioned in any <icode>#if0</icode>/<icode>#if1</icode> block'
              )
          , 'dialog-information'
          )
Beispiel #19
0
    def __init__(self, parent):
        super(ConsoleToolView, self).__init__(parent)
        self.toolView = kate.mainInterfaceWindow().createToolView(
            'ipython_console',
            kate.Kate.MainWindow.Bottom,
            KIcon('text-x-python').pixmap(32,32),
            i18nc('@title:tab', 'IPython Console')
        )
        self.toolView.installEventFilter(self)
        self.console = make_terminal_widget(parent=self.toolView, kate=kate)

        # Load CSS from file '${appdir}/ipython_console.css'
        css_string = None
        search_dirs = kate.applicationDirectories() + [os.path.dirname(__file__)]
        for appdir in search_dirs:
            # TODO Make a CSS file configurable?
            css_file = os.path.join(appdir, _CONSOLE_CSS)
            try:
                with open(css_file, 'r') as f:
                    css_string = f.read()
                    break
            except IOError:
                pass

        if css_string:
            self.console.style_sheet = css_string
            if ipython_1:                                   # For seamless borders
                self.console.setStyleSheet(css_string)

        if _SCROLLBACK_LINES_COUNT_CFG in kate.configuration:
            self.console.buffer_size = kate.configuration[_SCROLLBACK_LINES_COUNT_CFG]
    def setup_tooltip(self):
        print "setup_tooltip: Last updated:", self._widget.lastUpdated()
        # Tool tip for panel
        if self.has_tooltip:
            Plasma.ToolTipManager.self().clearContent(self.applet)
        self.metadata = self.package().metadata()
        self.tooltipdata = Plasma.ToolTipContent()
        self.tooltipdata.setAutohide(False)
        self.tooltipdata.setMainText(self.metadata.name())
        #self.tooltipdata.setSubText(self.metadata.description())
        tooltip_txt = str(i18nc("From code From Amount = To code To Amount - Last updated", "%s %s = %s %s<br /><br />Last updated:<br />%s"))
        tooltip_txt= tooltip_txt % (self._widget.fromCurrency(), self._widget.fromAmount(),
                                    self._widget.toCurrency(), self._widget.toAmount(),
                                    self._widget.lastUpdated())
        #print tooltip_txt
        self.tooltipdata.setSubText(tooltip_txt)
        self.tooltipdata.setImage(KIcon(self.metadata.pluginName()))
        Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata)

        # Only register the tooltip in panels
        #if (self.formFactor() != Plasma.Planar):
        if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)):
            #print("CurrencyConverterApplet: In Panel")
            Plasma.ToolTipManager.self().registerWidget(self.applet)
            self.has_tooltip = True
        else:
            Plasma.ToolTipManager.self().clearContent(self.applet)
            Plasma.ToolTipManager.self().unregisterWidget(self.applet)
            #print("CurrencyConverterApplet: Not in Panel")
            self.has_tooltip = False
Beispiel #21
0
    def __init__(self):
        super(ColorChooser, self).__init__(None)
        self.colors = KColorCells(self, 1, 1)
        self.colors.setAcceptDrags(False)
        self.colors.setEditTriggers(self.colors.NoEditTriggers)
        self.otherBtn = KPushButton(self)
        self.otherBtn.setText(i18nc('@action:button', '&Other...'))
        layout = QVBoxLayout(self)
        layout.addWidget(self.colors)
        layout.addWidget(self.otherBtn)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setFrameShape(QFrame.Panel)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        # Set default value for last used #color if not configured yet
        if ColorChooser._INSERT_COLOR_LCC not in kate.sessionConfiguration:
            kate.sessionConfiguration[ColorChooser._INSERT_COLOR_LCC] = '#ffffff'

        # Subscribe to observe widget events
        # - open KColorDialog on 'Other...' button click
        self.otherBtn.clicked.connect(self._show_color_dialog)
        # - select color by RMB click or ENTER on keyboard
        self.colors.cellActivated.connect(self._color_selected)
        # -
        self.colorSelected.connect(self._insert_color_into_active_document)

        self.installEventFilter(self)
Beispiel #22
0
    def show_touchpad(self, touchpad):
        """
        Show information about the given ``touchpad`` in this widget.

        ``touchpad`` is a :class:`~synaptiks.touchpad.Touchpad` object.
        """
        self.nameLabel.setText(i18nc(
            '@info touchpad name', '<title><resources>%1</resource></title>',
            touchpad.name))

        pixmaps = {True: 'dialog-ok', False: 'dialog-cancel'}
        for key in pixmaps:
            pixmaps[key] = KIconLoader.global_().loadIcon(
                pixmaps[key], KIconLoader.Small)

        button_widgets = ('left', 'middle', 'right')
        for widget_name, is_supported in zip(button_widgets, touchpad.buttons):
            widget = getattr(self, '{0}Button'.format(widget_name))
            widget.setPixmap(pixmaps[is_supported])

        self.fingerDetection.setValue(touchpad.finger_detection)

        # disable the emulation box, if the touchpad natively supports two
        # fingers natively.
        if touchpad.finger_detection > 2:
            self.twoFingerEmulationBox.setEnabled(False)
        # nonetheless always assign proper pixmaps
        self.fingerWidthDetection.setPixmap(
            pixmaps[touchpad.has_finger_width_detection])
        self.pressureDetection.setPixmap(
            pixmaps[touchpad.has_pressure_detection])
        self.twoFingerEmulation.setPixmap(
            pixmaps[touchpad.has_two_finger_emulation])
Beispiel #23
0
def get_linter(linter_name, callback):
    """tries to retrieve a linter and calls `callback` on it on success"""
    if linter_name in LINTERS:
        callback(LINTERS[linter_name])
        return

    if linter_name not in NEEDS_LICENSE:
        showError(i18nc('@info:status', 'No acceptable linter named %1!', linter_name))
        return

    license, objname, url = NEEDS_LICENSE[linter_name]
    cache_path = p.join(CACHE_DIR, linter_name + '.js')

    def success():
        """store newly created linter and “return” it"""
        LINTERS[linter_name] = JSModule(JS_ENGINE, cache_path, objname)
        callback(LINTERS[linter_name])

    if p.exists(cache_path):
        success()
        return

    # the user doesn’t have the file. ask to accept its license
    if not license_accepted(license):
        return

    download = KIO.file_copy(KUrl(url), KUrl.fromPath(cache_path))
    @download.result.connect
    def _call(job):
        if job.error():
            showError(i18nc('@info:status', 'Download failed'))
        else:
            success()
    download.start()
Beispiel #24
0
 def addDir(self):
     path = KFileDialog.getExistingDirectory(
         KUrl('')
       , self
       , i18nc('@title:window', 'Select a Directory with CMake Modules')
       )
     kate.kDebug('CMakeCC: got path={}'.format(path))
     self.moduleDirs.addItem(str(path))
Beispiel #25
0
 def selection_mode_checker(selectionMode, document):
     view = document.activeView()
     result = selectionMode == view.blockSelection()
     if not result:
         kate.ui.popup(
             i18nc('@title:window', 'Alert')
           , i18nc(
                 '@info:tooltip'
               , 'This operation is for block selection mode'
               )
             if selectionMode else
             i18nc(
                 '@info:tooltip'
               , 'This operation is for normal selection mode'
               )
           , 'dialog-information'
           )
     return result
Beispiel #26
0
    def try_complete_command(self, command, document, cursor, word, comp_list, invocationType):
        '''Try to complete a command'''
        if self.has_completion_for_command(command):
            if isinstance(self.__command_completers[command], types.FunctionType):
                # If a function registered as a completer, just call it...
                completions = self.__command_completers[command](document, cursor, word, comp_list)
            else:
                # Everything else, that is not a function, just pass to the generic completer
                completions = self._try_syntactic_completer(
                    self.__command_completers[command]
                  , document
                  , cursor
                  , word
                  , comp_list
                  )
        else:
            if invocationType != KTextEditor.CodeCompletionModel.AutomaticInvocation:
                # Show popup only if user explictly requested code completion
                kate.ui.popup(
                    i18nc('@title:window', 'Attention')
                  , i18nc('@info:tooltip', 'Sorry, no completion for <command>%1()</command>', command)
                  , 'dialog-information'
                  )

            completions = []

        # Result of a completion function must be a list type
        if completions and isinstance(completions, list):
            self.TITLE_AUTOCOMPLETION = i18nc(
                '@label:listbox'
              , 'CMake <command>%1()</command> Completion', command
              )
            for c in completions:
                # If completion item is a tuple, we expect to have 2 items in it:
                # 0 is a 'text' and 1 is a 'description'
                if isinstance(c, tuple) and len(c) == 2:
                    self.resultList.append(
                        self.createItemAutoComplete(
                            text=c[0]
                          , description=c[1]
                          )
                      )
                else:
                    self.resultList.append(self.createItemAutoComplete(text=c))
Beispiel #27
0
def _matchingParenthesisPosition(document, position, opening='('):
    closing = ')' if opening == '(' else '('
    delta = 1 if opening == '(' else -1
    # take a copy, Cursors are mutable
    position = position.__class__(position)

    level = 0
    state = None
    while 1:
        character = document.character(position)
        if state in ('"', "'"):
            if character == state:
                state = None
        else:
            if character == opening:
                level += 1
            elif character == closing:
                level -= 1
                if level == 0:
                    if closing == ')':
                        position.setColumn(position.column() + delta)
                    break
            elif character in ('"', "'"):
                state = character

        position.setColumn(position.column() + delta)
        # must we move down a line?
        if document.character(position) == None:
            position.setPosition(position.line() + delta, 0)
            if delta == -1:
                # move to the far right
                position.setColumn(document.lineLength(position.line()) - 1)
            # failure again => EOF
            if document.character(position) == None:
                raise ParseError(i18nc('@info', 'end of file reached'))
            else:
                if state in ('"', "'"):
                    raise ParseError(
                        i18nc(
                            '@info'
                          , 'end of line reached while searching for <icode>%1</icode>', state
                          )
                      )
    return position
Beispiel #28
0
def validate_cmake_executable(cmake_executable):
    # Make sure specified binary exists
    if os.path.isabs(cmake_executable) and os.path.exists(cmake_executable):
        out = _spawn_cmake_grab_stdout(['--version'], cmake_executable)
        lines = out.decode('utf-8').splitlines()
        # We expect a word 'cmake' in a very first line
        if not lines or lines[0].count('cmake') == 0:
            raise ValueError(
                i18nc(
                    '@item:intext'
                  , 'Specified CMake executable <command>%1</command> looks invalid', cmake_executable
                  )
              )
    else:
        raise ValueError(
            i18nc(
                '@item:intext'
              , 'Specified CMake executable <command>%1</command> not found', cmake_executable
              )
          )
Beispiel #29
0
def toggleSelectionSensitiveActions(view):
    clnt = kate.getXmlGuiClient()
    filename = _try_make_url_from_text(view.selectionText())
    kate.kDebug('Original new filename: {}'.format(repr(filename)))

    if view.selection() and len(filename) < _SANE_URI_LENGTH:
        clnt.stateChanged('has_selection')
        # Change action text...
        if _URI_LENGTH_SHOW_THRESHOLD < len(filename):
            lead_pos = int(2 * _URI_LENGTH_SHOW_THRESHOLD / 3)
            tail_pos = -int(_URI_LENGTH_SHOW_THRESHOLD / 3)
            filename = filename[:lead_pos] + '...' + filename[tail_pos:]
        assert('Sanity check' and hasattr(tryOpen, 'action'))
        kate.kDebug('New filename: {}'.format(filename))
        tryOpen.action.setText(
            i18nc('@ation:inmenu', 'Open <filename>%1</filename>', filename)
          )
    else:
        clnt.stateChanged('has_selection', KXMLGUIClient.StateReverse)
        tryOpen.action.setText(i18nc('@ation:inmenu', 'Open selected document'))
Beispiel #30
0
def boostFormat():
    '''Format function's/template's parameters list (or `for`'s) in a boost-like style
       I.e. when 2nd and the rest parameters has leading comma/semicolon
       and closing ')' or '>' on a separate line.
       THIS IS REALLY BETTER TO HAVE SUCH STYLE WHEN U HAVE A LONG PARAMETERS LIST!
    '''
    document = kate.activeDocument()
    view = kate.activeView()

    try:
        r, nestedRanges, breakPositions = getRangeTopology(',')
    except LookupError as error:
        kate.ui.popup(
            i18nc('@title:window', 'Alert')
          , i18nc(
                '@info:tooltip'
              , 'Failed to parse C++ expression:<nl/><message>%1</message>', error
              )
          , 'dialog-information'
          )
        return

    if r.isEmpty():                                         # Is range empty?
        kate.ui.popup(
            i18nc('@title:window', 'Alert')
          , i18nc(
                '@info:tooltip'
              , 'Failed to parse C++ expression:<nl/><message>%1</message>'
              , i18nc('@info:tooltip', "Did not find anything to format")
              )
          , 'dialog-information'
          )
        return                                              # Nothing interesting wasn't found...

    # Rescan the range w/ ';' as breaker added if current range is a `for` statement
    if document.line(r.start().line())[0:r.start().column() - 1].rstrip().endswith('for'):
        try:
            r, nestedRanges, breakPositions = getRangeTopology(',;')
        except LookupError as error:
            kate.ui.popup(
                i18nc('@title:window', 'Alert')
              , i18nc(
                    '@info:tooltip'
                  , 'Failed to parse C++ expression:<nl/><message>%1</message>', error
                  )
              , 'dialog-information'
              )
            return

    # Going to format a text whithin a selected range
    lineStr = document.line(r.start().line())
    lineStrStripped = lineStr.lstrip()
    indent = len(lineStr) - len(lineStrStripped)
    if lineStrStripped.startswith(', '):
        indent += 2
    text = boostFormatText(r, indent, breakPositions)
Beispiel #31
0
 def __init__(self, component_data, parent=None):
     KCModule.__init__(self, component_data, parent)
     KGlobal.locale().insertCatalog('synaptiks')
     # keep a reference to the generated about data to prevent it from being
     # deleted by the GC
     self._about = make_about_data(
         ki18nc('kcmodule description', 'Touchpad configuration'))
     self.setAboutData(self._about)
     self.setQuickHelp(i18nc(
         '@info:tooltip synaptiks kcmodule',
         '<title>Touchpad configuration</title>'
         '<para>This module lets you configure your touchpad.</para>'))
Beispiel #32
0
    def setup_actions(self):
        self.touchpad_on_action = KToggleAction(
            i18nc('@action:inmenu', 'Touchpad on'), self.actionCollection())
        self.actionCollection().addAction(
            'touchpadOn', self.touchpad_on_action)
        self.touchpad_on_action.setGlobalShortcut(
            KShortcut(i18nc('Touchpad toggle shortcut', 'Ctrl+Alt+T')))
        self.contextMenu().addAction(self.touchpad_on_action)

        self.contextMenu().addSeparator()

        shortcuts = self.actionCollection().addAction(
            KStandardAction.KeyBindings, 'shortcuts')
        shortcuts.triggered.connect(self.show_shortcuts_dialog)
        self.contextMenu().addAction(shortcuts)

        self.preferences_action = self.actionCollection().addAction(
            KStandardAction.Preferences, 'preferences')
        self.preferences_action.triggered.connect(
            self.show_configuration_dialog)
        self.contextMenu().addAction(self.preferences_action)

        help_menu = KHelpMenu(self.contextMenu(), KCmdLineArgs.aboutData())
        self.contextMenu().addMenu(help_menu.menu())
Beispiel #33
0
 def __init__(self, touchpad, parent=None):
     QWidget.__init__(self, parent)
     self._load_userinterface()
     # HACK: the designer is seems unable to set this property, so we set it
     # in code.
     self.touchpad_coasting_speed.setSpecialValueText(
         i18nc('@item coasting speed special value', 'Disabled'))
     self.touchpad_coasting_speed.valueChanged.connect(
         self._coasting_speed_changed)
     self.coasting.toggled.connect(self._coasting_toggled)
     step = self.touchpad_coasting_speed.singleStep()
     value = self.touchpad_coasting_speed.value()
     self._saved_coasting_speed = value or step
     if touchpad.finger_detection >= 2 or touchpad.has_two_finger_emulation:
         two_finger_widgets = self.findChildren(
             QWidget, QRegExp('touchpad_(.*)_two_finger_scrolling'))
         for widget in two_finger_widgets:
             widget.setEnabled(True)
Beispiel #34
0
    def __init__(self, config, parent=None):
        """
        Create a new configuration widget for the given ``touchpad``.

        ``config`` is the :class:`~synaptiks.config.TouchpadConfiguration`
        object displayed by this widget.  ``parent`` is the parent
        :class:`~PyQt4.QtGui.QWidget` (can be ``None``).
        """
        KTabWidget.__init__(self, parent)
        self.touchpad_config = config
        pages = [HardwarePage(self.touchpad, self), MotionPage(self),
                 ScrollingPage(self.touchpad, self),
                 TappingPage(self.touchpad, self)]
        for page in pages:
            self.addTab(page, page.windowTitle())
        self.setWindowTitle(
            i18nc('@title:window', 'Touchpad configuration'))
        self._setup(self.touchpad_config)
Beispiel #35
0
    def populateOutputsMenu(self):
        menu = QtGui.QMenu(self)

        for output in self._outputs:
            if output.outputType == Output.UnknownOutput:
                text = output.name
            else:
                text = kdecore.i18nc(
                        "Shown in menus, lists, etc. "
                        "%1 = localized output type, "
                        "%2 = output name (LVDS, VGA, etc.)",
                        "%1 (%2)", output.getTypeString(), output.name)
            action = QtGui.QAction(text, self)
            action.setData(QtCore.QVariant(output.name))
            action.setCheckable(True)
            if output in (self._left, self._right):
                action.setChecked(True)
            menu.addAction(action)

        menu.triggered.connect(self.slotOutputToggled)
        self.outputsButton.setMenu(menu)
#   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

from functools import partial
import sys

import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui

import PyKDE4.kdecore as kdecore
import PyKDE4.kdeui as kdeui
import PyKDE4.kio as kio

# import danbooru2nepomuk

_TRANSLATED_RATINGS = dict(
    Safe=kdecore.i18nc("Image for all audiences", "Safe"),
    Questionable=kdecore.i18nc("Image with suggestive themes", "Questionable"),
                          Explicit=kdecore.i18nc("Image with explicit content",
                              "Explicit")
    )

if sys.version_info.major > 2:
    unicode = str

class DanbooruPostWidget(QtGui.QWidget):

    """Widget that displays a DanbooruPost."""

    def __init__(self, danbooru_post, parent=None):

        super(DanbooruPostWidget, self).__init__(parent)