Esempio n. 1
0
    def on_popup_navigate(self, href):
        for url_prefix in ('https://', 'http://'):
            if href.startswith(url_prefix):
                webbrowser.open_new_tab(href)
                break

        mdpopups.hide_popup(self.view)
Esempio n. 2
0
    def run(self, edit):
        """Enable or disable instant scoper."""

        close_display = False

        sh_thread.instant_scoper = False
        if not self.view.settings().get('scope_hunter.view_enable', False):
            self.view.settings().set('scope_hunter.view_enable', True)
            sh_thread.modified = True
            sh_thread.time = time()
        else:
            self.view.settings().set('scope_hunter.view_enable', False)
            close_display = True

        if close_display:
            win = self.view.window()
            if win is not None:
                view = win.get_output_panel('scopehunter.results')
                parent_win = view.window()
                if parent_win:
                    parent_win.run_command('hide_panel', {'cancel': True})
                if TOOLTIP_SUPPORT:
                    mdpopups.hide_popup(self.view)
                if (
                    self.view is not None and
                    sh_thread.is_enabled(view) and
                    bool(sh_settings.get("highlight_extent", False)) and
                    len(view.get_regions("scope_hunter"))
                ):
                    view.erase_regions("scope_hunter")
    def run(self, edit):
        """Enable or disable instant scoper."""

        close_display = False

        sh_thread.instant_scoper = False
        if not self.view.settings().get('scope_hunter.view_enable', False):
            self.view.settings().set('scope_hunter.view_enable', True)
            sh_thread.modified = True
            sh_thread.time = time()
        else:
            self.view.settings().set('scope_hunter.view_enable', False)
            close_display = True

        if close_display:
            win = self.view.window()
            if win is not None:
                view = win.get_output_panel('scopehunter.results')
                parent_win = view.window()
                if parent_win:
                    parent_win.run_command('hide_panel', {'cancel': True})
                if TOOLTIP_SUPPORT:
                    mdpopups.hide_popup(self.view)
                if (
                    self.view is not None and
                    sh_thread.is_enabled(view) and
                    bool(sh_settings.get("highlight_extent", False)) and
                    len(view.get_regions("scope_hunter"))
                ):
                    view.erase_regions("scope_hunter")
    def on_popup_navigate(self, href):
        if href.startswith('https://'):
            webbrowser.open_new_tab(href)
            show_status_message(self.view, 'URL is opened.')
        elif href.startswith(PREFIX_COPY):
            sublime.set_clipboard(href[len(PREFIX_COPY):])
            show_status_message(self.view, 'Command is copied.')

        mdpopups.hide_popup(self.view)
Esempio n. 5
0
 def on_navigate_unmatched(self, href):
     """Handle unmatched click."""
     if HOVER_SUPPORT:
         pt = int(href)
         mdpopups.hide_popup(self.popup_view)
         self.popup_view.run_command("bh_offscreen_popup", {
             "point": pt,
             "no_threshold": True
         })
Esempio n. 6
0
 def on_navigate(self, href):
     """Navigate to code position."""
     if HOVER_SUPPORT:
         try:
             pt = int(href)
             self.popup_view.sel().clear()
             self.popup_view.sel().add(sublime.Region(pt))
             self.popup_view.show(pt)
             mdpopups.hide_popup(self.popup_view)
         except Exception:
             log("Problem handling popup event:\n%s" % str(traceback.format_exc()))
Esempio n. 7
0
 def on_navigate(self, href):
     """Navigate to code position."""
     if HOVER_SUPPORT:
         try:
             pt = int(href)
             self.popup_view.sel().clear()
             self.popup_view.sel().add(sublime.Region(pt))
             self.popup_view.show(pt)
             mdpopups.hide_popup(self.popup_view)
         except Exception:
             log("Problem handling popup event:\n%s" % str(traceback.format_exc()))
    def _show_popup(self, data, location):
        if mdpopups.is_popup_visible(self.view):
            mdpopups.hide_popup(self.view)

        mdpopups.show_popup(self.view,
                            TEMPLATE.format(**data),
                            css=CSS,
                            wrapper_class=WRAPPER_CLASS,
                            max_width=400,
                            location=location,
                            flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY,
                            on_navigate=self.on_popup_navigate)
Esempio n. 9
0
    def on_popup_navigate(self, href):
        if href.startswith(POPUP_HREF_PREFIX_OPEN):
            word = href[len(POPUP_HREF_PREFIX_OPEN):]

            try:
                subprocess.check_call(['open', 'dict://{}'.format(word)])
            except subprocess.SubprocessError as e:
                message = 'Dictionary.app could not be opened.'
                status_message(self.view, message)

            mdpopups.hide_popup(self.view)
        elif href == POPUP_HREF_CLOSE:
            mdpopups.hide_popup(self.view)
Esempio n. 10
0
    def on_close_phantom_and_popup(self, href):
        """Close all phantoms."""

        global mdpop_params
        mdpopups.erase_phantoms(self.view, 'trans')
        mdpopups.hide_popup(self.view)
        if "mdpopups.default_formatting" in mdpop_params:
            self.system_setting.set(
                "mdpopups.default_formatting",
                mdpop_params["mdpopups.default_formatting"])
        else:
            self.system_setting.erase("mdpopups.default_formatting")
        if "mdpopups.user_css" in mdpop_params:
            self.system_setting.set("mdpopups.user_css",
                                    mdpop_params["mdpopups.user_css"])
        else:
            self.system_setting.erase("mdpopups.user_css")
        sublime.save_settings("Preferences.sublime-settings")
Esempio n. 11
0
    def on_close_phantom_and_popup(self, href):
        """Close all phantoms."""

        global mdpop_params
        mdpopups.erase_phantoms(self.view, 'trans')
        mdpopups.hide_popup(self.view)
        if "mdpopups.default_formatting" in mdpop_params:
            self.system_setting.set(
                "mdpopups.default_formatting",
                mdpop_params["mdpopups.default_formatting"])
        else:
            self.system_setting.erase("mdpopups.default_formatting")
        if "mdpopups.user_css" in mdpop_params:
            self.system_setting.set("mdpopups.user_css",
                                    mdpop_params["mdpopups.user_css"])
        else:
            self.system_setting.erase("mdpopups.user_css")
        sublime.save_settings("Preferences.sublime-settings")
Esempio n. 12
0
    def _do_show_popup(self, popup_info):
        if mdpopups.is_popup_visible(self.view):
            mdpopups.hide_popup(self.view)

        data = popup_info['data']
        content = POPUP_TEMPLATE.format(
            word=data['word'],
            word_escaped=data['word_escaped'],
            definition=data['definition'],
        )

        mdpopups.show_popup(
            self.view,
            content,
            css=POPUP_CSS,
            flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY,
            location=popup_info['location'],
            max_width=POPUP_MAX_WIDTH,
            wrapper_class=POPUP_WRAPPER_CLASS,
            on_navigate=self.on_popup_navigate,
        )
