Exemplo n.º 1
0
		ret = []
		denom = int(steps)
		numer = int(denom * cpu_percent / 100)
		#numer = int(denom * cpu_percent / (100 * self.cpu_num))
		#self.warn('{0}, {1}, {2}'.format(denom, cpu_percent, numer))
		ret.append({
			'contents': cpu_glyph + ' ',
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 99,
			})
		ret.append({
			'contents': circle_glyph * numer,
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 99,
			})
		ret.append({
			'contents': circle_glyph * (denom - numer),
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 1,
			})

		return ret

cpu_load = with_docstring(CPULoad(), '')
Exemplo n.º 2
0
            'highlight_groups': ['stash'],
            'divider_highlight_group': self.divider_highlight_group
        }
        
        return [res]


# Add docstring:
branch = with_docstring(BranchSegment(),
"""Return the current VCS branch.

:param bool status_colors:
    Determines whether repository status will be used to determine highlighting. 
    Default: False.
:param bool ignore_statuses:
    List of statuses which will not result in repo being marked as dirty. Most 
    useful is setting this option to '["U"]': this will ignore repository 
    which has just untracked files (i.e. repository with modified, deleted or 
    removed files will be marked as dirty, while just untracked files will make 
    segment show clean repository). Only applicable if 'status_colors' option 
    is True.

Highlight groups used: 'branch_clean', 'branch_dirty', 'branch'.
""")

stash = with_docstring(StashSegment(),
"""Return the number of current VCS stash entries, if any.

Highlight groups used: 'stash'.
""")
Exemplo n.º 3
0
weather = with_docstring(
    WeatherSegment(),
    """Return weather from Yahoo! Weather.

Uses GeoIP lookup from http://freegeoip.net/ to automatically determine
your current location. This should be changed if you’re in a VPN or if your
IP address is registered at another location.

Returns a list of colorized icon and temperature segments depending on
weather conditions.

:param str unit:
	temperature unit, can be one of ``F``, ``C`` or ``K``
:param str location_query:
	location query for your current location, e.g. ``oslo, norway``
:param dict icons:
	dict for overriding default icons, e.g. ``{'heavy_snow' : u'❆'}``
:param str temp_format:
	format string, receives ``temp`` as an argument. Should also hold unit.
:param float temp_coldest:
	coldest temperature. Any temperature below it will have gradient level equal
	to zero.
:param float temp_hottest:
	hottest temperature. Any temperature above it will have gradient level equal
	to 100. Temperatures between ``temp_coldest`` and ``temp_hottest`` receive
	gradient level that indicates relative position in this interval
	(``100 * (cur-coldest) / (hottest-coldest)``).

Divider highlight group used: ``background:divider``.

Highlight groups used: ``weather_conditions`` or ``weather``, ``weather_temp_gradient`` (gradient) or ``weather``.
Also uses ``weather_conditions_{condition}`` for all weather conditions supported by Yahoo.
""",
)
Exemplo n.º 4
0
    retVal = "🚧"
    if not len(changes):
        retVal = None
    return (retVal)


@requires_filesystem_watcher
@requires_segment_info
class CustomSegment(Segment):
    divider_highlight_group = None

    def __call__(self, pl, segment_info, create_watcher):
        value = callgitcheck()
        if not value:  # do not display if everything is committed in git
            return None

        return [{
            #highlight_groups can be found in ~/.config/powerline/colorschemes/default.json
            #'highlight_groups': ['critical:failure'],
            #'highlight_groups': ['warning:regular'],
            'highlight_groups': ['player'],
            'draw_soft_divider': True,
            'draw_hard_divider': True,
            'draw_inner_divider': False,
            #'divider_highlight_group': 'cwd:divider',
            'contents': value,
        }]


gitcheck = with_docstring(CustomSegment(), '''Return a custom segment.''')
Exemplo n.º 5
0
weather = with_docstring(
    WeatherSegment(), '''Return weather from Yahoo! Weather.

Uses GeoIP lookup from http://freegeoip.net/ to automatically determine
your current location. This should be changed if you’re in a VPN or if your
IP address is registered at another location.

Returns a list of colorized icon and temperature segments depending on
weather conditions.

:param str unit:
	temperature unit, can be one of ``F``, ``C`` or ``K``
:param str location_query:
	location query for your current location, e.g. ``oslo, norway``
:param dict icons:
	dict for overriding default icons, e.g. ``{'heavy_snow' : u'❆'}``
:param str temp_format:
	format string, receives ``temp`` as an argument. Should also hold unit.
:param float temp_coldest:
	coldest temperature. Any temperature below it will have gradient level equal
	to zero.
:param float temp_hottest:
	hottest temperature. Any temperature above it will have gradient level equal
	to 100. Temperatures between ``temp_coldest`` and ``temp_hottest`` receive
	gradient level that indicates relative position in this interval
	(``100 * (cur-coldest) / (hottest-coldest)``).

Divider highlight group used: ``background:divider``.

Highlight groups used: ``weather_conditions`` or ``weather``, ``weather_temp_gradient`` (gradient) or ``weather``.
Also uses ``weather_conditions_{condition}`` for all weather conditions supported by Yahoo.
''')
Exemplo n.º 6
0
                else
                        return "stopped"
                end if
        '''.format(status_delimiter)

        spotify = asrun(pl, ascript)
        if not asrun:
            return None

        spotify_status = spotify.split(status_delimiter)
        state = _convert_state(spotify_status[0])
        if state == 'stop':
            return None
        return {
                'state': state,
                'album': spotify_status[1],
                'artist': spotify_status[2],
                'title': spotify_status[3],
                'total': _convert_seconds(float(spotify_status[4])/1000),
                'elapsed': _convert_seconds(float(spotify_status[5])),
                }


spotify = with_docstring(SpotifyAppleScriptPlayerSegment(),
    ('''Return spotify player information

        Requires ``osascript`` available in $PATH.

        {0}
    ''').format(_common_args.format('spotify_apple_script')))
Exemplo n.º 7
0
        except OSError as e:
            if e.errno == 2:
                pass
            else:
                raise


    def __call__(self, pl, segment_info, cake_core_include_path='lib'):

        return self.version(cake_core_include_path)

cakephp = with_docstring(CakePHPSegment(),
'''Return the status of a Git working copy.

It will show the branch-name, or the commit hash if in detached head state.

It will also show the number of commits behind, commits ahead, staged files,
unmerged files (conflicts), changed files, untracked files and stashed files
if that number is greater than zero.

:param bool use_dash_c:
    Call git with ``-C``, which is more performant and accurate, but requires git 1.8.5 or higher.
    Otherwise it will traverse the current working directory up towards the root until it finds a ``.git`` directory, then use ``--git-dir`` and ``--work-tree``.
    True by default.

Divider highlight group used: ``gitstatus:divider``.

