Exemple #1
0
def get_object(client: InteractiveCommandClient, argv: List[str]) -> InteractiveCommandClient:
    """
    Constructs a path to object and returns given object (if it exists).
    """
    if argv[0] == "cmd":
        argv = argv[1:]

    # Generate full obj specification
    for arg in argv:
        try:
            # check if it is an item
            client = client[client.normalize_item(arg)]
            continue
        except KeyError:
            pass

        try:
            # check if it is an attr
            client = getattr(client, arg)
            continue
        except AttributeError:
            pass

        print("Specified object does not exist " + " ".join(argv))
        sys.exit(1)

    return client
Exemple #2
0
def print_commands(prefix: str, obj: InteractiveCommandClient) -> None:
    """Print available commands for given object."""
    prefix += " -f "
    output = []
    max_cmd = 0  # max len of cmd for formatting

    try:
        cmds = obj.commands()
    except AttributeError:
        print("error: Sorry no commands in ", prefix)
        sys.exit(1)
    except CommandError:
        print("error: Sorry no such object ", prefix)
        sys.exit(1)

    for cmd in cmds:
        doc_args = get_formated_info(obj, cmd)

        pcmd = prefix + cmd
        max_cmd = max(len(pcmd), max_cmd)
        output.append([pcmd, doc_args])

    # Print formatted output
    formating = "{:<%d}\t{}" % (max_cmd + 1)
    for line in output:
        print(formating.format(line[0], line[1]))
Exemple #3
0
def main() -> None:
    "Runs tool according to specified arguments."
    description = 'Simple tool to expose qtile.command functionality to shell.'
    epilog = textwrap.dedent('''\
    Examples:
     qtile-cmd
     qtile-cmd -o cmd
     qtile-cmd -o cmd -f prev_layout -i
     qtile-cmd -o cmd -f prev_layout -a 3 # prev_layout on group 3
     qtile-cmd -o group 3 -f focus_back''')
    fmt = argparse.RawDescriptionHelpFormatter

    parser = argparse.ArgumentParser(description=description,
                                     epilog=epilog,
                                     formatter_class=fmt)
    parser.add_argument('--object',
                        '-o',
                        dest='obj_spec',
                        nargs='+',
                        help='Specify path to object (space separated).  '
                        'If no --function flag display available commands.  '
                        'Use `cmd` to specify root command.')
    parser.add_argument('--function',
                        '-f',
                        default="help",
                        help='Select function to execute.')
    parser.add_argument('--args',
                        '-a',
                        nargs='+',
                        default=[],
                        help='Set arguments supplied to function.')
    parser.add_argument(
        '--info',
        '-i',
        action='store_true',
        help=
        'With both --object and --function args prints documentation for function.'
    )
    parser.add_argument("--socket", "-s", help='Path of the Qtile IPC socket.')
    args = parser.parse_args()

    if args.obj_spec:
        sock_file = args.socket or find_sockfile()
        ipc_client = Client(sock_file)
        cmd_object = IPCCommandInterface(ipc_client)
        cmd_client = InteractiveCommandClient(cmd_object)
        obj = get_object(cmd_client, args.obj_spec)

        if args.function == "help":
            print_commands("-o " + " ".join(args.obj_spec), obj)
        elif args.info:
            print(get_formated_info(obj, args.function, args=True,
                                    short=False))
        else:
            ret = run_function(obj, args.function, args.args)
            if ret is not None:
                pprint.pprint(ret)
    else:
        print_base_objects()
        sys.exit(1)
Exemple #4
0
def cmd_obj(args) -> None:
    "Runs tool according to specified arguments."

    if args.obj_spec:
        sock_file = args.socket or find_sockfile()
        ipc_client = Client(sock_file)
        cmd_object = IPCCommandInterface(ipc_client)
        cmd_client = InteractiveCommandClient(cmd_object)
        obj = get_object(cmd_client, args.obj_spec)

        if args.function == "help":
            print_commands("-o " + " ".join(args.obj_spec), obj)
        elif args.info:
            print(get_formated_info(obj, args.function, args=True, short=False))
        else:
            ret = run_function(obj, args.function, args.args)
            if ret is not None:
                pprint.pprint(ret)
    else:
        print_base_objects()
        sys.exit(1)