Esempio n. 13
0
    def handle_href(self, href):
        """Handle href."""

        hires = None
        hsl = self.hsl
        colornames = False
        if href in ('hsl', 'rgb'):
            hsl = href == 'hsl'
            color = self.color
        elif href.startswith('insert'):
            color = href.split(':')[1]
        elif href.startswith('hirespick'):
            hires = href.split(':')[1]
            color = self.color
        elif href == "colornames":
            color = self.color
            colornames = True
        elif href == 'edit':
            color = self.color
        else:
            color = href
        if href == 'cancel':
            mdpopups.hide_popup(self.view)
            if self.on_cancel is not None:
                call = self.on_cancel.get('command', 'color_helper')
                args = self.on_cancel.get('args', {})
                self.view.run_command(call, args)
        elif href == 'edit':
            mdpopups.hide_popup(self.view)
            self.view.window().run_command(
                'color_helper_picker_panel', {
                    "color": color,
                    "allowed_colors": self.allowed_colors,
                    "use_hex_argb": self.use_hex_argb,
                    "compress_hex": self.compress_hex,
                    "on_done": self.on_done,
                    "on_cancel": self.on_cancel
                })
        elif href.startswith('insert'):
            mdpopups.hide_popup(self.view)
            if self.on_done is not None:
                call = self.on_done.get('command', 'color_helper')
                args = copy.deepcopy(self.on_done.get('args', {}))
                args['color'] = color
                self.view.run_command(call, args)
        else:
            self.view.run_command(
                'color_helper_picker', {
                    "color": color,
                    "allowed_colors": self.allowed_colors,
                    "use_hex_argb": self.use_hex_argb,
                    "compress_hex": self.compress_hex,
                    "hsl": hsl,
                    "hirespick": hires,
                    "colornames": colornames,
                    "on_done": self.on_done,
                    "on_cancel": self.on_cancel
                })
Esempio n. 14
0
    def run(self):
        """Enable or disable instant scoper."""

        sh_thread.instant_scoper = False if sh_thread.instant_scoper else True
        if sh_thread.instant_scoper:
            sh_thread.modified = True
            sh_thread.time = time()
        else:
            win = sublime.active_window()
            if win is not None:
                view = win.get_output_panel('scope_viewer')
                parent_win = view.window()
                if parent_win:
                    parent_win.run_command('hide_panel', {'cancel': True})
                view = win.active_view()
                if view is not None and TOOLTIP_SUPPORT:
                    mdpopups.hide_popup(view)
                if (
                    view is not None and
                    sh_thread.is_enabled(view) and
                    bool(sh_settings.get("highlight_extent", False)) and
                    len(view.get_regions("scope_hunter"))
                ):
                    view.erase_regions("scope_hunter")
    def handle_href(self, href):
        """Handle href."""

        hires = None
        hsl = self.hsl
        colornames = False
        if href in ('hsl', 'rgb'):
            hsl = href == 'hsl'
            color = self.color
        elif href.startswith('insert'):
            color = href.split(':')[1]
        elif href.startswith('hirespick'):
            hires = href.split(':')[1]
            color = self.color
        elif href == "colornames":
            color = self.color
            colornames = True
        elif href == 'edit':
            color = self.color
        else:
            color = href
        if href == 'cancel':
            mdpopups.hide_popup(self.view)
            if self.on_cancel is not None:
                call = self.on_cancel.get('command', 'color_helper')
                args = self.on_cancel.get('args', {})
                self.view.run_command(call, args)
        elif href == 'edit':
            mdpopups.hide_popup(self.view)
            self.view.window().run_command(
                'color_helper_picker_panel',
                {
                    "color": color, "allowed_colors": self.allowed_colors,
                    "use_hex_argb": self.use_hex_argb, "compress_hex": self.compress_hex,
                    "on_done": self.on_done, "on_cancel": self.on_cancel
                }
            )
        elif href.startswith('insert'):
            mdpopups.hide_popup(self.view)
            if self.on_done is not None:
                call = self.on_done.get('command', 'color_helper')
                args = copy.deepcopy(self.on_done.get('args', {}))
                args['color'] = color
                self.view.run_command(call, args)
        else:
            self.view.run_command(
                'color_helper_picker',
                {
                    "color": color, "allowed_colors": self.allowed_colors,
                    "use_hex_argb": self.use_hex_argb, "compress_hex": self.compress_hex,
                    "hsl": hsl, "hirespick": hires, "colornames": colornames,
                    "on_done": self.on_done, "on_cancel": self.on_cancel
                }
            )
Esempio n. 16
0
    def on_navigate(self, href):
        """Exceute link callback."""

        params = href.split(':')
        key = params[0]
        index = int(params[1]) if len(params) > 1 else None
        if key == 'reload':
            mdpopups.hide_popup(self.view)
            reinit_plugin()
            self.view.run_command('get_selection_scope')
        if key == 'copy-all':
            sublime.set_clipboard('\n'.join(self.scope_bfr))
            notify('Copied: All')
        elif key == 'copy-scope':
            copy_data(
                self.scope_bfr,
                SCOPE_KEY,
                index,
                lambda x: x.replace('\n' + ' ' * 31, ' ')
            )
        elif key == 'copy-points':
            copy_data(self.scope_bfr, PTS_KEY, index)
        elif key == 'copy-line-char':
            copy_data(self.scope_bfr, CHAR_LINE_KEY, index)
        elif key == 'copy-fg':
            copy_data(self.scope_bfr, FG_KEY, index)
        elif key == 'copy-fg-sim':
            copy_data(self.scope_bfr, FG_SIM_KEY, index)
        elif key == 'copy-fg-hash':
            copy_data(self.scope_bfr, HASHED_FG_KEY, index)
        elif key == 'copy-fg-hash-sim':
            copy_data(self.scope_bfr, HASHED_FG_SIM_KEY, index)
        elif key == 'copy-bg':
            copy_data(self.scope_bfr, BG_KEY, index)
        elif key == 'copy-bg-sim':
            copy_data(self.scope_bfr, BG_SIM_KEY, index)
        elif key == 'copy-style':
            copy_data(self.scope_bfr, STYLE_KEY, index)
        elif key == 'copy-fg-sel-name':
            copy_data(self.scope_bfr, FG_NAME_KEY, index)
        elif key == 'copy-fg-sel-scope':
            copy_data(self.scope_bfr, FG_SCOPE_KEY, index)
        elif key == 'copy-fg-hash-sel-name':
            copy_data(self.scope_bfr, HASHED_FG_NAME_KEY, index)
        elif key == 'copy-fg-hash-sel-scope':
            copy_data(self.scope_bfr, HASHED_FG_SCOPE_KEY, index)
        elif key == 'copy-bg-sel-name':
            copy_data(self.scope_bfr, BG_NAME_KEY, index)
        elif key == 'copy-bg-sel-scope':
            copy_data(self.scope_bfr, BG_SCOPE_KEY, index)
        elif key == 'copy-bold-sel-name':
            copy_data(self.scope_bfr, BOLD_NAME_KEY, index)
        elif key == 'copy-bold-sel-scope':
            copy_data(self.scope_bfr, BOLD_SCOPE_KEY, index)
        elif key == 'copy-italic-sel-name':
            copy_data(self.scope_bfr, ITALIC_NAME_KEY, index)
        elif key == 'copy-italic-sel-scope':
            copy_data(self.scope_bfr, ITALIC_SCOPE_KEY, index)
        elif key == 'copy-scheme':
            copy_data(self.scope_bfr, SCHEME_KEY, index)
        elif key == 'copy-syntax':
            copy_data(self.scope_bfr, SYNTAX_KEY, index)
        elif key == 'copy-overrides':
            copy_data(self.scope_bfr, OVERRIDE_SCHEME_KEY, index, lambda text: self.overrides[int(params[2]) - 1])
        elif key == 'scheme' and self.scheme_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.scheme_file.replace(
                        '\\', '/'
                    ).replace('Packages/', '', 1)
                }
            )
        elif key == 'syntax' and self.syntax_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.syntax_file.replace(
                        '\\', '/'
                    ).replace('Packages/', '', 1)
                }
            )
        elif key == 'override':
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.overrides[int(params[2]) - 1].replace('Packages/', '', 1)
                }
            )