Highlight groups used: ``gitstatus_branch_detached``, ``gitstatus_branch_dirty``, ``gitstatus_branch_clean``, ``gitstatus_branch``, ``gitstatus_behind``, ``gitstatus_ahead``, ``gitstatus_staged``, ``gitstatus_unmerged``, ``gitstatus_changed``, ``gitstatus_untracked``, ``gitstatus_stashed``, ``gitstatus``.
''')
Exemplo n.º 8
0
        return self.build_segments(statuses)


docker = with_docstring(DockerSegment(),
                        '''Return the status of Docker containers.

It will show the number of Docker containers running and exited.
It requires Docker and docker-py to be installed.

:param str base_url:
    base URL including protocol where your Docker daemon lives (e.g. ``tcp://192.168.99.109:2376``).
    Defaults to ``unix://var/run/docker.sock``, which is where it lives on most Unix systems.
:param list ignore_statuses:
    list of statuses which will be ignored and not printed out (e.g. ``["exited", "paused"]``).
:param bool use_tls:
    if True, it will enable TLS communication with the Docker daemon. Defaults to False.
:param str ca_cert:
    path to CA cert file (e.g. ``/home/user/.docker/machine/machines/default/ca.pem``)
:param str client_cert:
    path to client cert (e.g. ``/home/user/.docker/machine/machines/default/cert.pem``)
:param str client_key:
    path to client key (e.g. ``/home/user/.docker/machine/machines/default/key.pem``)


Divider highlight group used: ``docker:divider``.

Highlight groups used: ``docker_running``, ``docker_paused``, ``docker_exited``, ``docker_restarting``, ``docker``.
''')

def add_docker_segment(powerline):    
    list_dict_segments = docker(None)
Exemplo n.º 9
0
        if not err and report and not ret_code:
            full_begin_date = datetime.strptime([
                st for st in report[1].split(" ") if st
            ][1], "%Y-%m-%dT%H:%M:%S")
            if full_begin_date:
                return [{
                    'contents': full_begin_date.strftime(format),
                    'highlight_groups': ['timewarrior:total_time'],
                }]
        return []


current_track = with_docstring(
    CurrentTrackSegment(), '''Return information from Timewarrior time tracker.

    It shows the current tracked task

    Highlight groups used: ``timewarrior:current_track``
    ''')

total_time = with_docstring(
    TotalWorkingTimeSegment(),
    '''Return information from Timewarrior time tracker.

    It shows the total elapsed time on the current tracked task.

    Highlight groups used: ``timewarrior:total_time``
    ''')

begin_time = with_docstring(
    BeginWorkingTimeSegment(),
Exemplo n.º 10
0
                    end if
                end tell
            end if
        '''.format(status_delimiter)
        now_playing = asrun(pl, ascript)
        if not now_playing:
            return
        now_playing = now_playing.split(status_delimiter)
        if len(now_playing) != 6:
            return
        title, artist, album = now_playing[0], now_playing[1], now_playing[2]
        state = _convert_state(now_playing[5])
        total = _convert_seconds(now_playing[4])
        elapsed = _convert_seconds(float(now_playing[4]) - float(now_playing[4]))
        return {
            'title': title,
            'artist': artist,
            'album': album,
            'total': total,
            'elapsed': elapsed,
            'state': state
        }

itunes = with_docstring(iTunesPlayerSegment(),
    ('''Return iTunes now playing information.

        Requires ``osascript``.

        {0}
    ''').format(_common_args.format('itunes')))
Exemplo n.º 11
0
				'highlight_groups': ['email_alert'],
			}]
		else:
			return [{
				'contents': str(unread_count),
				'highlight_groups': ['email_alert_gradient', 'email_alert'],
				'gradient_level': min(unread_count * 100.0 / max_msgs, 100),
			}]


email_imap_alert = with_docstring(EmailIMAPSegment(),
'''Return unread e-mail count for IMAP servers.

:param str username:
	login username
:param str password:
	login password
:param str server:
	e-mail server
:param int port:
	e-mail server port
:param str folder:
	folder to check for e-mails
:param int max_msgs:
	Maximum number of messages. If there are more messages then max_msgs then it
	will use gradient level equal to 100, otherwise gradient level is equal to
	``100 * msgs_num / max_msgs``. If not present gradient is not computed.

Highlight groups used: ``email_alert_gradient`` (gradient), ``email_alert``.
''')
Exemplo n.º 12
0
            'contents': '%s,%s' % amixer_stats,
            'highlight_group': ['cpu_load_percent']
        }]

    def get_amixer_stats(self, device, pl):
        amixer_output = run_cmd(pl, ['amixer', '-M', 'get', '-D', 'pulse', device])
        for line in amixer_output.split("\n"):
            cleaned_line = line.strip()
            if cleaned_line.startswith("Front Left"):
                match = VOLUME_PATTERN.search(cleaned_line)
                if match is not None:
                    left = match.group(1)
            elif cleaned_line.startswith("Front Right"):
                match = VOLUME_PATTERN.search(cleaned_line)
                if match is not None:
                    right = match.group(1)

        return (left, right)

    def argspecobjs(self):
        for ret in super(VolumeSegment, self).argspecobjs():
            yield ret
        yield 'get_amixer_stats', self.get_amixer_stats

    def omitted_args(self, name, method):
        return (0,)


volume = with_docstring(VolumeSegment(),
                        '''Volume segment using amixer''')
Exemplo n.º 13
0
    def get_player_status(self, pl):
        """
        Returns MOC player information.

        mocp -i returns data with multi level information i.e.
            State: PAUSE
            File: <file_name>
            Title: <full_title>
            Artist: <artist_name>
            SongTitle: <track_title>
            ...
        """
        now_playing_str = run_cmd(pl, ['mocp', '-i'])
        if not now_playing_str:
            return

        now_playing = dict((parts[0], parts[1]) for parts in
                           [line.split(": ") for line in now_playing_str.split("\n")])
        state = _convert_state(now_playing.get("State"))
        return {
            'state': state,
            'album': now_playing.get('Album', ''),
            'artist': now_playing.get('Artist', ''),
            'title': now_playing.get('SongTitle', ''),
            'elapsed': _convert_seconds(int(now_playing.get('CurrentSec', 0))),
            'total': _convert_seconds(int(now_playing.get('TotalSec', 0)))
        }

moc = with_docstring(MocPlayerSegment(),
                     '''Return Music On Console information''')
Exemplo n.º 14
0
    def set_state(self, exchange="bitstamp", **kwargs):
        self.exchange = exchange
        super(BTCSegment, self).set_state(**kwargs)

    def update(self, oldprice):
        price = None
        if self.exchange == "bitstamp":
            ticker = requests.get("https://www.bitstamp.net/api/ticker/").json()
            price = "$%s" % ticker['last']
        if price is not None:
            return price
        else:
            return "Unknown exchange \"%s\"" % self.exchange

    def render(self, price, **kwargs):
        return [{
            "contents": str(price),
            "hightlight_group": ["btc"]
            }]