Exemple #5
0
def get_formated_info(obj: InteractiveCommandClient,
                      cmd: str,
                      args=True,
                      short=True) -> str:
    """Get documentation for command/function and format it.

    Returns:
      * args=True, short=True - '*' if arguments are present and a summary line.
      * args=True, short=False - (function args) and a summary line.
      * args=False - a summary line.

    If 'doc' function is not present in object or there is no doc string for
    given cmd it returns empty string.  The arguments are extracted from doc[0]
    line, the summary is constructed from doc[1] line.
    """

    if hasattr(obj, "doc"):
        doc = obj.doc(cmd).splitlines()
    else:
        doc = None

    if doc is not None:
        tdoc = doc[0]
        doc_args = tdoc[tdoc.find("(") + 1:tdoc.find(")")].strip()

        short_description = doc[1] if len(doc) > 1 else ""

        if doc_args:  # return formatted args
            doc_args = "({})".format(doc_args)
    else:
        doc_args = ""
        short_description = ""

    if args is False:
        doc_args = ""
    elif args and short:
        doc_args = "*" if len(doc_args) > 1 else " "

    return (doc_args + " " + short_description).rstrip()
Exemple #6
0
# SOFTWARE.
import nest_asyncio
nest_asyncio.apply()
from typing import List  # noqa: F401
import os
import sys
import subprocess

from libqtile.config import Key, Screen, Group, Drag, Click, Match
from libqtile.lazy import lazy
from libqtile import layout, hook, bar, widget
from libqtile.ipc import find_sockfile, Client 
from libqtile.command_client import InteractiveCommandClient 
from libqtile.command_interface import IPCCommandInterface                                                                    

client = InteractiveCommandClient(IPCCommandInterface(Client(find_sockfile())))

from helper import run
from controls import next_keyboard
from apperance import widget_defaults, extension_defaults
from apperance import top_bar, bottom_bar
from debug_logging import logger

# This has to be run this before screens are defined, so that it correctly picks up the order and resulotion
# run("xrandr --output DVI-D-1 --mode 1600x1200 --left-of HDMI-2 --output HDMI-2 --mode 2560x1080 --output HDMI-1 --mode 1920x1080 --right-of HDMI-2")

mod = "mod4"
alt = 'mod1'
username = "******"

def bring_group_to_front(group_name):
Exemple #7
0
def _main():
    parser = argparse.ArgumentParser(description="Get or set qtile workspaces")
    parser.add_argument("cmd", type=str, help="command can be 'get' or 'set'")
    parser.add_argument(
        "--pid",
        "-p",
        type=str,
        help=
        "Gets the workspace status for the screen displaying polybar with this pid. Should be passed with 'get' command"
    ),
    parser.add_argument(
        "--ws",
        "-w",
        type=str,
        help=
        "Sets this workspace as active on current screen. Should be passed with 'set' command"
    ),
    args = parser.parse_args()
    cmd = args.cmd
    pid = args.pid
    set_ws = args.ws

    client = Client()
    groups = client.groups()
    curr_group = client.group.info()
    with open('/tmp/polybar_info', 'r') as fh:
        d = yaml.safe_load(fh)
    screens = d['screens']
    formats = d['formats']
    separator = d['separator']

    if cmd == 'get':
        if not pid:
            print("--pid is required when using get command")
            sys.exit(0)
        result = ""
        for ws in groups:
            if ws == 'scratchpad':
                continue
            if ws == curr_group['name']:
                if pid == screens[str(curr_group['screen'])]['pid']:
                    if result:
                        result = formats['layoutWs'].replace(
                            '%icon%',
                            LAYOUT_ICONS[curr_group['layout']]) + result
                    else:
                        result = formats['layoutWs'].replace(
                            '%icon%', LAYOUT_ICONS[curr_group['layout']])
                    result = result + separator + formats['activeWs'].replace(
                        '%name% %icon%', curr_group['label'])
                else:
                    result = result + separator + formats[
                        'activeWsOther'].replace('%name% %icon%',
                                                 curr_group['label'])
            elif groups[ws]['screen'] is not None:
                if pid == screens[str(groups[ws]['screen'])]['pid']:
                    result = result + separator + formats['visibleWs'].replace(
                        '%name% %icon%', groups[ws]['label'])
                else:
                    result = result + separator + formats[
                        'visibleWsOther'].replace('%name% %icon%',
                                                  groups[ws]['label'])
            elif client.groups()[ws]['windows']:
                result = result + separator + formats['occupiedWs'].replace(
                    '%name% %icon%', groups[ws]['label'])
        return result
    elif cmd == 'set':
        if not set_ws:
            print("--ws is required when using set command")
            sys.exit(0)
        if not set_ws.isdigit():
            _ws = int(curr_group['name'])
            if set_ws in ['next', '+1']:
                set_ws = str(_ws + 1) if _ws + 1 <= len(groups) - 1 else '1'
            elif set_ws in ['prv', 'prev', 'previous', '-1']:
                set_ws = str(_ws - 1) if _ws - 1 >= 1 else str(len(groups) - 1)
            else:
                sys.exit(1)
        elif set_ws not in groups:
            sys.exit(1)
        client.group[set_ws].toscreen()
        try:
            subprocess.call(['polybar-msg', 'hook', 'qtileWs', '1'])
        except subprocess.CalledProcessError as e:
            print(e)