Esempio n. 17
0
    def show_popup(self, menu):
        global BACK
        global BACK_TO_SUBMENU

        settings = sublime.load_settings('Preferences.sublime-settings')
        popup = []

        marked = settings.get('theme_config_marked', False)
        unmarked = settings.get('theme_config_unmarked', False)
        radio_marked = settings.get('theme_config_radio_marked', False)
        radio_unmarked = settings.get('theme_config_radio_unmarked', False)

        if marked is False:
            marked = MARKED

        if unmarked is False:
            unmarked = UNMARKED

        if radio_marked is False:
            radio_marked = RADIO_MARKED

        if radio_unmarked is False:
            radio_unmarked = RADIO_UNMARKED

        if menu == 'Home':
            popup.append(SECTIONS_LABEL)
            for k in (['UI Theme', 'Color Scheme'] +
                      list(SUB_SECTIONS.keys()) +
                      list(SECTION_OPTIONS.keys())):
                popup.append(SECTIONS % {'section': k})
        elif menu == 'UI Theme':
            theme = settings.get('theme', '')
            boxy_themes = [
                os.path.basename(bt) for bt in sorted(
                    sublime.find_resources('Boxy*.sublime-theme')
                ) if is_boxy_res(bt)
            ]
            popup.append(THEME_LABEL)
            for option in boxy_themes:
                option_value = theme == option
                popup.append(
                    THEME % {
                        'name': option,
                        'status': radio_marked if option_value else radio_unmarked,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'UI Theme'
                    }
                )
            if theme is not None and theme not in boxy_themes:
                popup.append(
                    OTHER_THEME % {
                        'name': theme,
                        'status': radio_marked,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'UI Theme'
                    }
                )
        elif menu == 'Color Scheme':
            scheme = settings.get('color_scheme', '')
            boxy_schemes = [
                bs for bs in sorted(
                    sublime.find_resources('Boxy*.tmTheme')
                ) if is_boxy_res(bs)
            ]
            popup.append(SCHEME_LABEL)
            for option in boxy_schemes:
                option_value = scheme == option
                popup.append(
                    SCHEME % {
                        'name': option,
                        'status': radio_marked if option_value else radio_unmarked,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'Color Scheme'
                    }
                )
            if scheme is not None and scheme not in boxy_schemes:
                popup.append(
                    OTHER_SCHEME % {
                        'name': scheme,
                        'status': radio_marked,
                        'set': option,
                        'class': '.success',
                        'section': 'Color Scheme'
                    }
                )
        elif menu in SUB_SECTIONS.keys():
            popup.append(SECTION_LABEL % menu)
            for k in SUB_SECTIONS[menu]:
                popup.append(SECTIONS % {'section': k})
            BACK = '[← Back](back-Home){: .boxy-control .boxy-control-back }'
            BACK_TO_SUBMENU = '''[← Back](back-%s){: .boxy-control\
             .boxy-control-back }''' % (menu)
        elif menu in SECTION_OPTIONS.keys():
            popup.append(SECTION_LABEL % menu)
            for option in SECTION_OPTIONS[menu]:
                option_value = bool(settings.get(option, False))
                popup.append(
                    GENERAL_SETTING % {
                        'name': option,
                        'status': marked if option_value else unmarked,
                        'set': str(not option_value),
                        'class': '.success' if option_value else '.error',
                        'section': menu
                    }
                )
            BACK = '[← Back](back-Home){: .boxy-control .boxy-control-back }'
        else:
            popup.append(SECTION_LABEL % menu)
            for option in SUB_SECTION_OPTIONS[menu]:
                option_value = bool(settings.get(option, False))
                popup.append(
                    GENERAL_SETTING % {
                        'name': option,
                        'status': marked if option_value else unmarked,
                        'set': str(not option_value),
                        'class': '.success' if option_value else '.error',
                        'section': menu
                    }
                )
            BACK = BACK_TO_SUBMENU

        if menu != 'Home':
            popup.append(BACK)

        mdpopups.hide_popup(self.view)
        mdpopups.show_popup(
            self.view,
            ''.join(popup),
            css=STYLES,
            wrapper_class='boxy-config',
            on_navigate=self.on_navigate,
            max_width=1024,
            max_height=1024
        )
Esempio n. 18
0
 def run(self):
     global mdpop_params
     self.view = self.window.active_view()
     mdpopups.erase_phantoms(self.view, 'trans')
     mdpopups.hide_popup(self.view)
Esempio n. 19
0
    def on_hover(self, view, point, hover_zone):

        if view.settings().get('is_widget'):
            return

        if not view.settings().get('show_definitions'):
            return

        if hover_zone != sublime.HOVER_TEXT:
            return

        if not view.score_selector(point, 'source.lsl'):
            return

        word = view.substr(view.word(point))

        if not word:
            return

        if not KWDB:
            return

        try:
            tooltipRows = []
            for result in KWDB.findall(".//*[@name='" + word + "']"):
                if result.tag == 'param':
                    continue
                if result.tag == 'function' or result.tag == 'constant':
                    tooltipRows.append(
                        '### (%s) <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>'
                        % (result.get('type', 'void'), result.get('name'),
                           result.get('name')))
                else:
                    tooltipRows.append(
                        '### <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>'
                        % (result.get('name'), result.get('name')))
                if result.tag == 'constant':
                    tooltipRows.append(' ')
                    tooltipRows.append('**Value**: %s' %
                                       str(result.get('value')))
                if result.get('status', None) is not None and result.get(
                        'status', 'normal') != 'normal':
                    tooltipRows.append(' ')
                    tooltipRows.append(
                        '<body class="danger">**Status**: %s</body>' %
                        result.get('status', 'normal'))
                if result.get('delay', None) is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('**Delay**: %s' %
                                       str(result.get('delay')))
                if result.get('energy', None) is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('**Energy**: %s' %
                                       str(result.get('energy')))
                if result.tag == 'function' or result.tag == 'event':
                    if result.findall('./param') != []:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Parameters')
                        for param in result.iter('param'):
                            tooltipRows.append(
                                '* (%s) **%s**' %
                                (param.get('type'), param.get('name')))
                if result.find('description').text is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('#### Description')
                    tooltipRows.append(' ')
                    tooltipRows.append('%s' %
                                       result.find('description').text.strip())