btc = with_docstring(BTCSegment(),
"""Returns the current price of Bitcoin at the specified exchage
:param str exchange:
    The name of the exchange. Currently supported:

    * bitstamp (supported currencies: USD)

highlight groups: ``btc``
    """)
Exemplo n.º 15
0
            'highlight_groups': ['xcode_version', 'xcode_build'],
            'divider_highlight_group': 'xcode_version:divider',
        }]

    def marketing_version(self, pl):
        command = ( "plutil -p $(xcode-select -p)/../version.plist"
                    " | grep -e CFBundleShortVersionString"
                    " | sed 's/[^0-9\.]*//g'"
                    )
        pl.debug("command: " + command)
        output = self.execute(pl, command)

        return output

    # command is a string array
    def execute(self, pl, command):
        pl.debug('Executing command: %s' % ' '.join(command))

        try:
            output = check_output(command, shell=True).decode('utf-8').rstrip()
            pl.debug("output: " + output)
        except CalledProcessError as e:
            pl.error("ERROR " + e.returncode + ": " + e.output)
            return

        return output

xcodeversion = with_docstring(XcodeVersionSegment(),
'''Returns the currently selected Xcode version.
''')
Exemplo n.º 16
0
		ret = []
		denom = int(steps)
		numer = int(denom * cpu_percent / 100)
		#numer = int(denom * cpu_percent / (100 * self.cpu_num))
		#self.warn('{0}, {1}, {2}'.format(denom, cpu_percent, numer))
		ret.append({
			'contents': cpu_glyph + ' ',
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 99,
			})
		ret.append({
			'contents': circle_glyph * numer,
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 99,
			})
		ret.append({
			'contents': circle_glyph * (denom - numer),
			'draw_soft_divider': False,
			'divider_highlight_group': 'background:divider',
			'highlight_group': ['cpu_load'],
			'gradient_level': 1,
			})

		return ret

cpu_load = with_docstring(CPULoad(), '')
Exemplo n.º 17
0
            branch = self.execute(pl, base +
                                  ['rev-parse', '--short', 'HEAD'])[0][0]

        staged, unmerged, changed, untracked = self.parse_status(status)

        stashed = len(
            self.execute(pl, base + ['stash', 'list', '--no-decorate'])[0])

        return self.build_segments(branch, detached, behind, ahead, staged,
                                   unmerged, changed, untracked, stashed)


gitstatus = with_docstring(
    GitStatusSegment(), '''Return the status of a Git working copy.

It will show the branch-name, or the commit hash if in detached head state.

It will also show the number of commits behind, commits ahead, staged files,
unmerged files (conflicts), changed files, untracked files and stashed files
if that number is greater than zero.

:param bool use_dash_c:
    Call git with ``-C``, which is more performant and accurate, but requires git 1.8.5 or higher.
    Otherwise it will traverse the current working directory up towards the root until it finds a ``.git`` directory, then use ``--git-dir`` and ``--work-tree``.
    True by default.

Divider highlight group used: ``gitstatus:divider``.

Highlight groups used: ``gitstatus_branch_detached``, ``gitstatus_branch_dirty``, ``gitstatus_branch_clean``, ``gitstatus_branch``, ``gitstatus_behind``, ``gitstatus_ahead``, ``gitstatus_staged``, ``gitstatus_unmerged``, ``gitstatus_changed``, ``gitstatus_untracked``, ``gitstatus_stashed``, ``gitstatus``.
''')
Exemplo n.º 18
0
				ret[0]['contents'] = ret[0]['contents'][1:]
		return ret


cwd = with_docstring(CwdSegment(),
'''Return the current working directory.

Returns a segment list to create a breadcrumb-like effect.

:param int dir_shorten_len:
	shorten parent directory names to this length (e.g. 
	:file:`/long/path/to/powerline` → :file:`/l/p/t/powerline`)
:param int dir_limit_depth:
	limit directory depth to this number (e.g. 
	:file:`/long/path/to/powerline` → :file:`⋯/to/powerline`)
:param bool use_path_separator:
	Use path separator in place of soft divider.
:param bool shorten_home:
	Shorten home directory to ``~``.
:param str ellipsis:
	Specifies what to use in place of omitted directories. Use None to not 
	show this subsegment at all.

Divider highlight group used: ``cwd:divider``.

Highlight groups used: ``cwd:current_folder`` or ``cwd``. It is recommended to define all highlight groups.
''')


def date(pl, format='%Y-%m-%d', istime=False):
	'''Return the current date.
Exemplo n.º 19
0
                     self.prev_counters[disk].write_bytes) /
                    (cur_time - self.prev_time))
        self.prev_counters = counters
        self.prev_time = cur_time
        return data

    def render_one(self,
                   data,
                   format="{read_speed:>7} {write_speed:>7}",
                   **kwargs):
        if data is None or "read_speed" not in data or "write_speed" not in data:
            return None
        return [{
            "contents": format.format(**data),
            "highlight_groups": ["traffic"]
        }]


traffic = with_docstring(
    TrafficSegment(), ''' Get hdd traffic

:param disk: partition to measure traffic
:param format: use {read_speed} and {write_speed}
''')

# TODO: implement as segment class
# util_per_partition[partition].read_bytes/write_bytes
#def traffic(pl, partition="sdb2", format="{0:1.f}"):
#    util_per_partition = disk_io_counters(True)
#    if partition not in util_per_partition:
Exemplo n.º 20
0
@requires_segment_info
class TempSegment(Segment):

    divider_highlight_group = None

    def __call__(self, pl, segment_info, create_watcher):
        temp_output = subprocess.run(
            ['~/.tmux/plugins/tmux-cpu/scripts/cpu_temp.sh'],
            stdout=PIPE,
            stderr=STDOUT,
            check=True)
        cpu_temp = _canonical_temp(temp_output.stdout)
        return [{
            'contents': f'CPU: {cpu_temp}',
            'highlight_groups': ['information:regular'],
        }]


def _canonical_temp(temperature):
    """return canonical temperature.

    :temperature: temperature in bytes from  external utility
    :returns: TODO

    """
    return temperature.decode('utf-8')


holistic = with_docstring(TempSegment(),
                          '''Return a tmux temperature segment.''')
Exemplo n.º 21
0
	+------------+-------------------------------------------------------------+
:param dict state_symbols:
	Symbols used for displaying state. Must contain all of the following keys:

	========  ========================================================
	Key       Description
	========  ========================================================
	play      Displayed when player is playing.
	pause     Displayed when player is paused.
	stop      Displayed when player is not playing anything.
	fallback  Displayed if state is not one of the above or not known.
	========  ========================================================
'''


_player = with_docstring(PlayerSegment(), _common_args.format('_player'))


