Skip to content

Commit b96e431

Browse files
committed
Initial commit
0 parents  commit b96e431

16 files changed

+551
-0
lines changed

.flake8

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[flake8]
2+
max-line-length = 127

.gitignore

+164
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# poetry
98+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102+
#poetry.lock
103+
104+
# pdm
105+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106+
#pdm.lock
107+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108+
# in version control.
109+
# https://pdm.fming.dev/#use-with-ide
110+
.pdm.toml
111+
112+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113+
__pypackages__/
114+
115+
# Celery stuff
116+
celerybeat-schedule
117+
celerybeat.pid
118+
119+
# SageMath parsed files
120+
*.sage.py
121+
122+
# Environments
123+
.env
124+
.venv
125+
env/
126+
venv/
127+
ENV/
128+
env.bak/
129+
venv.bak/
130+
131+
# Spyder project settings
132+
.spyderproject
133+
.spyproject
134+
135+
# Rope project settings
136+
.ropeproject
137+
138+
# mkdocs documentation
139+
/site
140+
141+
# mypy
142+
.mypy_cache/
143+
.dmypy.json
144+
dmypy.json
145+
146+
# Pyre type checker
147+
.pyre/
148+
149+
# pytype static type analyzer
150+
.pytype/
151+
152+
# Cython debug symbols
153+
cython_debug/
154+
155+
# PyCharm
156+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158+
# and can be added to the global gitignore or merged into this file. For a more nuclear
159+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160+
#.idea/
161+
162+
.vscode
163+
164+
test.py

README.md

Whitespace-only changes.

pyflowlauncher/__init__.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import os
2+
import logging
3+
4+
from .plugin import Plugin, ResultResponse, send_results
5+
from .result import Result
6+
from .jsonrpc import JsonRPCRequest
7+
8+
9+
log_level = os.environ.get("FLOW_LAUNCHER_API_LOG_LEVEL", "INFO")
10+
11+
logger = logging.getLogger(__name__)
12+
13+
__all__ = [
14+
"Plugin",
15+
"ResultResponse",
16+
"send_results",
17+
"Result",
18+
"JsonRPCRequest",
19+
]
20+
21+
22+
logging.basicConfig(
23+
level=log_level,
24+
format="%(asctime)s %(name)s %(levelname)s %(message)s",
25+
datefmt="%Y-%m-%d %H:%M:%S",
26+
)

pyflowlauncher/api.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from .jsonrpc import JsonRPCRequest
2+
3+
NAME_SPACE = 'Flow.Launcher'
4+
5+
6+
def change_query(query: str, requery: bool = False) -> JsonRPCRequest:
7+
"""Change the query in Flow Launcher."""
8+
return {"method": f"{NAME_SPACE}.ChangeQuery", "parameters": [query, requery]}
9+
10+
11+
def shell_run(command: str) -> JsonRPCRequest:
12+
"""Run a shell command."""
13+
return {"method": f"{NAME_SPACE}.ShellRun", "parameters": [command]}
14+
15+
16+
def close_app() -> JsonRPCRequest:
17+
"""Close Flow Launcher."""
18+
return {"method": f"{NAME_SPACE}.CloseApp", "parameters": []}
19+
20+
21+
def hide_app() -> JsonRPCRequest:
22+
"""Hide Flow Launcher."""
23+
return {"method": f"{NAME_SPACE}.HideApp", "parameters": []}
24+
25+
26+
def show_app() -> JsonRPCRequest:
27+
"""Show Flow Launcher."""
28+
return {"method": f"{NAME_SPACE}.ShowApp", "parameters": []}
29+
30+
31+
def show_msg(title: str, sub_title: str, ico_path: str = "") -> JsonRPCRequest:
32+
"""Show a message in Flow Launcher."""
33+
return {"method": f"{NAME_SPACE}.ShowMsg", "parameters": [title, sub_title, ico_path]}
34+
35+
36+
def open_setting_dialog() -> JsonRPCRequest:
37+
"""Open the settings window in Flow Launcher."""
38+
return {"method": f"{NAME_SPACE}.OpenSettingDialog", "parameters": []}
39+
40+
41+
def start_loading_bar() -> JsonRPCRequest:
42+
"""Start the loading bar in Flow Launcher."""
43+
return {"method": f"{NAME_SPACE}.StartLoadingBar", "parameters": []}
44+
45+
46+
def stop_loading_bar() -> JsonRPCRequest:
47+
"""Stop the loading bar in Flow Launcher."""
48+
return {"method": f"{NAME_SPACE}.StopLoadingBar", "parameters": []}
49+
50+
51+
def reload_plugins() -> JsonRPCRequest:
52+
"""Reload the plugins in Flow Launcher."""
53+
return {"method": f"{NAME_SPACE}.ReloadPlugins", "parameters": []}