#               add version info
#               add grid info by splitting spaces and re-joining as markdown list
#          seperate entries by horizontal line

            if 0 < len(tooltipRows):
                mdpopups.show_popup(view,
                                    '\n'.join(tooltipRows),
                                    flags=sublime.COOPERATE_WITH_AUTO_COMPLETE
                                    | sublime.HIDE_ON_MOUSE_MOVE_AWAY,
                                    location=point,
                                    max_width=1024,
                                    on_navigate=self.on_navigate)
                return

        except Exception as e:
            print(e)

        mdpopups.hide_popup(view)
    def show_popup(self, menu):

        settings = sublime.load_settings('Preferences.sublime-settings')
        popup = []

        marked = settings.get('theme_config_marked', False)
        unmarked = settings.get('theme_config_unmarked', False)
        radio_marked = settings.get('theme_config_radio_marked', False)
        radio_unmarked = settings.get('theme_config_radio_unmarked', False)

        if marked is False:
            marked = MARKED

        if unmarked is False:
            unmarked = UNMARKED

        if radio_marked is False:
            radio_marked = RADIO_MARKED

        if radio_unmarked is False:
            radio_unmarked = RADIO_UNMARKED

        if menu != 'Main':
            popup = [BACK]

        if menu == 'Main':
            popup.append(SECTIONS_LABEL)
            for k in sorted(['Theme', 'Color Scheme'] + list(OPTIONS.keys())):
                popup.append(SECTIONS % {'section': k})

        elif menu == 'Theme':
            theme = settings.get('theme', '')
            mt_themes = [
                os.path.basename(bt) for bt in sorted(
                    sublime.find_resources('Material-Theme*.sublime-theme'))
                if is_mt_res(bt)
            ]
            popup.append(THEME_LABEL)
            for option in sorted(mt_themes):
                option_value = theme == option
                popup.append(
                    THEME % {
                        'name': option,
                        'status':
                        RADIO_MARKED if option_value else RADIO_UNMARKED,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'Theme'
                    })
            if theme is not None and theme not in mt_themes:
                popup.append(
                    OTHER_THEME % {
                        'name': theme,
                        'status': RADIO_MARKED,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'Theme'
                    })

        elif menu == 'Color Scheme':
            scheme = settings.get('color_scheme', '')
            mt_schemes = [
                bs for bs in sorted(
                    sublime.find_resources('Material-Theme*.tmTheme'))
                if is_mt_res(bs)
            ]
            popup.append(SCHEME_LABEL)
            for option in sorted(mt_schemes):
                option_value = scheme == option
                scheme_name = option[32:].replace('.tmTheme', '')
                popup.append(
                    SCHEME % {
                        'name': scheme_name,
                        'status':
                        RADIO_MARKED if option_value else RADIO_UNMARKED,
                        'set': option,
                        'class': '.success' if option_value else '.error',
                        'section': 'Color Scheme'
                    })
                if scheme is not None and scheme not in mt_schemes:
                    popup.append(
                        OTHER_SCHEME % {
                            'name': scheme,
                            'status': RADIO_MARKED,
                            'set': option,
                            'class': '.success',
                            'section': 'Color Scheme'
                        })
        else:
            popup.append(SECTION_LABEL % menu)
            for option in sorted(OPTIONS[menu]):
                option_value = bool(settings.get(option, False))
                popup.append(
                    GENERAL_SETTING % {
                        'name': option,
                        'status': MARKED if option_value else UNMARKED,
                        'set': str(not option_value),
                        'class': '.success' if option_value else '.error',
                        'section': menu
                    })

        mdpopups.hide_popup(self.view)
        mdpopups.show_popup(self.view,
                            ''.join(popup),
                            css=STYLE,
                            wrapper_class='mt-config',
                            on_navigate=self.on_navigate,
                            max_width=800,
                            max_height=400)
Esempio n. 21
0
def on_close_popup(href):
    """Close the popup."""
    view = active_view()
    mdpopups.hide_popup(view)
Esempio n. 22
0
 def on_navigate_unmatched(self, href):
     """Handle unmatched click."""
     if HOVER_SUPPORT:
         if href == 'match':
             mdpopups.hide_popup(self.popup_view)
             self.popup_view.run_command("bh_async_key", {"lines": True})
Esempio n. 23
0
    def on_hover(self, view, point, hover_zone):

        if view.settings().get('is_widget'):
            return

        if not view.settings().get('show_definitions'):
            return

        if hover_zone != sublime.HOVER_TEXT:
            return

        if not view.score_selector(point, 'source.lsl'):
            return

        word = view.substr(view.word(point))

        if not word:
            return

        if TOOLTIP_DATA is None:
            return

        try:
            tooltipRows = []
            for result in TOOLTIP_DATA:
                if result.get('name', None) == word:
                    if 'type' in result or result['name'].startswith('ll'):
                        tooltipRows.append(
                            '### (%s) <a href="%s%s">%s</a>' %
                            (result.get('type', 'void'), SL_WIKI,
                             result['name'], result['name']))
                    else:
                        tooltipRows.append(
                            '### <a href="%s%s">%s</a>' %
                            (SL_WIKI, result['name'], result['name']))
                    if 'value' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('**Value**: %s' %
                                           str(result['value']))
                    if 'version' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('**SL server version**: %s' %
                                           result['version'])
                    if 'status' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append(
                            '<body class="danger">**Status**: %s</body>' %
                            result['status'])
                    if 'delay' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('**Delay**: %s' %
                                           str(result['delay']))
                    if 'energy' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('**Energy**: %s' %
                                           str(result['energy']))
                    if 'param' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Parameters')
                        if type(result['param']) is dict:
                            tooltipRows.append('* (%s) **%s**' %
                                               (result['param']['type'],
                                                result['param']['name']))
                        elif type(result['param']) is list:
                            for param in result['param']:
                                tooltipRows.append(
                                    '* (%s) **%s**' %
                                    (param['type'], param['name']))
                    if 'description' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Description')
                        tooltipRows.append(' ')
                        tooltipRows.append('%s' %
                                           result['description']['en_US'])
                    if 'snippets' in result:
                        tooltipRows.append('#### Snippets')
                        for snippet in result['snippets']:
                            tooltipRows.append(' ')
                            tooltipRows.append('```lsl')
                            tooltipRows.append('%s' % snippet)
                            tooltipRows.append('```')
            if 0 < len(tooltipRows):
                mdpopups.show_popup(view,
                                    '\n'.join(tooltipRows),
                                    flags=(sublime.COOPERATE_WITH_AUTO_COMPLETE
                                           | sublime.HIDE_ON_MOUSE_MOVE_AWAY),
                                    location=point,
                                    wrapper_class='lsl',
                                    max_width=1280,
                                    max_height=960,
                                    on_navigate=self.on_navigate,
                                    on_hide=self.on_hide(view))
                return
        except Exception as e:
            print(e)

        mdpopups.hide_popup(view)