class CmusPlayerSegment(PlayerSegment):
	def get_player_status(self, pl):
		'''Return cmus player information.

		cmus-remote -Q returns data with multi-level information i.e.
			status playing
			file <file_name>
			tag artist <artist_name>
			tag title <track_title>
			tag ..
			tag n
			set continue <true|false>
			set repeat <true|false>
Exemplo n.º 22
0
        # if `svn status` returned dirty results, display the branch as dirty
        if self.is_dirty(counts):
            segments[0]['highlight_groups'] = [
                'svnstatus_dirty', 'branch_dirty', 'svnstatus', 'branch'
            ]

        # add the count of each status type as a separate segment
        return segments + [
            self.build_status_segment(x) for x in counts.items()
        ]


svnstatus = with_docstring(
    SvnStatusSegment(),
    '''Return the status of the Subversion working directory.

Returns a segment showing the branch/tag name of the working directory,
and additional segments for each type of modification
(ie A for Addded, C for Conflicted, D for Deleted, etc)
with the count of files which have that modification type.

:param str branch_re:
    Regex to use to convert URL from `svn info` into short branch name.
    The capturing groups of the regex are concatonated together
    to create the branch name. The default regex is this:
    '/(trunk)(?:/|$)|/(?:tags|branch(?:es)?)/([^/]+)'.

Highlight groups used: ``svnstatus_clean``, ``svnstatus_dirty``, ``svnstatus_unknown``, ``svnstatus``. Also will use per-modification-type groups if available, such as ``svnstatus_A``, ``svnstatus_C``, ``svnstatus_D``, etc.
''')
Exemplo n.º 23
0
						pl.exception('Failed to compute tree status: {0}', str(e))
						status = '?'
					else:
						status = status and status.strip()
						if status in ignore_statuses:
							status = None
					scol.insert(0, 'branch_dirty' if status else 'branch_clean')
				return [{
					'contents': branch,
					'highlight_groups': scol,
					'divider_highlight_group': self.divider_highlight_group,
				}]


branch = with_docstring(BranchSegment(),
'''Return the current VCS branch.

:param bool status_colors:
	Determines whether repository status will be used to determine highlighting. 
	Default: False.
:param bool ignore_statuses:
	List of statuses which will not result in repo being marked as dirty. Most 
	useful is setting this option to ``["U"]``: this will ignore repository 
	which has just untracked files (i.e. repository with modified, deleted or 
	removed files will be marked as dirty, while just untracked files will make 
	segment show clean repository). Only applicable if ``status_colors`` option 
	is True.

Highlight groups used: ``branch_clean``, ``branch_dirty``, ``branch``.
''')
Exemplo n.º 24
0
        @staticmethod
        def render(cpu_percent, pl, format='{0:.0f}%', threshold=None**kwargs):
            pl.warn(
                'Module “psutil” is not installed, thus CPU load is not available'
            )
            return None


cpu_load_percent = with_docstring(
    CPULoadPercentSegment(), '''Return the average CPU load as a percentage.

Requires the ``psutil`` module.

:param str format:
    Output format. Accepts measured CPU load as the first argument.
:param int threshold:
    Minimum load to display the segment (in percent)

Highlight groups used: ``cpu_load_percent_gradient`` (gradient) or ``cpu_load_percent``.

Click values supplied: ``cpu_load`` (string), ``cpu_load_raw`` (int)
''')


@requires_segment_info
def memory_usage(pl,
                 segment_info,
                 format='{percent:.1f}% {absolute:.1f}G/{total:.1f}G',
                 threshold_good=20,
                 threshold_bad=80,
                 short_format='{percent:.1f}%',
Exemplo n.º 25
0
        segments = [
            {'contents': u'\U00002388 ', 'highlight_groups': ['kubernetes'], 'divider_highlight_group': 'kubernetes:divider'},
            {'contents': '%s - %s' % (context, namespace), 'highlight_groups': ['kubernetes'], 'divider_highlight_group': 'kubernetes:divider'},
        ]
	return segments

    def __call__(self, pl):
        pl.debug('Running powerline-kubernetes')

        self.pl = pl

	try:
            context = K8sConfig().current_context
	    namespace = K8sConfig().namespace
        except Exception as e:
            pl.error(e)
            return

        return self.build_segments(context,namespace)

kubernetes = with_docstring(KubernetesSegment(),
'''Return the current context.

It will show the current context in config.
It requires kubectl and kubernetes-py to be installed.

Divider highlight group used: ``kubernetes:divider``.

Highlight groups used: ``kubernetes``.
''')
Exemplo n.º 26
0
    def __call__(self, pl, base_url='unix://var/run/docker.sock'):
        self.pl = pl

        pl.debug('Running powerline-docker')

        self.cli = Client(base_url=base_url)

        try:
            running, paused, exited, restarting = self.get_container_statuses()
        except ConnectionError:
            pl.error('Cannot connect to Docker server on \'%s\'' % (base_url,))
            return
        except Exception as e:
            pl.error(e)
            return

        return self.build_segments(running, paused, exited, restarting)


docker = with_docstring(DockerSegment(),
'''Return the status of Docker containers.

It will show the number of Docker containers running and exited.
It requires Docker and docker-py to be installed.

Divider highlight group used: ``docker:divider``.

Highlight groups used: ``docker_running``, ``docker_exited``, ``docker``.
''')
Exemplo n.º 27
0
network_manager = with_docstring(
    NetworkManagerSegment(),
    '''Return what NetworkManager knows about the current connection. Requires ``nmcli``

    :param string name:
        the name of the segment, defaults to ``status``.
        Setting this value changes the highlight groups used.

        ========  =================================================================================
        Name      Highlight Groups Used
        ========  =================================================================================
        status    ``net:status``
        wifi      ``wireless:quality``, `net:wifi` or ``wireless:down``, ``net:wifi``
        ethernet  ``ethernet:up``, ``ethernet:down``
        ========  =================================================================================
    :param string device:
        the device to use. Per default this segment will list data for all active devices.
    :param string format:
        the output format
    :param string short_format:
        optional shorter format when the powerline needs to shrink segments
    :param string format_down:
        if set to any other value than ``None``, it will be shown when no connection is present
        on the specified device
    :param bool auto_shrink:
        if set to true, this segment will use ``short_format`` per default,
        only using ``format`` when any message is present on the ``net.nm_<name>``
        message channel.
    :param list device_types:
        filter for the given device types. May include ``wifi``, ``ethernet``, ``gsm``, ``lo``, etc
        Consult ``man nmcli`` for a comprehensive list.

    Highlight groups used: ``ethernet:up`` or ``net:ethernet``, ``ethernet:down`` or ``net:ethernet``, ``wireless:quality`` (gradient) or ``net:wifi``, ``wireless:down`` or ``net:wifi``, ``net:status``

    Click values supplied: (any value available in format)