pyflowlauncher/event.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
3+
class EventHandler:
4+
5+
def __init__(self):
6+
self._methods = {}
7+
8+
def add_method(self, method, *, name=None):
9+
self._methods[name or method.__name__] = method
10+
11+
def add_methods(self, methods):
12+
for method in methods:
13+
self.add_method(method)
14+
15+
def __call__(self, method, *args, **kwargs):
16+
return self._methods[method](*args, **kwargs)

pyflowlauncher/icons.py

Whitespace-only changes.

pyflowlauncher/jsonrpc.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import json
2+
import sys
3+
from typing import Any, Dict, Mapping, TypedDict, NotRequired
4+
5+
6+
class JsonRPCRequest(TypedDict):
7+
method: str
8+
parameters: list
9+
settings: NotRequired[Dict[Any, Any]]
10+
11+
12+
Response = Dict[Any, Any]
13+
14+
15+
class JsonRPCClient:
16+
17+
def send(self, data: Mapping) -> None:
18+
json.dump(data, sys.stdout)
19+
20+
def recieve(self) -> JsonRPCRequest:
21+
try:
22+
return json.loads(sys.argv[1])
23+
except IndexError:
24+
return {'method': 'query', 'parameters': ['']}

pyflowlauncher/plugin.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from typing import Any, Dict, Iterable, Callable, Optional, TypedDict, Union
2+
from functools import wraps
3+
4+
from .result import Result
5+
from .jsonrpc import JsonRPCClient
6+
from .event import EventHandler
7+
from .api import JsonRPCRequest
8+
9+
10+
class ResultResponse(TypedDict):
11+
result: Iterable[Dict[str, Any]]
12+
13+
14+
Method = Callable[..., Union[ResultResponse, JsonRPCRequest]]
15+
16+
17+
def send_results(results: Iterable[Result]) -> ResultResponse:
18+
return {'result': [result.as_dict() for result in results]}
19+
20+
21+
class Plugin:
22+
23+
def __init__(self, methods: Optional[list[Method]] = None) -> None:
24+
self._client = JsonRPCClient()
25+
self._event_handler = EventHandler()
26+
self._settings: Dict[str, Any] = {}
27+
if methods:
28+
self.add_methods(methods)
29+
30+
def add_method(self, method: Method, *, name: Optional[str] = None) -> None:
31+
self._event_handler.add_method(method, name=name)
32+
33+
def add_methods(self, methods: Iterable[Method]) -> None:
34+
self._event_handler.add_methods(methods)
35+
36+
def on_method(self, method: Method) -> Method:
37+
@wraps(method)
38+
def wrapper(*args, **kwargs):
39+
return method(*args, **kwargs)
40+
self._event_handler.add_method(wrapper)
41+
return wrapper
42+
43+
@property
44+
def settings(self) -> Dict:
45+
if self._settings is None:
46+
self._settings = {}
47+
self._settings = self._client.recieve().get('settings', {})
48+
return self._settings
49+
50+
def run(self) -> None:
51+
request = self._client.recieve()
52+
method = request.get('method')
53+
parameters = request.get('parameters', [])
54+
feedback = self._event_handler(method, *parameters)
55+
self._client.send(feedback)

pyflowlauncher/result.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from __future__ import annotations
2+
from dataclasses import dataclass
3+
from pathlib import Path
4+
from typing import TYPE_CHECKING, Any, Iterable, Optional, TypedDict, Union, Dict, NotRequired
5+
6+
7+
if TYPE_CHECKING:
8+
from .plugin import Method
9+
10+
11+
class JsonRPCAction(TypedDict):
12+
"""Flow Launcher JsonRPCAction"""
13+
Method: str
14+
Parameters: Iterable
15+
DontHideAfterAction: NotRequired[bool]
16+
17+
18+
class Glyph(TypedDict):
19+
"""Flow Launcher Glyph"""
20+
Glyph: str
21+
FontFamily: str
22+
23+
24+
@dataclass
25+
class Result:
26+
Title: str
27+
SubTitle: Optional[str] = None
28+
IcoPath: Optional[Union[str, Path]] = None
29+
Score: int = 0
30+
JsonRPCAction: Optional[JsonRPCAction] = None
31+
ContextData: Optional[Iterable] = None
32+
Glyph: Optional[Glyph] = None
33+
CopyText: Optional[str] = None
34+
AutoCompleteText: Optional[str] = None
35+
RoundedIcon: bool = False
36+
37+
def as_dict(self) -> Dict[str, Any]:
38+
return self.__dict__
39+
40+
def add_action(self, method: Method,
41+
parameters: Optional[Iterable[Any]] = None,
42+
*,
43+
dont_hide_after_action: bool = False) -> None:
44+
self.JsonRPCAction = {
45+
"Method": method.__name__,
46+
"Parameters": parameters or [],
47+
"DontHideAfterAction": dont_hide_after_action
48+
}
49+
self._method = method

0 commit comments

Comments
 (0)