Esempio n. 24
0
    def on_hover(self, view, point, hover_zone):

        if view.settings().get('is_widget'):
            return

        if not view.settings().get('show_definitions'):
            return

        if hover_zone is not sublime.HOVER_TEXT:
            return

        if not view.score_selector(point, 'source.lsl'):
            return

        # TODO: fix makopo/sublime-text-tooltip-lsl#6
        # word = view.substr(view.expand_by_class(point, sublime.CLASS_WORD_START | sublime.CLASS_WORD_END, "./\\()\"'-:,.;<>~!@#$%^&*|+=[]{}`~?"))
        word = view.substr(view.word(point))

        if not word:
            return

        from .keyword_data_loader import LSL_KEYWORD_DATA
        if LSL_KEYWORD_DATA is None:
            return

        try:
            tooltipRows = []

            result = LSL_KEYWORD_DATA[word]

            if result is None:
                return

            # Python-Markdown/markdown used by facelessuser/sublime-markdown-popups requires 4 spaces indentation

            if 'type' in result or word.startswith('ll'):
                return_value = '({}) '.format(result['type']) if 'type' in result else ''
                # TODO: return_value = f'({result['type']}) ' if 'type' in result else ''
                if 'params' in result:
                    paramsCache = []
                    for param in result['params']:
                        if 'default' in param:
                            paramsCache.append('<a href="{}{}">{}</a> {} (Default: {})'.format(SL_WIKI, param['type'], param['type'], param['name'], param['default']))
                        else:
                            paramsCache.append('<a href="{}{}">{}</a> {}'.format(SL_WIKI, param['type'], param['type'], param['name']))
                    params = '(' + ', '.join(paramsCache) + ')'
                else:
                    params = ''
                has_value = ' = {}'.format(str(result['value'])) if 'value' in result else ''
                if 'value_description' in result:
                    has_value = has_value + ' = {}'.format(str(result['value_description']))
                tooltipRows.append('{}<a href="{}{}">{}</a>{}{}'.format(return_value, SL_WIKI, word, word, params, has_value))
                # TODO: tooltipRows.append(f'{return_value}<a href="{SL_WIKI}{word}">{word}</a>{params}{has_value}')
            else:
                tooltipRows.append('<a href="{}{}">{}</a>'.format(SL_WIKI, word, word))
                # TODO: tooltipRows.append(f'<a href="{SL_WIKI}{word}">{word}</a>')
            tooltipRows.append(' ')
            if 'type' in result or word.startswith('ll'):
                if 'params' in result:
                    tooltipRows.append('* Params:')
                    for param in result['params']:
                        tooltipRows.append('    * ({}) {}'.format(param['type'], param['name']))
                        if 'default' in param:
                            tooltipRows.append('        * default: {}'.format(param['default']))
                        if 'description' in param:
                            tooltipRows.append('        * description: {}'.format(param['description']))
            if 'function-id' in result:
                tooltipRows.append('* [Function id](https://wiki.secondlife.com/wiki/LSL_Function_ID): {}'.format(str(result['function-id'])))
            if 'required_permissions' in result:
                tooltipRows.append('* [Required permissions](https://wiki.secondlife.com/wiki/Category:LSL_Requires_Permissions): ' + ', '.join(str('<a href="{}{}">{}</a>'.format(SL_WIKI, permission, permission)) for permission in result['required_permissions']))
                # TODO: tooltipRows.append('* [Required permissions](https://wiki.secondlife.com/wiki/Category:LSL_Requires_Permissions): ' + ', '.join(str(f'<a href="{SL_WIKI}{permission}">{permission}</a>') for permission in result['required_permissions']))
            if 'version' in result:
                tooltipRows.append('* SL server version: {}'.format(result['version']))
            if 'status' in result:
                tooltipRows.append('* Status: {}'.format(result['status']))
            if 'delay' in result:
                # delay is float (in seconds) or string ('variable' for llSleep)
                tooltipRows.append('* [Delay](https://wiki.secondlife.com/wiki/LSL_Delay): {}'.format(str(result['delay'])))
            if 'energy' in result:
                tooltipRows.append('* Energy: {}'.format(str(result['energy'])))
            tooltipRows.append('* SL JIRA: [{}](http://jira.secondlife.com/secure/IssueNavigator!executeAdvanced.jspa?jqlQuery=%28summary+%7E+%22{}%22+OR+description+%7E+%22{}%22%29+&runQuery=true)'.format(word, word, word))
            # TODO: tooltipRows.append(f'* SL JIRA: [{word}](http://jira.secondlife.com/secure/IssueNavigator!executeAdvanced.jspa?jqlQuery=%28summary+%7E+%22{word}%22+OR+description+%7E+%22{word}%22%29+&runQuery=true)')
            if 'description' in result:
                tooltipRows.append(' ')
                tooltipRows.append('---')
                tooltipRows.append(' ')
                tooltipRows.append('{}'.format(result['description']))
            if 'related' in result:
                tooltipRows.append(' ')
                tooltipRows.append('---')
                tooltipRows.append(' ')
                tooltipRows.append('Related:')
                tooltipRows.append(' ')
                if 'constants' in result['related']:
                    tooltipRows.append('* Constants: ' + ', '.join(str('<a href="{}{}">{}</a>'.format(SL_WIKI, related, related)) for related in result['related']['constants']))
                    # TODO: tooltipRows.append('* Constants: ' + ', '.join(str(f'<a href="{SL_WIKI}{related}">{related}</a>') for related in result['related']['constants']))
                if 'events' in result['related']:
                    tooltipRows.append('* Events: ' + ', '.join(str('<a href="{}{}">{}</a>'.format(SL_WIKI, related, related)) for related in result['related']['events']))
                    # TODO: f-strings
                if 'functions' in result['related']:
                    tooltipRows.append('* Functions: ' + ', '.join(str('<a href="{}{}">{}</a>'.format(SL_WIKI, related, related)) for related in result['related']['functions']))
                    # TODO: f-strings
                if 'slwiki' in result['related']:
                    tooltipRows.append('* SL wiki: ' + ', '.join(str('<a href="{}{}">{}</a>'.format(SL_WIKI, related, related)) for related in result['related']['slwiki']))
                    # TODO: f-strings
                if 'slwiki_categories' in result['related']:
                    tooltipRows.append('* SL wiki categories: ' + ', '.join(str('<a href="{}Category:{}">{}</a>'.format(SL_WIKI, related, related)) for related in result['related']['slwiki_categories']))
                    # TODO: f-strings
                if 'wikipedia' in result['related']:
                    tooltipRows.append('* Wikipedia (en): ' + ', '.join(str('<a href="{}{}">{}</a>'.format(WIKIPEDIA, related, related)) for related in result['related']['wikipedia']['en']))
                    # TODO: f-strings
            if 'usage' in result:
                tooltipRows.append(' ')
                tooltipRows.append('---')
                for usage_example in result['usage']:
                    tooltipRows.append(' ')
                    tooltipRows.append('```lsl')
                    tooltipRows.append('{}'.format(usage_example))
                    # TODO: tooltipRows.append(f'{usage_example}')
                    tooltipRows.append('```')
            if 'snippets' in result:
                tooltipRows.append(' ')
                tooltipRows.append('---')
                for snippet in result['snippets']:
                    tooltipRows.append(' ')
                    tooltipRows.append('```lsl')
                    tooltipRows.append('{}'.format(snippet))
                    # TODO: tooltipRows.append(f'{snippet}')
                    tooltipRows.append('```')

            if 0 < len(tooltipRows):
                tooltipText = mdpopups.format_frontmatter({'allow_code_wrap': True})
                tooltipText += '\n'
                tooltipText += '\n'.join(tooltipRows)
                # mdpopups.color_box for vectors? or mdpopups.tint with placeholder image?
                mdpopups.show_popup(view,
                                    tooltipText,
                                    flags=(sublime.COOPERATE_WITH_AUTO_COMPLETE | sublime.HIDE_ON_MOUSE_MOVE_AWAY),
                                    location=point,
                                    wrapper_class='lsl',
                                    max_width=640,
                                    max_height=480,
                                    on_navigate=self.on_navigate,
                                    on_hide=self.on_hide(view))
                return
            mdpopups.hide_popup(view)
        except Exception as e:
            mdpopups.hide_popup(view)