''')
Exemplo n.º 28
0
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import os

from powerline.segments import Segment, with_docstring
from powerline.theme import requires_segment_info, requires_filesystem_watcher
from powerline.segments.shell import ShellCwdSegment


@requires_segment_info
class Rainbow(ShellCwdSegment):
    def __call__(self, pl, segment_info, **kwargs):
        seg = super(Rainbow, self).__call__(pl, segment_info, **kwargs)
        val = 0
        for item in seg:
            if (val > 100):
                val = 0
            item['gradient_level'] = val
            item['highlight_groups'] = ['cascading_rainbow']
            val += 5
        return seg


rainbow_segment = with_docstring(Rainbow(), 'hi')
Exemplo n.º 29
0
            ret.append({
                'contents': part,
                'highlight_groups': ['cwd'],
                'divider_highlight_group': 'cwd:divider',
                'draw_inner_divider': draw_inner_divider,
            })
        ret[-1]['highlight_groups'] = ['cwd:current_folder', 'cwd']

        if use_path_separator:
            ret[-1]['contents'] = ret[-1]['contents'][:-1]
            if len(ret) > 1 and ret[0]['contents'][0] == os.sep:
                ret[0]['contents'] = ret[0]['contents'][1:]
        return ret


gitpath = with_docstring(GitPathSegment(), '''Return a custom segment.''')


@requires_filesystem_watcher
@requires_segment_info
class GitNameSegment(Segment):
    def __call__(self, pl, segment_info, **kwargs):
        repo = Repo(segment_info['getcwd'](), search_parent_directories=True)
        reponame = os.path.basename(repo.working_dir)

        return [{
            'contents': reponame,
            'highlight_groups': ['information:regular'],
        }]

Exemplo n.º 30
0
            'rc.report.next.labels:1,2', 'limit:1', 'next'
        ]


class TaskwarriorSegment(TaskwarriorBaseSegment):
    def build_segments(self):
        self.pl.debug('Build ActiveTask + Context segment')
        return ActiveTaskSegment()(
            self.pl, self.task_alias) + ContextSegment()(self.pl,
                                                         self.task_alias)


taskwarrior = with_docstring(
    TaskwarriorSegment(), '''Return information from Taskwarrior task manager.

    It will show current context and active task (first by urgency order).

    Highlight groups used: ``taskwarrior:active_id``, ``taskwarrior:active_desc``, ``taskwarrior:context``
    ''')

context = with_docstring(
    ContextSegment(), '''Return information from Taskwarrior task manager.

    It will show current context.

    Highlight groups used: ``information:regular``
    ''')

active_task = with_docstring(
    ActiveTaskSegment(), '''Return information from Taskwarrior task manager.
Exemplo n.º 31
0
		@staticmethod
		def shutdown():
			pass

		@staticmethod
		def render(cpu_percent, pl, format='{0:.0f}%', **kwargs):
			pl.warn('Module “psutil” is not installed, thus CPU load is not available')
			return None


cpu_load_percent = with_docstring(CPULoadPercentSegment(),
'''Return the average CPU load as a percentage.

Requires the ``psutil`` module.

:param str format:
	Output format. Accepts measured CPU load as the first argument.

Highlight groups used: ``cpu_load_percent_gradient`` (gradient) or ``cpu_load_percent``.
''')


if os.path.exists('/proc/uptime'):
	def _get_uptime():
		with open('/proc/uptime', 'r') as f:
			return int(float(f.readline().split()[0]))
elif 'psutil' in globals():
	from time import time

	if hasattr(psutil, 'boot_time'):
		def _get_uptime():
Exemplo n.º 32
0
                    'click_values': {},
                    'payload_name':
                    channel_name
                }]

    bluetooth = with_docstring(
        BluetoothSegment(),
        ''' Return the connected Bluetooth devices. Requires ``dbus``.

        :param string format:
            Format
        :param string short_format:
            Short format
        :param string format_down:
            Format when no device is connected
        :param string format_battery:
            Format used to display the battery status of the connected device.
        :param boolean ignore_unconnected:
            When listing devices, ignore
        :param boolean auto_shrink:
            if set to true, this segment will use ``short_format`` per default,
            only using ``format`` when any message is present on the ``bluetooth`` message channel.

        Highlight groups used: ``bluetooth`` or ``bluetooth:down``

        Click values supplied: (any value available in format)
    ''')

except ImportError:

    def bluetooth(pl,
                  format='BT {name}',
Exemplo n.º 33
0

class K8sClusterInfo(ThreadedSegment):
    interval = 1

    def _update(self):
        context = config.list_kube_config_contexts()[1]['name']
        return context

    def update(self, old):
        return self._update()

    #def run(self):
    #while not self.shutdown_event.is_set():
    #    self.update_value = self._update()
    #    time.sleep(self.interval)

    def render(self, value, **kwargs):
        if "prod" in value:
            color_name = 'k8s_prod'
        else:
            color_name = 'k8s_nonprod'

        return [{'contents': value, 'highlight_groups': [color_name]}]


k8s_cluster_info = with_docstring(K8sClusterInfo(), '''Return shit.

Nothing to read.
''')
Exemplo n.º 34
0
	+------------+-------------------------------------------------------------+
:param dict state_symbols:
	Symbols used for displaying state. Must contain all of the following keys:

	========  ========================================================
	Key       Description
	========  ========================================================
	play      Displayed when player is playing.
	pause     Displayed when player is paused.
	stop      Displayed when player is not playing anything.
	fallback  Displayed if state is not one of the above or not known.
	========  ========================================================
'''


_player = with_docstring(PlayerSegment(), _common_args.format('_player'))


class CmusPlayerSegment(PlayerSegment):
	def get_player_status(self, pl):
		'''Return cmus player information.

		cmus-remote -Q returns data with multi-level information i.e.
			status playing
			file <file_name>
			tag artist <artist_name>
			tag title <track_title>
			tag ..
			tag n
			set continue <true|false>
			set repeat <true|false>
Exemplo n.º 35
0
                    "divider_highlight_group": "gitstatus:divider",
                }
            )
        if self._untracked:
            segments.append(
                {
                    "contents": "?",
                    "highlight_groups": ["gitstatus_untracked", "gitstatus"],
                    "divider_highlight_group": "gitstatus:divider",
                }
            )
        if self._stashed:
            segments.append(
                {
                    "contents": " ⚑ {0}".format(self._stashed),
                    "highlight_groups": ["gitstatus_stashed", "gitstatus"],
                    "divider_highlight_group": "gitstatus:divider",
                }
            )

        return segments