Exemple #8
0
 def __init__(self):
     self.color = 0
     self.client = InteractiveCommandClient(
         IPCCommandInterface(IPCClient(find_sockfile())))
Exemple #9
0
class Client:
    COLORS = [
        "#44cc44",  # green
        "#cc44cc",  # magenta
        "#4444cc",  # blue
        "#cccc44",  # yellow
        "#44cccc",  # cyan
        "#cccccc",  # white
        "#777777",  # gray
        "#ffa500",  # orange
        "#333333",  # black
    ]

    def __init__(self):
        self.color = 0
        self.client = InteractiveCommandClient(
            IPCCommandInterface(IPCClient(find_sockfile())))

    def current_group(self):
        return self.client.group[self.client.group.info().get("name")]

    def switch_to_group(self, group):
        if isinstance(group, str):
            self.client.group[group].toscreen()
        else:
            group.toscreen()

    def spawn_window(self, color=None):
        if color is None:
            color = self.color
            self.color += 1
        if isinstance(color, int):
            color = Client.COLORS[color]
        self.client.spawn(
            "xterm +ls -hold -e printf '\e]11;{}\007'".format(color))

    def prepare_layout(self, layout, windows, commands=None):
        # set selected layout
        self.client.group.setlayout(layout)

        # spawn windows
        for i in range(windows):
            self.spawn_window()
            time.sleep(0.05)

        # prepare layout
        if commands:
            for cmd in commands:
                self.run_layout_command(cmd)
                time.sleep(0.05)

    def clean_layout(self, commands=None):
        if commands:
            for cmd in commands:
                self.run_layout_command(cmd)
                time.sleep(0.05)
        self.kill_group_windows()

    def run_layout_command(self, cmd):
        if cmd == "spawn":
            self.spawn_window()
        else:
            getattr(self.client.layout, cmd)()

    def kill_group_windows(self):
        while len(self.client.layout.info().get("clients")) > 0:
            try:
                self.client.window.kill()
            except Exception:
                pass
        self.color = 0
Exemple #10
0
                    return True
                return False
            if q.current_layout.name != self._layout:
                if q.current_window and q.current_window.floating and not self._when_floating:
                    return False
        return True


class LazyCommandInterface(CommandInterface):
    """A lazy loading command object

    Allows all commands and items to be resolved at run time, and returns
    lazily evaluated commands.
    """
    def execute(self, call: CommandGraphCall, args: Tuple,
                kwargs: Dict) -> LazyCall:
        """Lazily evaluate the given call"""
        return LazyCall(call, args, kwargs)

    def has_command(self, node: CommandGraphNode, command: str) -> bool:
        """Lazily resolve the given command"""
        return True

    def has_item(self, node: CommandGraphNode, object_type: str,
                 item: Union[str, int]) -> bool:
        """Lazily resolve the given item"""
        return True


lazy = InteractiveCommandClient(LazyCommandInterface())
Exemple #11
0
 def __init__(self, qtile: CommandObject) -> None:
     q = QtileCommandInterface(qtile)
     self.client = InteractiveCommandClient(q)
     self.thisfinal = None  # type: Optional[str]
     self.reset()
Exemple #12
0
                    return True
                return False
            if q.current_layout.name != self._layout:
                if q.current_window and q.current_window.floating and not self._when_floating:
                    return False
        return True


class LazyCommandObject(CommandInterface):
    """A lazy loading command object

    Allows all commands and items to be resolved at run time, and returns
    lazily evaluated commands.
    """
    def execute(self, call: CommandGraphCall, args: Tuple,
                kwargs: Dict) -> LazyCall:
        """Lazily evaluate the given call"""
        return LazyCall(call, args, kwargs)

    def has_command(self, node: CommandGraphNode, command: str) -> bool:
        """Lazily resolve the given command"""
        return True

    def has_item(self, node: CommandGraphNode, object_type: str,
                 item: Union[str, int]) -> bool:
        """Lazily resolve the given item"""
        return True


lazy = InteractiveCommandClient(LazyCommandObject())
Exemple #13
0
from libqtile.ipc import find_sockfile, Client as IPCClient
from libqtile.command_client import InteractiveCommandClient
from libqtile.command_interface import IPCCommandInterface

if __name__ == '__main__':
    client = InteractiveCommandClient(
        IPCCommandInterface(IPCClient(find_sockfile())))
    # does not work:
    print(client.display_kb())
    # print(getattr(client, 'display_kb')())