Esempio n. 25
0
    def handle_href(self, href):
        """Handle HREF."""

        hires = None
        colornames = False
        mode = self.mode
        tool = None
        controls = self.controls
        if href.startswith('__space__'):
            # If we received a color space switch to that picker.
            space = href.split(':')[1]
            color = self.color.convert(space).to_string(**COLOR_FULL_PREC)
            mode = space
        elif href.startswith('__controls__'):
            color = self.color.to_string(**COLOR_FULL_PREC)
            controls = href.split(':')[1]
        elif href.startswith('__insert__'):
            # We will need to call the insert dialog
            color = href.split(':')[1]
        elif href.startswith('__hirespick__'):
            # We need to open a high resolution channel picker
            hires = href.split(':')[1]
            color = self.color.to_string(**COLOR_FULL_PREC)
        elif href.startswith('__tools__'):
            color = self.color.to_string(**COLOR_FULL_PREC)
        elif href.startswith('__tool__'):
            tool = href.split(':')[1]
            color = self.color.to_string(**DEFAULT)
        elif href == "__colornames__":
            # We need to open the color name picker
            color = self.color.to_string(**COLOR_FULL_PREC)
            colornames = True
        else:
            # Process we need to update the current color
            color = href
        if href == '__cancel__':
            # Close color picker and call the callback if one was provided
            mdpopups.hide_popup(self.view)
            if self.on_cancel is not None:
                call = self.on_cancel.get('command', 'color_helper')
                args = self.on_cancel.get('args', {})
                self.view.run_command(call, args)
        elif href == '__tools__':
            self.show_tools()
        elif href.startswith('__tool__'):
            # Edit color in edit panel
            mdpopups.hide_popup(self.view)

            # Provide callback info for the color picker.
            on_done = {
                "command": "color_helper_picker",
                "args": {
                    "mode": self.mode,
                    "controls": self.controls
                }
            }

            # On edit cancel, call the color picker with the current color.
            on_cancel = {
                "command": "color_helper_picker",
                "args": {
                    "mode": self.mode,
                    "controls": self.controls,
                    "color": self.color.to_string(**COLOR_FULL_PREC)
                }
            }

            if tool == '__contrast__':
                cmd = 'color_helper_contrast_ratio'
            elif tool == "__colormod__":
                cmd = 'color_helper_sublime_color_mod'
            else:
                cmd = 'color_helper_edit'

            # Call the edit input panel
            self.view.run_command(
                cmd, {
                    "initial":
                    Color(color,
                          filters=util.SRGB_SPACES).to_string(**DEFAULT),
                    "on_done":
                    on_done,
                    "on_cancel":
                    on_cancel
                })

        elif href.startswith('__insert__'):
            # Call back to ColorHelper to insert the color.
            mdpopups.hide_popup(self.view)
            if self.on_done is None:
                on_done = {
                    'command': 'color_helper',
                    'args': {
                        'mode': "result",
                        "result_type": "__color_picker__"
                    }
                }
            else:
                on_done = self.on_done
            call = on_done.get('command')
            if call is None:
                return
            args = copy.deepcopy(on_done.get('args', {}))
            args['color'] = color
            self.view.run_command(call, args)
        else:
            # Call color picker with the provided color.
            self.view.run_command(
                'color_helper_picker', {
                    "color": color,
                    "mode": mode,
                    "hirespick": hires,
                    "colornames": colornames,
                    "controls": controls,
                    "on_done": self.on_done,
                    "on_cancel": self.on_cancel
                })
    def on_navigate(self, href):
        """Exceute link callback."""

        params = href.split(':')
        key = params[0]
        index = int(params[1]) if len(params) > 1 else None
        if key == 'reload':
            mdpopups.hide_popup(self.view)
            reinit_plugin()
            self.view.run_command('get_selection_scope')
        if key == 'copy-all':
            sublime.set_clipboard('\n'.join(self.scope_bfr))
            notify('Copied: All')
        elif key == 'copy-scope':
            copy_data(
                self.scope_bfr,
                SCOPE_KEY,
                index,
                lambda x: x.replace('\n' + ' ' * 31, ' ')
            )
        elif key == 'copy-points':
            copy_data(self.scope_bfr, PTS_KEY, index)
        elif key == 'copy-line-char':
            copy_data(self.scope_bfr, CHAR_LINE_KEY, index)
        elif key == 'copy-fg':
            copy_data(self.scope_bfr, FG_KEY, index)
        elif key == 'copy-fg-sim':
            copy_data(self.scope_bfr, FG_SIM_KEY, index)
        elif key == 'copy-fg-hash':
            copy_data(self.scope_bfr, HASHED_FG_KEY, index)
        elif key == 'copy-fg-hash-sim':
            copy_data(self.scope_bfr, HASHED_FG_SIM_KEY, index)
        elif key == 'copy-bg':
            copy_data(self.scope_bfr, BG_KEY, index)
        elif key == 'copy-bg-sim':
            copy_data(self.scope_bfr, BG_SIM_KEY, index)
        elif key == 'copy-style':
            copy_data(self.scope_bfr, STYLE_KEY, index)
        elif key == 'copy-fg-sel-name':
            copy_data(self.scope_bfr, FG_NAME_KEY, index)
        elif key == 'copy-fg-sel-scope':
            copy_data(self.scope_bfr, FG_SCOPE_KEY, index)
        elif key == 'copy-fg-hash-sel-name':
            copy_data(self.scope_bfr, HASHED_FG_NAME_KEY, index)
        elif key == 'copy-fg-hash-sel-scope':
            copy_data(self.scope_bfr, HASHED_FG_SCOPE_KEY, index)
        elif key == 'copy-bg-sel-name':
            copy_data(self.scope_bfr, BG_NAME_KEY, index)
        elif key == 'copy-bg-sel-scope':
            copy_data(self.scope_bfr, BG_SCOPE_KEY, index)
        elif key == 'copy-bold-sel-name':
            copy_data(self.scope_bfr, BOLD_NAME_KEY, index)
        elif key == 'copy-bold-sel-scope':
            copy_data(self.scope_bfr, BOLD_SCOPE_KEY, index)
        elif key == 'copy-italic-sel-name':
            copy_data(self.scope_bfr, ITALIC_NAME_KEY, index)
        elif key == 'copy-italic-sel-scope':
            copy_data(self.scope_bfr, ITALIC_SCOPE_KEY, index)
        elif key == 'copy-underline-sel-name':
            copy_data(self.scope_bfr, UNDERLINE_NAME_KEY, index)
        elif key == 'copy-underline-sel-scope':
            copy_data(self.scope_bfr, UNDERLINE_SCOPE_KEY, index)
        elif key == 'copy-glow-sel-name':
            copy_data(self.scope_bfr, GLOW_NAME_KEY, index)
        elif key == 'copy-glow-sel-scope':
            copy_data(self.scope_bfr, GLOW_SCOPE_KEY, index)
        elif key == 'copy-scheme':
            copy_data(self.scope_bfr, SCHEME_KEY, index)
        elif key == 'copy-syntax':
            copy_data(self.scope_bfr, SYNTAX_KEY, index)
        elif key == 'copy-overrides':
            copy_data(self.scope_bfr, OVERRIDE_SCHEME_KEY, index, lambda text: self.overrides[int(params[2]) - 1])
        elif key == 'scheme' and self.scheme_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.scheme_file.replace(
                        '\\', '/'
                    ).replace('Packages/', '', 1)
                }
            )
        elif key == 'syntax' and self.syntax_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.syntax_file.replace(
                        '\\', '/'
                    ).replace('Packages/', '', 1)
                }
            )
        elif key == 'override':
            window = self.view.window()
            window.run_command(
                'open_file',
                {
                    "file": "${packages}/%s" % self.overrides[int(params[2]) - 1].replace('Packages/', '', 1)
                }
            )