gitstatus = with_docstring(
    GitStatusSegment(),
    """Return the status of a Git working copy.
Divider highlight group used: ``gitstatus:divider``.
Highlight groups used: ``gitstatus_branch_detached``, ``gitstatus_branch_dirty``, ``gitstatus_branch_clean``, ``gitstatus_branch``, ``gitstatus_behind``, ``gitstatus_ahead``, ``gitstatus_staged``, ``gitstatus_unmerged``, ``gitstatus_changed``, ``gitstatus_untracked``, ``gitstatus_stashed``, ``gitstatus``.
""",
)
Exemplo n.º 36
0
svnstatus = with_docstring(
    SvnStatusSegment(),
    '''Return the status of the Subversion working directory.

Returns a segment showing the branch/tag name of the working directory,
and additional segments for each type of modification
(ie A for Addded, C for Conflicted, D for Deleted, etc)
with the count of files which have that modification type.

:param str branch_format:
    Format string for segment content. One string argument (`%%s`) is
    substituted by the matched groups of below `branch_re`. Defaults to
    a branch symbol followed by that string.

:param str branch_re:
    Regex to use to convert URL from `svn info` into short branch name.
    The capturing groups of the regex are concatenated together
    to create the branch name. The default regex is this:
    '/(trunk)(?:/|$)|/(?:tags|branch(?:es)?)/([^/]+)'.

:param str line_start:
    String that line of interest from `svn info` output should start
    with. The above regular expression is used on this particular line.
    By default, this is 'URL: ', so that the URL of the repository is
    targeted. The line of output minus this prefix is fed to the
    `branch_re` regular expression.

Highlight groups used: ``svnstatus_clean``, ``svnstatus_dirty``, ``svnstatus_unknown``, ``svnstatus``. Also will use per-modification-type groups if available, such as ``svnstatus_A``, ``svnstatus_C``, ``svnstatus_D``, etc.
''')
Exemplo n.º 37
0
				"contents": WEATHER_NAME.get(icon, "Unknown")

			},
			{
				'contents': rest,
				'highlight_groups': groups,
				'divider_highlight_group': 'background:divider',
			},
		]


weather = with_docstring(WeatherSegment(),
'''Return weather from wttr.in.

Uses GeoIP lookup from http://geoip.nekudo.com to automatically determine
your current location. This should be changed if you’re in a VPN or if your
IP address is registered at another location.

Returns a list of colorized icon and temperature segments depending on
weather conditions.

:param str unit:
	temperature unit, can be one of ``F``, ``C`` or ``K``
:param str location_query:
	location query for your current location, e.g. ``oslo, norway``

Divider highlight group used: ``background:divider``.

Highlight groups used: ``weather_conditions`` or ``weather``, ``weather_temp_gradient`` (gradient) or ``weather``.
''')
Exemplo n.º 38
0
        self.show_cluster = show_cluster
        self.show_namespace = show_namespace
        self.show_default_namespace = show_default_namespace
        self.alerts = alerts

        try:
            k8_loader = kube_config.KubeConfigLoader(self.config)
            current_context = k8_loader.current_context
            ctx = current_context['context']
            context = current_context['name']
            namespace = ctx['namespace']
        except Exception as e:
            pl.error(e)
            return

        return self.build_segments(context, namespace)


kubernetes = with_docstring(
    KubernetesSegment(), '''Return the current context.

It will show the current context in config.
It requires kubectl and kubernetes-py to be installed.

Divider highlight group used: ``kubernetes:divider``.

Highlight groups used: ``kubernetes_cluster``,
``kubernetes_cluster:alert``, ``kubernetes_namespace``,
and ``kubernetes_namespace:alert``, .
''')
Exemplo n.º 39
0
                ret[0]['contents'] = ret[0]['contents'][1:]
        return ret


cwd = with_docstring(
    CwdSegment(), '''Return the current working directory.

Returns a segment list to create a breadcrumb-like effect.

:param int dir_shorten_len:
	shorten parent directory names to this length (e.g. 
	:file:`/long/path/to/powerline` → :file:`/l/p/t/powerline`)
:param int dir_limit_depth:
	limit directory depth to this number (e.g. 
	:file:`/long/path/to/powerline` → :file:`⋯/to/powerline`)
:param bool use_path_separator:
	Use path separator in place of soft divider.
:param bool shorten_home:
	Shorten home directory to ``~``.
:param str ellipsis:
	Specifies what to use in place of omitted directories. Use None to not 
	show this subsegment at all.

Divider highlight group used: ``cwd:divider``.

Highlight groups used: ``cwd:current_folder`` or ``cwd``. It is recommended to define all highlight groups.
''')

try:
    import psutil
Exemplo n.º 40
0
vcsinfo = with_docstring(
    VCSInfoSegment(), '''Return the current revision info

:param str name:
	Determines what property should be used. Valid values:

	========  ===================================================
	Name      Description
	========  ===================================================
	branch    Current branch name.
	short     Current commit revision abbreviated hex or revno.
	summary   Current commit summary.
	name      Human-readable name of the current revision.
	bookmark  Current bookmark (mercurial) or branch (otherwise).
	status    Current repository status.
	========  ===================================================
:param bool status_colors:
	Determines whether repository status will be used to determine highlighting.
	Default: False.
:param list ignore_statuses:
	List of statuses which will not result in repo being marked as dirty. Most
	useful is setting this option to ``["U"]``: this will ignore repository
	which has just untracked files (i.e. repository with modified, deleted or
	removed files will be marked as dirty, while just untracked files will make
	segment show clean repository). Only applicable if ``status_colors`` option
    is True.

Highlight groups used: ``vcsinfo:clean``, ``vcsinfo:dirty``, ``vcsinfo``.

Additionally ``vcsinfo:{name}`` is used.
''')
Exemplo n.º 41
0
				pass
		return super(ShellCwdSegment, self).get_shortened_path(pl, segment_info, **kwargs)


cwd = with_docstring(ShellCwdSegment(),
'''Return the current working directory.

Returns a segment list to create a breadcrumb-like effect.

:param int dir_shorten_len:
	shorten parent directory names to this length (e.g. 
	:file:`/long/path/to/powerline` → :file:`/l/p/t/powerline`)
:param int dir_limit_depth:
	limit directory depth to this number (e.g. 
	:file:`/long/path/to/powerline` → :file:`⋯/to/powerline`)
:param bool use_path_separator:
	Use path separator in place of soft divider.
:param bool use_shortened_path:
	Use path from shortened_path ``--renderer_arg`` argument. If this argument 
	is present ``shorten_home`` argument is ignored.
:param bool shorten_home:
	Shorten home directory to ``~``.
:param str ellipsis:
	Specifies what to use in place of omitted directories. Use None to not 
	show this subsegment at all.

Divider highlight group used: ``cwd:divider``.

Highlight groups used: ``cwd:current_folder`` or ``cwd``. It is recommended to define all highlight groups.
''')
Exemplo n.º 42
0
	def update(self, old_ip):
		return _external_ip(query_url=self.query_url)

	def render(self, ip, **kwargs):
		if not ip:
			return None
		return [{'contents': ip, 'divider_highlight_group': 'background:divider'}]