Esempio n. 27
0
    def show_popup(self, menu):

      settings = sublime.load_settings('Preferences.sublime-settings')
      popup = []

      marked = settings.get('theme_config_marked', False)
      unmarked = settings.get('theme_config_unmarked', False)
      radio_marked = settings.get('theme_config_radio_marked', False)
      radio_unmarked = settings.get('theme_config_radio_unmarked', False)

      if marked is False:
        marked = MARKED

      if unmarked is False:
        unmarked = UNMARKED

      if radio_marked is False:
        radio_marked = RADIO_MARKED

      if radio_unmarked is False:
        radio_unmarked = RADIO_UNMARKED

      if menu != 'Main':
        popup = [BACK]

      if menu == 'Main':
        popup.append(SECTIONS_LABEL)
        for k in sorted(['Theme', 'Color Scheme'] + list(OPTIONS.keys())):
          popup.append(SECTIONS % {'section': k})

      elif menu == 'Theme':
        theme = settings.get('theme', '')
        mt_themes = [
          os.path.basename(bt) for bt in sorted(sublime.find_resources('Material-Theme*.sublime-theme')) if is_mt_res(bt)
        ]
        popup.append(THEME_LABEL)
        for option in sorted(mt_themes):
          option_value = theme == option
          popup.append(
            THEME % {
              'name': option,
              'status': RADIO_MARKED if option_value else RADIO_UNMARKED,
              'set': option,
              'class': '.success' if option_value else '.error',
              'section': 'Theme'
            }
          )
        if theme is not None and theme not in mt_themes:
          popup.append(
            OTHER_THEME % {
              'name': theme,
              'status': RADIO_MARKED,
              'set': option,
              'class': '.success' if option_value else '.error',
              'section': 'Theme'
            }
          )

      elif menu == 'Color Scheme':
        scheme = settings.get('color_scheme', '')
        mt_schemes = [
            bs for bs in sorted(sublime.find_resources('Material-Theme*.tmTheme')) if is_mt_res(bs)
        ]
        popup.append(SCHEME_LABEL)
        for option in sorted(mt_schemes):
          option_value = scheme == option
          scheme_name = option[32:].replace('.tmTheme', '')
          popup.append(
            SCHEME % {
              'name': scheme_name,
              'status': RADIO_MARKED if option_value else RADIO_UNMARKED,
              'set': option,
              'class': '.success' if option_value else '.error',
              'section': 'Color Scheme'
            }
          )
          if scheme is not None and scheme not in mt_schemes:
            popup.append(
              OTHER_SCHEME % {
                'name': scheme,
                'status': RADIO_MARKED,
                'set': option,
                'class': '.success',
                'section': 'Color Scheme'
              }
            )
      else:
        popup.append(SECTION_LABEL % menu)
        for option in sorted(OPTIONS[menu]):
          option_value = bool(settings.get(option, False))
          popup.append(
            GENERAL_SETTING % {
              'name': option,
              'status': MARKED if option_value else UNMARKED,
              'set': str(not option_value),
              'class': '.success' if option_value else '.error',
              'section': menu
            }
          )

      mdpopups.hide_popup(self.view)
      mdpopups.show_popup(
        self.view,
        ''.join(popup),
        css=STYLE,
        wrapper_class='mt-config',
        on_navigate=self.on_navigate,
        max_width=800,
        max_height=400
      )
Esempio n. 28
0
def on_close_popup(href):
    """Close the popup."""
    view = active_view()
    mdpopups.hide_popup(view)
Esempio n. 29
0
 def on_navigate_unmatched(self, href):
     """Handle unmatched click."""
     if HOVER_SUPPORT:
         pt = int(href)
         mdpopups.hide_popup(self.popup_view)
         self.popup_view.run_command("bh_offscreen_popup", {"point": pt, "no_threshold": True})
Esempio n. 30
0
    def show_popup(self, menu):

      settings = sublime.load_settings('Preferences.sublime-settings')
      popup = []

      if menu != 'Main':
        popup = [BACK]

      if menu == 'Main':
        popup.append(SECTIONS_LABEL)
        for k in ['Theme', 'Color Scheme'] + list(OPTIONS.keys()):
          popup.append(SECTIONS % {"section": k})

      elif menu == 'Theme':
        theme = settings.get('theme', '')
        mt_themes = [
          os.path.basename(bt) for bt in sorted(sublime.find_resources('Material-Theme*.sublime-theme')) if is_mt_res(bt)
        ]
        popup.append(THEME_LABEL)
        for option in mt_themes:
          option_value = theme == option
          popup.append(
            THEME % {
              "name": option,
              "status": RADIO_MARKED if option_value else RADIO_UNMARKED,
              "set": option,
              "class": '.success' if option_value else '.error',
              'section': "Theme"
            }
          )
        if theme is not None and theme not in mt_themes:
          popup.append(
            OTHER_THEME % {
              "name": theme,
              "status": RADIO_MARKED,
              "set": option,
              "class": '.success' if option_value else '.error',
              'section': "Theme"
            }
          )

      elif menu == 'Color Scheme':
        scheme = settings.get('color_scheme', '')
        mt_schemes = [
            bs for bs in sorted(sublime.find_resources('Material-Theme*.tmTheme')) if is_mt_res(bs)
        ]
        popup.append(SCHEME_LABEL)
        for option in mt_schemes:
          option_value = scheme == option
          scheme_name = option[32:].replace('/', ' ⚠️ ')
          popup.append(
            SCHEME % {
              "name": scheme_name,
              "status": RADIO_MARKED if option_value else RADIO_UNMARKED,
              "set": option,
              "class": '.success' if option_value else '.error',
              "section": 'Color Scheme'
            }
          )
          if scheme is not None and scheme not in mt_schemes:
            popup.append(
              OTHER_SCHEME % {
                "name": scheme,
                "status": RADIO_MARKED,
                "set": option,
                "class": '.success',
                "section": 'Color Scheme'
              }
            )
      else:
        popup.append(SECTION_LABEL % menu)
        for option in OPTIONS[menu]:
          option_value = bool(settings.get(option, False))
          popup.append(
            GENERAL_SETTING % {
              "name": option,
              "status": MARKED if option_value else UNMARKED,
              "set": str(not option_value),
              "class": '.success' if option_value else '.error',
              "section": menu
            }
          )

      mdpopups.hide_popup(self.view)
      mdpopups.show_popup(
        self.view,
        ''.join(popup),
        css=STYLE,
        on_navigate=self.on_navigate,
        max_width=800,
        max_height=400
      )
Esempio n. 31
0
 def run(self):
     global mdpop_params
     self.view = self.window.active_view()
     mdpopups.erase_phantoms(self.view, 'trans')
     mdpopups.hide_popup(self.view)
    def show_popup(self, menu):
        """Show config popup."""

        settings = sublime.load_settings('Preferences.sublime-settings')
        popup = []
        if menu != 'Main':
            popup = [BACK]

        if menu == 'Main':
            popup.append(SECTIONS_LABEL)
            for k in ['Theme', 'Color Scheme'] + list(OPTIONS.keys()):
                popup.append(SECTIONS % {"section": k})
        elif menu == 'Theme':
            theme = settings.get('theme', '')
            mt_themes = [
                os.path.basename(bt) for bt in sorted(
                    sublime.find_resources('Material-Theme*.sublime-theme'))
                if is_mt_res(bt)
            ]
            popup.append(THEME_LABEL)
            for option in mt_themes:
                option_value = theme == option
                popup.append(
                    THEME % {
                        "name": option,
                        "status":
                        RADIO_MARKED if option_value else RADIO_UNMARKED,
                        "set": option,
                        "class": '.success' if option_value else '.error',
                        'section': "Theme"
                    })
            if theme is not None and theme not in mt_themes:
                popup.append(
                    OTHER_THEME % {
                        "name": theme,
                        "status": RADIO_MARKED,
                        "set": option,
                        "class": '.success' if option_value else '.error',
                        'section': "Theme"
                    })
        elif menu == 'Color Scheme':
            scheme = settings.get('color_scheme', '')
            mt_schemes = [
                bs for bs in sorted(
                    sublime.find_resources('Material-Theme*.tmTheme'))
                if is_mt_res(bs)
            ]
            popup.append(SCHEME_LABEL)
            for option in mt_schemes:
                option_value = scheme == option
                scheme_name = option[32:].replace('/', ' ⚠️ ')
                popup.append(
                    SCHEME % {
                        "name": scheme_name,
                        "status":
                        RADIO_MARKED if option_value else RADIO_UNMARKED,
                        "set": option,
                        "class": '.success' if option_value else '.error',
                        "section": 'Color Scheme'
                    })
            if scheme is not None and scheme not in mt_schemes:
                popup.append(
                    OTHER_SCHEME % {
                        "name": scheme,
                        "status": RADIO_MARKED,
                        "set": option,
                        "class": '.success',
                        "section": 'Color Scheme'
                    })
        else:
            popup.append(SECTION_LABEL % menu)
            for option in OPTIONS[menu]:
                option_value = bool(settings.get(option, False))
                popup.append(
                    GENERAL_SETTING % {
                        "name": option,
                        "status": MARKED if option_value else UNMARKED,
                        "set": str(not option_value),
                        "class": '.success' if option_value else '.error',
                        "section": menu
                    })

        mdpopups.hide_popup(self.view)
        mdpopups.show_popup(self.view,
                            ''.join(popup),
                            css=css,
                            on_navigate=self.on_navigate,
                            max_width=800,
                            max_height=400)
Esempio n. 33
0
 def on_hide(self, view):
     mdpopups.hide_popup(view)
    def on_hover(self, view, point, hover_zone):

        if view.settings().get('is_widget'):
            return

        if not view.settings().get('show_definitions'):
            return

        if hover_zone != sublime.HOVER_TEXT:
            return

        if not view.score_selector(point, 'source.lsl'):
            return

        word = view.substr(view.word(point))

        if not word:
            return

        if not KWDB:
            return

        try:
            tooltipRows = []
            for result in KWDB.findall(".//*[@name='" + word + "']"):
                if result.tag == 'param':
                    continue
                if result.tag == 'function' or result.tag == 'constant':
                    tooltipRows.append('### (%s) <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>' % (result.get('type', 'void'), result.get('name'), result.get('name')))
                else:
                    tooltipRows.append('### <a href="https://wiki.secondlife.com/w/index.php?title=Special:Search&go=Go&search=%s">%s</a>' % (result.get('name'), result.get('name')))
                if result.tag == 'constant':
                    tooltipRows.append(' ')
                    tooltipRows.append('**Value**: %s' % str(result.get('value')))
                if result.get('status', None) is not None and result.get('status', 'normal') != 'normal':
                    tooltipRows.append(' ')
                    tooltipRows.append('<body class="danger">**Status**: %s</body>' % result.get('status', 'normal'))
                if result.get('delay', None) is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('**Delay**: %s' % str(result.get('delay')))
                if result.get('energy', None) is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('**Energy**: %s' % str(result.get('energy')))
                if result.tag == 'function' or result.tag == 'event':
                    if result.findall('./param') != []:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Parameters')
                        for param in result.iter('param'):
                            tooltipRows.append('* (%s) **%s**' % (param.get('type'), param.get('name')))
                if result.find('description').text is not None:
                    tooltipRows.append(' ')
                    tooltipRows.append('#### Description')
                    tooltipRows.append(' ')
                    tooltipRows.append('%s' % result.find('description').text.strip())
#               add version info
#               add grid info by splitting spaces and re-joining as markdown list
#          seperate entries by horizontal line

            if 0 < len(tooltipRows):
                mdpopups.show_popup(view, '\n'.join(tooltipRows),
                    flags=sublime.COOPERATE_WITH_AUTO_COMPLETE|sublime.HIDE_ON_MOUSE_MOVE_AWAY,
                    location=point, max_width=1024,
                    on_navigate=self.on_navigate
                )
                return

        except Exception as e:
            print(e)

        mdpopups.hide_popup(view)
Esempio n. 35
0
    def on_hover(self, view, point, hover_zone):

        if view.settings().get('is_widget'):
            return

        if not view.settings().get('show_definitions'):
            return

        if hover_zone != sublime.HOVER_TEXT:
            return

        if not view.score_selector(point, 'source.lsl'):
            return

        word = view.substr(view.word(point))

        if not word:
            return

        if TOOLTIP_DATA is None:
            return

        try:
            tooltipRows = []
            for result in TOOLTIP_DATA:
                if result.get('name', None) == word:
                    if 'type' in result or result['name'].startswith('ll'):
                        tooltipRows.append(
                            '### (%s) <a href="%s%s">%s</a>' %
                            (result.get('type', 'void'), SL_WIKI,
                             result['name'], result['name']))
                    else:
                        tooltipRows.append(
                            '### <a href="%s%s">%s</a>' %
                            (SL_WIKI, result['name'], result['name']))
                    tooltipRows.append(' ')
                    if 'value' in result:
                        tooltipRows.append('* Value: %s' %
                                           str(result['value']))
                    if 'version' in result:
                        tooltipRows.append('* SL server version: %s' %
                                           result['version'])
                    if 'status' in result:
                        tooltipRows.append(
                            '* <div class="danger">Status: %s</div>' %
                            result['status'])
                    if 'delay' in result:
                        tooltipRows.append('* Delay: %s' %
                                           str(result['delay']))
                    if 'energy' in result:
                        tooltipRows.append('* Energy: %s' %
                                           str(result['energy']))
                    if 'param' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Parameters')
                        tooltipRows.append(' ')
                        if type(result['param']) is dict:
                            tooltipRows.append(
                                '* <a href="%s%s">%s</a> %s' %
                                (SL_WIKI, result['param']['type'],
                                 result['param']['type'],
                                 result['param']['name']))
                        elif type(result['param']) is list:
                            for param in result['param']:
                                tooltipRows.append(
                                    '* <a href="%s%s">%s</a> %s' %
                                    (SL_WIKI, param['type'], param['type'],
                                     param['name']))
                    if 'description' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('#### Description')
                        tooltipRows.append(' ')
                        tooltipRows.append('%s' %
                                           result['description']['en_US'])
                    if 'related' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('---')
                        tooltipRows.append(' ')
                        tooltipRows.append('> ' + ', '.join(
                            str('<a href="%s%s">%s</a>' %
                                (SL_WIKI, related, related))
                            for related in result['related']))
                        tooltipRows.append(' ')
                    if 'usage' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('---')
                        for usage_example in result['usage']:
                            tooltipRows.append(' ')
                            tooltipRows.append('```lsl')
                            tooltipRows.append('%s' % usage_example)
                            tooltipRows.append('```')
                        tooltipRows.append(' ')
                    if 'snippets' in result:
                        tooltipRows.append(' ')
                        tooltipRows.append('---')
                        for snippet in result['snippets']:
                            tooltipRows.append(' ')
                            tooltipRows.append('```lsl')
                            tooltipRows.append('%s' % snippet)
                            tooltipRows.append('```')
                        tooltipRows.append(' ')
            if 0 < len(tooltipRows):
                frontmatter = mdpopups.format_frontmatter(
                    {'allow_code_wrap': True})
                mdpopups.show_popup(view,
                                    frontmatter + '\n'.join(tooltipRows),
                                    flags=(sublime.COOPERATE_WITH_AUTO_COMPLETE
                                           | sublime.HIDE_ON_MOUSE_MOVE_AWAY),
                                    location=point,
                                    wrapper_class='lsl',
                                    max_width=640,
                                    max_height=480,
                                    on_navigate=self.on_navigate,
                                    on_hide=self.on_hide(view))
                return
            # mdpopups.color_box for vectors? or mdpopups.tint with placeholder img?
        except Exception as e:
            print(e)

        mdpopups.hide_popup(view)