external_ip = with_docstring(ExternalIpSegment(),
'''Return external IP address.

:param str query_url:
	URI to query for IP address, should return only the IP address as a text string

	Suggested URIs:

	* http://ipv4.icanhazip.com/
	* http://ipv6.icanhazip.com/
	* http://icanhazip.com/ (returns IPv6 address if available, else IPv4)

Divider highlight group used: ``background:divider``.
''')


try:
	import netifaces
except ImportError:
	def internal_ip(pl, interface='detect', ipv=4):
		return None
else:
	_interface_starts = {
Exemplo n.º 43
0
                    'unread_count': str(unread_count)
                }
            }]


email_imap_alert = with_docstring(
    EmailIMAPSegment(), ('''Return unread e-mail count for IMAP servers.

:param str username:
    login username
:param str password:
    login password
:param str server:
    e-mail server
:param int port:
    e-mail server port
:param str folder:
    folder to check for e-mails
:param int max_msgs:
    Maximum number of messages. If there are more messages then max_msgs then it
    will use gradient level equal to 100, otherwise gradient level is equal to
    ``100 * msgs_num / max_msgs``. If not present gradient is not computed.
:param bool use_ssl:
    If ``True`` then use SSL connection. If ``False`` then do not use it.
    Default is ``True`` if port is equal to {ssl_port} and ``False`` otherwise.

Highlight groups used: ``email_alert_gradient`` (gradient), ``email_alert``.

Click values supplied: ``unread_count`` (string)
''').format(ssl_port=IMAP4_SSL_PORT))
Exemplo n.º 44
0
            return None

        more = True
        page = 0
        routes = 0
        nodes = []
        while more:
            table = cjdns.NodeStore_dumpTable(page)
            more = "more" in table
            routes += len(table['routingTable'])
            for route in table['routingTable']:
                if not route['ip'] in nodes:
                    nodes.append(route['ip'])
            page += 1
        return nodes

    def render(self, nodes, **kwags):
        return [{
            "contents": str(len(nodes)),
            "highlight_group": ["cjdns:nodes"]
            }]
nodes = with_docstring(
    NodesSegment(),
    """Displays the number of nodes in the cjdns routing table""")

if __name__ == "__main__":
    print """Hint: If you see this message and you don't know why, \
     try reading the included README.md file"""
    print peers(None)
    print nodes(None)
Exemplo n.º 45
0
		@staticmethod
		def shutdown():
			pass

		@staticmethod
		def render(cpu_percent, pl, format='{0:.0f}%', **kwargs):
			pl.warn('Module “psutil” is not installed, thus CPU load is not available')
			return None


cpu_load_percent = with_docstring(CPULoadPercentSegment(),
'''Return the average CPU load as a percentage.

Requires the ``psutil`` module.

:param str format:
	Output format. Accepts measured CPU load as the first argument.

Highlight groups used: ``cpu_load_percent_gradient`` (gradient) or ``cpu_load_percent``.
''')

try:
	import psutil

	class MemLoadPercentSegment(ThreadedSegment):
		def update(self, old_mem):
			mem = psutil.virtual_memory()
			return float(mem.used*100)/float(mem.total)

		def run(self):
			while not self.shutdown_event.is_set():
Exemplo n.º 46
0
			return [{
				'contents': str(unread_count),
				'highlight_groups': ['email_alert_gradient', 'email_alert'],
				'gradient_level': min(unread_count * 100.0 / max_msgs, 100),
			}]


email_imap_alert = with_docstring(EmailIMAPSegment(),
('''Return unread e-mail count for IMAP servers.

:param str username:
	login username
:param str password:
	login password
:param str server:
	e-mail server
:param int port:
	e-mail server port
:param str folder:
	folder to check for e-mails
:param int max_msgs:
	Maximum number of messages. If there are more messages then max_msgs then it
	will use gradient level equal to 100, otherwise gradient level is equal to
	``100 * msgs_num / max_msgs``. If not present gradient is not computed.
:param bool use_ssl:
	If ``True`` then use SSL connection. If ``False`` then do not use it. 
	Default is ``True`` if port is equal to {ssl_port} and ``False`` otherwise.

Highlight groups used: ``email_alert_gradient`` (gradient), ``email_alert``.
''').format(ssl_port=IMAP4_SSL_PORT))
Exemplo n.º 47
0
    def render(self, ip, **kwargs):
        if not ip:
            return None
        return [{
            'contents': ip,
            'divider_highlight_group': 'background:divider'
        }]


external_ip = with_docstring(
    ExternalIpSegment(), '''Return external IP address.

:param str query_url:
	URI to query for IP address, should return only the IP address as a text string

	Suggested URIs:

	* http://ipv4.icanhazip.com/
	* http://ipv6.icanhazip.com/
	* http://icanhazip.com/ (returns IPv6 address if available, else IPv4)

Divider highlight group used: ``background:divider``.
''')

try:
    import netifaces
except ImportError:

    def internal_ip(pl, interface='auto', ipv=4):
        return None
else:
    _interface_starts = {
Exemplo n.º 48
0
	+------------+-------------------------------------------------------------+
:param dict state_symbols:
	Symbols used for displaying state. Must contain all of the following keys:

	========  ========================================================
	Key       Description
	========  ========================================================
	play      Displayed when player is playing.
	pause     Displayed when player is paused.
	stop      Displayed when player is not playing anything.
	fallback  Displayed if state is not one of the above or not known.
	========  ========================================================
'''


_player = with_docstring(PlayerSegment(), _common_args.format('_player'))


class CmusPlayerSegment(PlayerSegment):
	def get_player_status(self, pl):
		'''Return cmus player information.

		cmus-remote -Q returns data with multi-level information i.e.
			status playing
			file <file_name>
			tag artist <artist_name>
			tag title <track_title>
			tag ..
			tag n
			set continue <true|false>
			set repeat <true|false>
Exemplo n.º 49
0
            })
        if removed_files > 0:
            segments.append({
                'contents':
                ' ✖ ' + str(removed_files),
                'highlight_groups': ['hgstatus_removed', 'hgstatus'],
                'divider_highlight_group':
                'hgstatus:divider'
            })

        return segments

    def __call__(self, pl, segment_info):
        pl.debug('Running hgstatus...')

        cwd = segment_info['getcwd']()

        if not cwd:
            return

        branch = self.get_hg_branch(pl, cwd)

        if not branch:
            return

        return self.build_segments(branch, pl, cwd)


hgstatus = with_docstring(
    HgStatusSegment(), '''Return the status of a Mercurial working copy.''')
Exemplo n.º 50
0
srot = with_docstring(
    ScreenRotationSegment(),
    ''' Manage screen rotation and optionally display some information. Optionally disables
    Touchpads in rotated states. (Note that rotating to the ``left`` and ``right``
    states does not currently work if there is another output connected whose
    displayed content is not mirrored to the screen to be rotated.)

    Requires ``xinput`` and ``python-xlib`` and an accelerometer.

    :param string output:
        The initial output to be rotated and to which touchscreen and stylus inputs are mapped.
        (Note that this can be changed at runtime via interaction with the segment.)
    :param bool show_on_all_outputs:
        If set to false, this segment is only visible on the specified output.
    :param string name:
        Possible values are ``rotation`` and ``mode``. This value is used to determine
        which highlight groups to use and how to populate the ``icon`` field in the
        format string in the returned segment.
        If set to any other value, this segment will produce no output.
    :param string format:
        Format string. Possible fields are ``rotation`` (the current rotation state of the screen),
        ``mode`` (either ``auto`` or ``locked``, depending on whether auto-rotation on the
        screen is enabled or not), and ``icon`` (an icon depicting either the rotation status
        or the auto-rotation status, depending on the segment's name).
    :param dict icons:
        Dictionary mapping rotation states (``normal``, ``inverted``, ``left``, ``right``)
        and auto-rotation states (``locked``, ``auto``) to strings to use to display them.
        Depending on the given name parameter, not all of these fields must be populated.
    :param string list states:
        Allowed rotation states. Possible entries are ``normal``, ``inverted``, ``left``, and
        ``right``. Per default, all of them are enabled.
    :param dict gravity_triggers:
        Sensor values that trigger rotation as a dictionary mapping rotation states
        (``normal``, ``inverted``, ``left``, ``right``) to numbers.
        Defaults to ``{'normal': -8, 'inverted': 8, 'left': 8, 'right': -8}``, meaning that
        a (scaled) reading of the ``in_accel_x_raw`` reading greater than 8 triggers a
        rotation to state ``left`` and a reading less than -8 triggers a rotation to state
        ``right``. Readings of ``in_accel_y_raw`` greater and less than 8 and -8 respectively
        will yield a rotation to the ``inverted`` and ``normal`` states respectively.
    :param string_list mapped_inputs:
        List of substrings of device names that should be mapped to the specified output.
        The entries in the specified list should be only substrings of devices listed as
        ``Virtual core pointer``, not of devices listed as ``Virtual core keyboard``.
    :param string_list touchpads:
        List of substrings of device names of touchpads to be managed.
        The entries in the specified list should be only substrings of devices listed as
        ``Virtual core pointer``, not of devices listed as ``Virtual core keyboard``.
    :param dict touchpad_states:
        Dictionary mapping a rotation state (``normal``, ``inverted``, ``left``, ``right``)
        to either ``enabled`` or ``disabled``, depending on whether the touchpads shall be
        enabled or disabled if the output is currently in the corresponding state.
    :param string rotation_hook:
        A string to be run by a shell after a rotation that changes the screen ratio
        (e.g. from ``normal`` to ``left``).
        It will be executed after the rotation takes place, but before the inputs are
        mapped to the output and before the bar resizes itself.
    :param (string,string_list)_list additional_controls:
        A list of (contents, highlight_groups) pairs. For each entry, an additional
        segment with the given contents and highlight groups is omitted. These segments
        obtain the same click values and may also be used to control the segment behavior.
        Also, all segments additionally use the ``srot`` highlight group and the contents
        may be a format string with all fields (except ``icon``) available.
    :param bool hide_controls:
        Hide the extra control segments. They may be shown via segment interaction.

    Highlight groups used: ``srot:normal`` or ``srot:inverted`` or ``srot:right`` or ``srot:left`` or ``srot:rotation`` or ``srot`` (if the name parameter is ``rotation``) or
    ``srot:auto`` or ``srot:locked`` or ``srot:mode`` or ``srot`` (if the name parameter
    is ``mode``) or None (if the name is set to something else).

    Click values supplied: ``mode`` (string), ``rotation`` (string), ``output`` (string,
    the output this segment is rendered to), ``managed_output`` (string, the screen
    currently managed), ``touch_output`` (string, the screen where touch inputs are mapped to).

    Interaction: This segment supports interaction via bar commands in the following way.
    (Note that parameters given to the bar may be combined with click values.)

    +------------------------------------------+---------------------------------------------+
    | Bar command                              | Description                                 |
    +==========================================+=============================================+
    | #bar;pass_oneshot:capture_input:<output> | Map all specified input devices to <output> |
    |                                          | (experimental)                              |
    +------------------------------------------+---------------------------------------------+
    | #bar;pass_oneshot:capture:<output>       | Rotate the screen <output> instead          |
    |                                          | (experimental)                              |
    +------------------------------------------+---------------------------------------------+
    | #bar;pass_oneshot:toggle_rot             | Toggle auto rotation if used on the screen  |
    |                                          | that is currently managed; otherwise        |
    |                                          | ignored.                                    |
    +------------------------------------------+---------------------------------------------+
    | #bar;pass_oneshot:toggle_controls:<outpt>| Toggles the visibility of additional        |
    |                                          | control segments on output <output>         |
    +------------------------------------------+---------------------------------------------+
''')
Exemplo n.º 51
0
    @staticmethod
    def get_directory(segment_info):
        if vim_getbufoption(segment_info, 'buftype'):
            return None
        return buffer_name(segment_info)


branch = with_docstring(
    VimBranchSegment(), '''Return the current working branch.

:param bool status_colors:
	Determines whether repository status will be used to determine highlighting.
	Default: False.
:param bool ignore_statuses:
	List of statuses which will not result in repo being marked as dirty. Most
	useful is setting this option to ``["U"]``: this will ignore repository
	which has just untracked files (i.e. repository with modified, deleted or
	removed files will be marked as dirty, while just untracked files will make
	segment show clean repository). Only applicable if ``status_colors`` option
	is True.

Highlight groups used: ``branch_clean``, ``branch_dirty``, ``branch``.

Divider highlight group used: ``branch:divider``.
''')


@requires_filesystem_watcher
@requires_segment_info
class VimStashSegment(StashSegment):
    divider_highlight_group = 'stash:divider'
Exemplo n.º 52
0
	+------------+-------------------------------------------------------------+
:param dict state_symbols:
	Symbols used for displaying state. Must contain all of the following keys:

	========  ========================================================
	Key       Description
	========  ========================================================
	play      Displayed when player is playing.
	pause     Displayed when player is paused.
	stop      Displayed when player is not playing anything.
	fallback  Displayed if state is not one of the above or not known.
	========  ========================================================
"""


_player = with_docstring(PlayerSegment(), _common_args.format("_player"))


class CmusPlayerSegment(PlayerSegment):
    def get_player_status(self, pl):
        """Return cmus player information.

		cmus-remote -Q returns data with multi-level information i.e.
			status playing
			file <file_name>
			tag artist <artist_name>
			tag title <track_title>
			tag ..
			tag n
			set continue <true|false>
			set repeat <true|false>