├── .gitignore ├── kitty.conf.example ├── grab.py ├── grab-vim.conf.example ├── kitten_options_parse.py ├── kitten_options_utils.py ├── grab.conf.example ├── README.md ├── kitten_options_definition.py ├── kitten_options_types.py ├── _grab_ui.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | **/__pycache__/ 3 | .mypy_cache 4 | -------------------------------------------------------------------------------- /kitty.conf.example: -------------------------------------------------------------------------------- 1 | map alt+insert kitten kitty_grab/grab.py 2 | -------------------------------------------------------------------------------- /grab.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import Any, Dict, List, Sequence 3 | 4 | from kittens.tui.handler import result_handler 5 | try: 6 | # For kitty v0.42+ 7 | from kitty.typing_compat import BossType 8 | except ModuleNotFoundError: 9 | # Fallback for older versions of kitty. 10 | from kitty.typing import BossType 11 | 12 | import _grab_ui 13 | 14 | 15 | def main(args: List[str]) -> None: 16 | pass 17 | 18 | 19 | @result_handler(no_ui=True) 20 | def handle_result(args: List[str], data: Dict[str, Any], target_window_id: int, boss: BossType) -> None: 21 | window = boss.window_id_map.get(target_window_id) 22 | if window is None: 23 | return 24 | tab = window.tabref() 25 | if tab is None: 26 | return 27 | content = window.as_text(as_ansi=True, add_history=True, 28 | add_wrap_markers=True) 29 | content = content.replace('\r\n', '\n').replace('\r', '\n') 30 | n_lines = content.count('\n') 31 | top_line = (n_lines - (window.screen.lines - 1) - window.screen.scrolled_by) 32 | boss._run_kitten(_grab_ui.__file__, args=[ 33 | *args[1:], 34 | '--title={}'.format(window.title), 35 | '--cursor-x={}'.format(window.screen.cursor.x), 36 | '--cursor-y={}'.format(window.screen.cursor.y), 37 | '--top-line={}'.format(top_line)], 38 | input_data=content.encode('utf-8'), 39 | window=window) 40 | -------------------------------------------------------------------------------- /grab-vim.conf.example: -------------------------------------------------------------------------------- 1 | # vim:fileencoding=utf-8:ft=conf:foldmethod=marker 2 | 3 | #: Colors {{{ 4 | 5 | # selection_foreground #FFFFFF 6 | # selection_background #5294E2 7 | 8 | #: Colors for selected text while grabbing. 9 | 10 | # cursor #ad7fa8 11 | 12 | #: Cursor color while grabbing. 13 | 14 | #: }}} 15 | 16 | #: Key shortcuts {{{ 17 | 18 | # map q quit 19 | 20 | #: Exit the grabber without copying anything. 21 | 22 | # map Enter confirm 23 | map y confirm 24 | 25 | #: Copy the selected region to clipboard and exit. 26 | 27 | map h move left 28 | map l move right 29 | map k move up 30 | map j move down 31 | map Ctrl+u move page up 32 | map Ctrl+d move page down 33 | map 0 move first 34 | map ^ move first nonwhite 35 | map $ move last nonwhite 36 | map g move top 37 | map G move bottom 38 | map b move word left 39 | map w move word right 40 | 41 | #: Move the cursor around the screen. 42 | #: This will scroll the buffer if needed and possible. 43 | #: Note that due to https://github.com/kovidgoyal/kitty/issues/5469, the ctrl+d 44 | #: shortcut will only work with kitty >= 0.26.2 45 | 46 | map Ctrl+y scroll up 47 | map Ctrl+e scroll down 48 | 49 | #: Scroll the buffer, if possible. 50 | #: Cursor stays in the same position relative to the screen. 51 | 52 | map v set_mode visual 53 | map Ctrl+v set_mode block 54 | map Ctrl+Left_Bracket set_mode normal 55 | map Escape set_mode normal 56 | 57 | #: Change the selecting mode. 58 | 59 | #: }}} 60 | -------------------------------------------------------------------------------- /kitten_options_parse.py: -------------------------------------------------------------------------------- 1 | # generated by gen-config.py DO NOT edit 2 | 3 | import typing 4 | from kitten_options_utils import parse_map 5 | from kitty.conf.utils import merge_dicts, to_color 6 | 7 | 8 | class Parser: 9 | 10 | def cursor(self, val: str, ans: typing.Dict[str, typing.Any]) -> None: 11 | ans['cursor'] = to_color(val) 12 | 13 | def select_by_word_characters(self, val: str, ans: typing.Dict[str, typing.Any]) -> None: 14 | ans['select_by_word_characters'] = str(val) 15 | 16 | def selection_background(self, val: str, ans: typing.Dict[str, typing.Any]) -> None: 17 | ans['selection_background'] = to_color(val) 18 | 19 | def selection_foreground(self, val: str, ans: typing.Dict[str, typing.Any]) -> None: 20 | ans['selection_foreground'] = to_color(val) 21 | 22 | def map(self, val: str, ans: typing.Dict[str, typing.Any]) -> None: 23 | for k in parse_map(val): 24 | ans['map'].append(k) 25 | 26 | 27 | def create_result_dict() -> typing.Dict[str, typing.Any]: 28 | return { 29 | 'map': [], 30 | } 31 | 32 | 33 | actions: typing.FrozenSet[str] = frozenset(('map',)) 34 | 35 | 36 | def merge_result_dicts(defaults: typing.Dict[str, typing.Any], vals: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]: 37 | ans = {} 38 | for k, v in defaults.items(): 39 | if isinstance(v, dict): 40 | ans[k] = merge_dicts(v, vals.get(k, {})) 41 | elif k in actions: 42 | ans[k] = v + vals.get(k, []) 43 | else: 44 | ans[k] = vals.get(k, v) 45 | return ans 46 | 47 | 48 | parser = Parser() 49 | 50 | 51 | def parse_conf_item(key: str, val: str, ans: typing.Dict[str, typing.Any]) -> bool: 52 | func = getattr(parser, key, None) 53 | if func is not None: 54 | func(val, ans) 55 | return True 56 | return False 57 | -------------------------------------------------------------------------------- /kitten_options_utils.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Callable, Iterable, Sequence, Tuple 2 | 3 | from kitty.conf.utils import KittensKeyDefinition, parse_kittens_key 4 | 5 | FuncArgsType = Tuple[str, Sequence[Any]] 6 | 7 | try: 8 | from kitty.conf.utils import KeyFuncWrapper 9 | func_with_args = KeyFuncWrapper[FuncArgsType]() 10 | except ImportError: 11 | from kitty.conf.utils import key_func 12 | func_with_args, args_funcs = key_func() 13 | func_with_args.args_funcs = args_funcs 14 | 15 | 16 | 17 | def parse_map(val: str) -> Iterable[KittensKeyDefinition]: 18 | x = parse_kittens_key(val, func_with_args.args_funcs) 19 | if x is not None: 20 | yield x 21 | 22 | 23 | def parse_region_type(region_type: str) -> str: 24 | result = region_type.lower() 25 | assert result in ['stream', 'columnar'] 26 | return result 27 | 28 | 29 | def parse_direction(direction: str) -> str: 30 | direction_lc = direction.lower() 31 | assert direction_lc in ['left', 'right', 'up', 'down', 32 | 'page up', 'page down', 33 | 'first', 'first nonwhite', 34 | 'last nonwhite', 'last', 35 | 'top', 'bottom', 36 | 'word left', 'word right'] 37 | return direction_lc.replace(' ', '_') 38 | 39 | 40 | def parse_scroll_direction(direction: str) -> str: 41 | result = direction.lower() 42 | assert result in ['up', 'down'] 43 | return result 44 | 45 | 46 | def parse_mode(mode: str) -> str: 47 | result = mode.lower() 48 | assert result in ['normal', 'visual', 'block'] 49 | return result 50 | 51 | 52 | @func_with_args('move') 53 | def move(func: Callable, direction: str) -> Tuple[Callable, str]: 54 | return func, parse_direction(direction) 55 | 56 | 57 | @func_with_args('scroll') 58 | def scroll(func: Callable, direction: str) -> Tuple[Callable, str]: 59 | return func, parse_scroll_direction(direction) 60 | 61 | 62 | @func_with_args('select') 63 | def select(func: Callable, args: str) -> Tuple[Callable, Tuple[str, str]]: 64 | region_type, direction = args.split(' ', 1) 65 | return func, (parse_region_type(region_type), 66 | parse_direction(direction)) 67 | 68 | 69 | @func_with_args("set_mode") 70 | def set_mode(func: Callable, mode: str) -> Tuple[Callable, str]: 71 | return func, parse_mode(mode) 72 | -------------------------------------------------------------------------------- /grab.conf.example: -------------------------------------------------------------------------------- 1 | # vim:fileencoding=utf-8:ft=conf:foldmethod=marker 2 | 3 | #: Colors {{{ 4 | 5 | # selection_foreground #FFFFFF 6 | # selection_background #5294E2 7 | 8 | #: Colors for selected text while grabbing. 9 | 10 | # cursor #ad7fa8 11 | 12 | #: Cursor color while grabbing. 13 | 14 | #: }}} 15 | 16 | #: Key shortcuts {{{ 17 | 18 | # map q quit 19 | # map Escape quit 20 | 21 | #: Exit the grabber without copying anything. 22 | 23 | # map Enter confirm 24 | 25 | #: Copy the selected region to clipboard and exit. 26 | 27 | # map Left move left 28 | # map Right move right 29 | # map Up move up 30 | # map Down move down 31 | # map Page_Up move page up 32 | # map Page_Down move page down 33 | # map Home move first 34 | # map a move first nonwhite 35 | # map End move last nonwhite 36 | # map e move last 37 | # map Ctrl+Home move top 38 | # map Ctrl+End move bottom 39 | # map Ctrl+Left move word left 40 | # map Ctrl+Right move word right 41 | 42 | #: Cancel selection and move the cursor around the screen. 43 | #: This will scroll the buffer if needed and possible. 44 | 45 | # map Ctrl+Up scroll up 46 | # map Ctrl+Down scroll down 47 | 48 | #: Scroll the buffer, if possible. 49 | #: Cursor stays in the same position relative to the screen. 50 | 51 | # map Shift+Left select stream left 52 | # map Shift+Right select stream right 53 | # map Shift+Up select stream up 54 | # map Shift+Down select stream down 55 | # map Shift+Page_Up select stream page up 56 | # map Shift+Page_Down select stream page down 57 | # map Shift+Home select stream first 58 | # map A select stream first nonwhite 59 | # map Shift+End select stream last nonwhite 60 | # map E select stream last 61 | # map Shift+Ctrl+Home select stream top 62 | # map Shift+Ctrl+End select stream bottom 63 | # map Shift+Ctrl+Left select stream word left 64 | # map Shift+Ctrl+Right select stream word right 65 | 66 | #: Extend a stream selection. 67 | #: If no region is selected, start selecting. 68 | #: Stream selection includes all characters between the region ends. 69 | 70 | # map Alt+Left select columnar left 71 | # map Alt+Right select columnar right 72 | # map Alt+Up select columnar up 73 | # map Alt+Down select columnar down 74 | # map Alt+Page_Up select columnar page up 75 | # map Alt+Page_Down select columnar page down 76 | # map Alt+Home select columnar first 77 | # map Alt+A select columnar first nonwhite 78 | # map Alt+End select columnar last nonwhite 79 | # map Alt+E select columnar last 80 | # map Alt+Ctrl+Home select columnar top 81 | # map Alt+Ctrl+End select columnar bottom 82 | # map Alt+Ctrl+Left select columnar word left 83 | # map Alt+Ctrl+Right select columnar word right 84 | 85 | #: Extend a columnar selection. 86 | #: If no region is selected, start selecting. 87 | #: Columnar selection includes characters in the rectangle 88 | #: defined by the region ends. 89 | 90 | #: }}} 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Keyboard-driven screen grabber for Kitty 2 | 3 | [Kitty][kitty] is a fast GPU-based terminal emulator. 4 | 5 | [kitty]: https://sw.kovidgoyal.net/kitty/ 6 | 7 | Kitty lets you select text in the terminal using your mouse 8 | and copy it to the clipboard using a key shortcut. 9 | However, it lacks a built-in way to select text using the keyboard. 10 | 11 | This project implements keyboard-driven text selection as a kitten. 12 | 13 | 14 | # Minimum requirements 15 | 16 | Kitty ≥0.21.2. 17 | 18 | For Kitty ≥0.13.0, <0.21.0, see the tag `v0.20`, 19 | but be aware that version will not be updated. 20 | 21 | 22 | # Installation and initial configuration 23 | 24 | * Clone this repository into your Kitty configuration directory: 25 | 26 | $ cd ~/.config/kitty 27 | $ git clone https://github.com/yurikhan/kitty_grab.git 28 | 29 | * In the Kitty configuration file (`kitty.conf`), 30 | map a key to run the `grab.py` kitten: 31 | 32 | map Alt+Insert kitten kitty_grab/grab.py 33 | 34 | * Restart kitty or reload the config (`Ctrl`+`Shift`+`F5` by default, see [kitty.conf](https://sw.kovidgoyal.net/kitty/conf/#shortcut-kitty.Reload-kitty.conf)). 35 | 36 | 37 | # Usage 38 | 39 | When you press the key bound to `kitten grab1.py`, 40 | your screen will briefly flash 41 | and its title will change to indicate the grabber is active. 42 | 43 | You can now move your cursor around the screen using arrow keys. 44 | It will scroll if you try to go beyond the screen top or bottom. 45 | Hold down `Shift` while moving to select a stream region, 46 | or `Alt` to select a rectangular (columnar) region. 47 | Press `Enter` to copy the selected region to the clipboard and exit, 48 | or `Esc` or `q` to exit without copying. 49 | 50 | 51 | ## Start/end of buffer 52 | 53 | `Ctrl`+`Home`/`End` move (or, with `Shift` or `Alt`, select) 54 | to the top left or bottom right of the buffer, respectively. 55 | 56 | **Note:** By default, Kitty binds `Ctrl`+`Shift`+`Home`/`End` 57 | to scroll the scrollback buffer to top and bottom, respectively. 58 | You might want to install [`kitty_scroll`][kitty_scroll] 59 | to be able to use these shortcuts with `kitty_grab`. 60 | 61 | [kitty_scroll]: https://github.com/yurikhan/kitty-smart-scroll 62 | 63 | map Ctrl+Shift+Home kitten smart_scroll.py scroll_home Ctrl+Shift+Home 64 | map Ctrl+Shift+End kitten smart_scroll.py scroll_end Ctrl+Shift+End 65 | 66 | 67 | ## Word motion 68 | 69 | Hold down `Ctrl` while pressing `←`/`→` to move by words. 70 | 71 | 72 | **Note:** By default, Kitty binds `Ctrl`+`Shift`+`←`/`→` 73 | to activate the previous/next tab. 74 | That will prevent `kitty_grab`, 75 | as well as other terminal-based programs, 76 | from seeing these combinations. 77 | You can either bind different keys in `grab.conf`: 78 | 79 | map Shift+Alt+B select stream word left 80 | map Shift+Alt+F select stream word right 81 | 82 | or rebind previous/next tab to different keys in `kitty.conf` 83 | (recommended): 84 | 85 | map kitty_mod+Left no_op 86 | map kitty_mod+Right no_op 87 | map Ctrl+Page_Up previous_tab 88 | map Ctrl+Page_Down next_tab 89 | 90 | (Remember to [reload config](https://sw.kovidgoyal.net/kitty/conf/#shortcut-kitty.Reload-kitty.conf/) if you modify `kitty.conf`.) 91 | 92 | 93 | # Configuration 94 | 95 | See the `grab.conf.example` file. 96 | You will need to copy it to `~/.config/kitty/grab.conf` 97 | and edit to your liking. 98 | 99 | All example entries are commented out. 100 | Remove the `#` at the start of lines you modify. 101 | 102 | You do not need to reload config when you edit `grab.conf`. 103 | It will take effect the next time you use the grabber. 104 | 105 | 106 | # Vim-like Modal Highlighting 107 | 108 | Vim-like modal selecting is available. 109 | Copy the provided `grab-vim.conf.example` file, and copy it to `~/.config/kitty/grab.conf`. 110 | 111 | 112 | # License 113 | 114 | GNU Public License version 3 or later. 115 | -------------------------------------------------------------------------------- /kitten_options_definition.py: -------------------------------------------------------------------------------- 1 | from kitty.conf.types import Action, Definition 2 | 3 | definition = Definition( 4 | '!kitten_options_utils', 5 | Action( 6 | 'map', 'parse_map', 7 | {'key_definitions': 'kitty.conf.utils.KittensKeyMap'}, 8 | ['kitty.types.ParsedShortcut', 'kitty.conf.utils.KeyAction'] 9 | ), 10 | ) 11 | 12 | agr = definition.add_group 13 | egr = definition.end_group 14 | opt = definition.add_option 15 | map = definition.add_map 16 | 17 | # color options {{{ 18 | agr('color', 'Color') 19 | 20 | opt('selection_foreground', '#FFFFFF', 21 | option_type='to_color', 22 | long_text=''' 23 | Foreground color for selected text while grabbing.''') 24 | opt('selection_background', '#5294E2', 25 | option_type='to_color', 26 | long_text=''' 27 | Background color for selected text while grabbing.''') 28 | 29 | opt('cursor', '#ad7fa8', 30 | option_type='to_color', 31 | long_text=''' 32 | Cursor color while grabbing.''') 33 | 34 | egr() # }}} 35 | 36 | # shortcuts {{{ 37 | agr('shortcuts', 'Keyboard shortcuts') 38 | 39 | long_text = ''' 40 | Exit the grabber without copying anything.''' 41 | map('Quit', 'quit q quit') 42 | map('Quit', 'quit Escape quit', long_text=long_text) 43 | 44 | long_text = ''' 45 | Copy the selected region to clipboard and exit.''' 46 | map('Confirm', 'confirm Enter confirm', long_text=long_text) 47 | 48 | long_text = ''' 49 | Cancel selection and move the cursor around the screen. 50 | This will scroll the buffer if needed and possible.''' 51 | map('Move left', 'move Left move left') 52 | map('Move right', 'move Right move right') 53 | map('Move up', 'move Up move up') 54 | map('Move down', 'move Down move down') 55 | map('Move page up', 'move Page_Up move page up') 56 | map('Move page down', 'move Page_Down move page down') 57 | map('Move first', 'move Home move first') 58 | map('Move first nonwhite', 'move a move first nonwhite') 59 | map('Move last nonwhite', 'move End move last nonwhite') 60 | map('Move last', 'move e move last') 61 | map('Move top', 'move Ctrl+Home move top') 62 | map('Move bottom', 'move Ctrl+End move bottom') 63 | map('Move word left', 'move Ctrl+Left move word left') 64 | map('Move word right', 'move Ctrl+Right move word right', long_text=long_text) 65 | 66 | long_text = ''' 67 | Scroll the buffer, if possible. 68 | Cursor stays in the same position relative to the screen.''' 69 | map('Scroll up', 'scroll Ctrl+Up scroll up') 70 | map('Scroll down', 'scroll Ctrl+Down scroll down', long_text=long_text) 71 | 72 | long_text = ''' 73 | #: Extend a stream selection. 74 | #: If no region is selected, start selecting. 75 | #: Stream selection includes all characters between the region ends.''' 76 | map('SelectStream left', 'select_stream Shift+Left select stream left') 77 | map('SelectStream right', 'select_stream Shift+Right select stream right') 78 | map('SelectStream up', 'select_stream Shift+Up select stream up') 79 | map('SelectStream down', 'select_stream Shift+Down select stream down') 80 | map('SelectStream page up', 'select_stream Shift+Page_Up select stream page up') 81 | map('SelectStream page down', 'select_stream Shift+Page_Down select stream page down') 82 | map('SelectStream first', 'select_stream Shift+Home select stream first') 83 | map('SelectStream first nonwhite', 'select_stream A select stream first nonwhite') 84 | map('SelectStream last nonwhite', 'select_stream Shift+End select stream last nonwhite') 85 | map('SelectStream last', 'select_stream E select stream last') 86 | map('SelectStream top', 'select_stream Shift+Ctrl+Home select stream top') 87 | map('SelectStream bottom', 'select_stream Shift+Ctrl+End select stream bottom') 88 | map('SelectStream word left', 'select_stream Shift+Ctrl+Left select stream word left') 89 | map('SelectStream word right', 'select_stream Shift+Ctrl+Right select stream word right', long_text=long_text) 90 | 91 | long_text = ''' 92 | Extend a columnar selection. 93 | If no region is selected, start selecting. 94 | Columnar selection includes characters in the rectangle 95 | defined by the region ends.''' 96 | map('SelectColumnar left', 'select_columnar Alt+Left select columnar left') 97 | map('SelectColumnar right', 'select_columnar Alt+Right select columnar right') 98 | map('SelectColumnar up', 'select_columnar Alt+Up select columnar up') 99 | map('SelectColumnar down', 'select_columnar Alt+Down select columnar down') 100 | map('SelectColumnar page up', 'select_columnar Alt+Page_Up select columnar page up') 101 | map('SelectColumnar page down', 'select_columnar Alt+Page_Down select columnar page down') 102 | map('SelectColumnar first', 'select_columnar Alt+Home select columnar first') 103 | map('SelectColumnar first nonwhite', 'select_columnar Alt+A select columnar first nonwhite') 104 | map('SelectColumnar last nonwhite', 'select_columnar Alt+End select columnar last nonwhite') 105 | map('SelectColumnar last', 'select_columnar Alt+E select columnar last') 106 | map('SelectColumnar top', 'select_columnar Alt+Ctrl+Home select columnar top') 107 | map('SelectColumnar bottom', 'select_columnar Alt+Ctrl+End select columnar bottom') 108 | map('SelectColumnar word left', 'select_columnar Alt+Ctrl+Left select columnar word left') 109 | map('SelectColumnar word right', 'select_columnar Alt+Ctrl+Right select columnar word right', long_text=long_text) 110 | 111 | long_text = ''' 112 | Keys to enable vim-like modal selecting.''' 113 | map('SetMode visual', 'set_mode v set_mode visual') 114 | map('SetMode block', 'set_mode Ctrl+v set_mode block') 115 | map('SetMode normal', 'set_mode Ctrl+LeftBracket set_mode normal', long_text=long_text) 116 | 117 | egr() # }}} 118 | 119 | agr('behavior', 'Behavior') # {{{ 120 | 121 | opt('select_by_word_characters', '', 122 | option_type='str', 123 | long_text=''' 124 | Characters considered part of a word when moving by words. 125 | By default, those are taken from main Kitty config.''') 126 | 127 | egr() # }}} 128 | -------------------------------------------------------------------------------- /kitten_options_types.py: -------------------------------------------------------------------------------- 1 | # generated by gen-config.py DO NOT edit 2 | 3 | import typing 4 | from kitty.conf.utils import KeyAction, KittensKeyMap 5 | import kitty.conf.utils 6 | from kitty.fast_data_types import Color 7 | import kitty.fast_data_types 8 | from kitty.types import ParsedShortcut 9 | import kitty.types 10 | 11 | 12 | option_names = ( # {{{ 13 | 'cursor', 14 | 'map', 15 | 'select_by_word_characters', 16 | 'selection_background', 17 | 'selection_foreground') # }}} 18 | 19 | 20 | class Options: 21 | cursor: Color = Color(173, 127, 168) 22 | select_by_word_characters: str = '' 23 | selection_background: Color = Color(82, 148, 226) 24 | selection_foreground: Color = Color(255, 255, 255) 25 | map: typing.List[typing.Tuple[kitty.types.ParsedShortcut, kitty.conf.utils.KeyAction]] = [] 26 | key_definitions: KittensKeyMap = {} 27 | config_paths: typing.Tuple[str, ...] = () 28 | config_overrides: typing.Tuple[str, ...] = () 29 | 30 | def __init__(self, options_dict: typing.Optional[typing.Dict[str, typing.Any]] = None) -> None: 31 | if options_dict is not None: 32 | null = object() 33 | for key in option_names: 34 | val = options_dict.get(key, null) 35 | if val is not null: 36 | setattr(self, key, val) 37 | 38 | @property 39 | def _fields(self) -> typing.Tuple[str, ...]: 40 | return option_names 41 | 42 | def __iter__(self) -> typing.Iterator[str]: 43 | return iter(self._fields) 44 | 45 | def __len__(self) -> int: 46 | return len(self._fields) 47 | 48 | def _copy_of_val(self, name: str) -> typing.Any: 49 | ans = getattr(self, name) 50 | if isinstance(ans, dict): 51 | ans = ans.copy() 52 | elif isinstance(ans, list): 53 | ans = ans[:] 54 | return ans 55 | 56 | def _asdict(self) -> typing.Dict[str, typing.Any]: 57 | return {k: self._copy_of_val(k) for k in self} 58 | 59 | def _replace(self, **kw: typing.Any) -> "Options": 60 | ans = Options() 61 | for name in self: 62 | setattr(ans, name, self._copy_of_val(name)) 63 | for name, val in kw.items(): 64 | setattr(ans, name, val) 65 | return ans 66 | 67 | def __getitem__(self, key: typing.Union[int, str]) -> typing.Any: 68 | k = option_names[key] if isinstance(key, int) else key 69 | try: 70 | return getattr(self, k) 71 | except AttributeError: 72 | pass 73 | raise KeyError(f"No option named: {k}") 74 | 75 | 76 | defaults = Options() 77 | defaults.map = [ 78 | # quit 79 | (ParsedShortcut(mods=0, key_name='q'), KeyAction('quit')), # noqa 80 | # quit 81 | (ParsedShortcut(mods=0, key_name='ESCAPE'), KeyAction('quit')), # noqa 82 | # confirm 83 | (ParsedShortcut(mods=0, key_name='ENTER'), KeyAction('confirm')), # noqa 84 | # move 85 | (ParsedShortcut(mods=0, key_name='LEFT'), KeyAction('move', ('left',))), # noqa 86 | # move 87 | (ParsedShortcut(mods=0, key_name='RIGHT'), KeyAction('move', ('right',))), # noqa 88 | # move 89 | (ParsedShortcut(mods=0, key_name='UP'), KeyAction('move', ('up',))), # noqa 90 | # move 91 | (ParsedShortcut(mods=0, key_name='DOWN'), KeyAction('move', ('down',))), # noqa 92 | # move 93 | (ParsedShortcut(mods=0, key_name='PAGE_UP'), KeyAction('move', ('page_up',))), # noqa 94 | # move 95 | (ParsedShortcut(mods=0, key_name='PAGE_DOWN'), KeyAction('move', ('page_down',))), # noqa 96 | # move 97 | (ParsedShortcut(mods=0, key_name='HOME'), KeyAction('move', ('first',))), # noqa 98 | # move 99 | (ParsedShortcut(mods=0, key_name='a'), KeyAction('move', ('first_nonwhite',))), # noqa 100 | # move 101 | (ParsedShortcut(mods=0, key_name='END'), KeyAction('move', ('last_nonwhite',))), # noqa 102 | # move 103 | (ParsedShortcut(mods=0, key_name='e'), KeyAction('move', ('last',))), # noqa 104 | # move 105 | (ParsedShortcut(mods=4, key_name='HOME'), KeyAction('move', ('top',))), # noqa 106 | # move 107 | (ParsedShortcut(mods=4, key_name='END'), KeyAction('move', ('bottom',))), # noqa 108 | # move 109 | (ParsedShortcut(mods=4, key_name='LEFT'), KeyAction('move', ('word_left',))), # noqa 110 | # move 111 | (ParsedShortcut(mods=4, key_name='RIGHT'), KeyAction('move', ('word_right',))), # noqa 112 | # scroll 113 | (ParsedShortcut(mods=4, key_name='UP'), KeyAction('scroll', ('up',))), # noqa 114 | # scroll 115 | (ParsedShortcut(mods=4, key_name='DOWN'), KeyAction('scroll', ('down',))), # noqa 116 | # select_stream 117 | (ParsedShortcut(mods=1, key_name='LEFT'), KeyAction('select', ('stream', 'left'))), # noqa 118 | # select_stream 119 | (ParsedShortcut(mods=1, key_name='RIGHT'), KeyAction('select', ('stream', 'right'))), # noqa 120 | # select_stream 121 | (ParsedShortcut(mods=1, key_name='UP'), KeyAction('select', ('stream', 'up'))), # noqa 122 | # select_stream 123 | (ParsedShortcut(mods=1, key_name='DOWN'), KeyAction('select', ('stream', 'down'))), # noqa 124 | # select_stream 125 | (ParsedShortcut(mods=1, key_name='PAGE_UP'), KeyAction('select', ('stream', 'page_up'))), # noqa 126 | # select_stream 127 | (ParsedShortcut(mods=1, key_name='PAGE_DOWN'), KeyAction('select', ('stream', 'page_down'))), # noqa 128 | # select_stream 129 | (ParsedShortcut(mods=1, key_name='HOME'), KeyAction('select', ('stream', 'first'))), # noqa 130 | # select_stream 131 | (ParsedShortcut(mods=0, key_name='A'), KeyAction('select', ('stream', 'first_nonwhite'))), # noqa 132 | # select_stream 133 | (ParsedShortcut(mods=1, key_name='END'), KeyAction('select', ('stream', 'last_nonwhite'))), # noqa 134 | # select_stream 135 | (ParsedShortcut(mods=0, key_name='E'), KeyAction('select', ('stream', 'last'))), # noqa 136 | # select_stream 137 | (ParsedShortcut(mods=5, key_name='HOME'), KeyAction('select', ('stream', 'top'))), # noqa 138 | # select_stream 139 | (ParsedShortcut(mods=5, key_name='END'), KeyAction('select', ('stream', 'bottom'))), # noqa 140 | # select_stream 141 | (ParsedShortcut(mods=5, key_name='LEFT'), KeyAction('select', ('stream', 'word_left'))), # noqa 142 | # select_stream 143 | (ParsedShortcut(mods=5, key_name='RIGHT'), KeyAction('select', ('stream', 'word_right'))), # noqa 144 | # select_columnar 145 | (ParsedShortcut(mods=2, key_name='LEFT'), KeyAction('select', ('columnar', 'left'))), # noqa 146 | # select_columnar 147 | (ParsedShortcut(mods=2, key_name='RIGHT'), KeyAction('select', ('columnar', 'right'))), # noqa 148 | # select_columnar 149 | (ParsedShortcut(mods=2, key_name='UP'), KeyAction('select', ('columnar', 'up'))), # noqa 150 | # select_columnar 151 | (ParsedShortcut(mods=2, key_name='DOWN'), KeyAction('select', ('columnar', 'down'))), # noqa 152 | # select_columnar 153 | (ParsedShortcut(mods=2, key_name='PAGE_UP'), KeyAction('select', ('columnar', 'page_up'))), # noqa 154 | # select_columnar 155 | (ParsedShortcut(mods=2, key_name='PAGE_DOWN'), KeyAction('select', ('columnar', 'page_down'))), # noqa 156 | # select_columnar 157 | (ParsedShortcut(mods=2, key_name='HOME'), KeyAction('select', ('columnar', 'first'))), # noqa 158 | # select_columnar 159 | (ParsedShortcut(mods=2, key_name='A'), KeyAction('select', ('columnar', 'first_nonwhite'))), # noqa 160 | # select_columnar 161 | (ParsedShortcut(mods=2, key_name='END'), KeyAction('select', ('columnar', 'last_nonwhite'))), # noqa 162 | # select_columnar 163 | (ParsedShortcut(mods=2, key_name='E'), KeyAction('select', ('columnar', 'last'))), # noqa 164 | # select_columnar 165 | (ParsedShortcut(mods=6, key_name='HOME'), KeyAction('select', ('columnar', 'top'))), # noqa 166 | # select_columnar 167 | (ParsedShortcut(mods=6, key_name='END'), KeyAction('select', ('columnar', 'bottom'))), # noqa 168 | # select_columnar 169 | (ParsedShortcut(mods=6, key_name='LEFT'), KeyAction('select', ('columnar', 'word_left'))), # noqa 170 | # select_columnar 171 | (ParsedShortcut(mods=6, key_name='RIGHT'), KeyAction('select', ('columnar', 'word_right'))), # noqa 172 | # set_mode 173 | (ParsedShortcut(mods=0, key_name='v'), KeyAction('set_mode', ('visual',))), # noqa 174 | # set_mode 175 | (ParsedShortcut(mods=4, key_name='v'), KeyAction('set_mode', ('block',))), # noqa 176 | # set_mode 177 | (ParsedShortcut(mods=4, key_name='LeftBracket'), KeyAction('set_mode', ('normal',))), # noqa 178 | ] 179 | -------------------------------------------------------------------------------- /_grab_ui.py: -------------------------------------------------------------------------------- 1 | from base64 import b64encode 2 | from functools import total_ordering 3 | from itertools import takewhile 4 | import json 5 | import os.path 6 | import re 7 | import sys 8 | from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, 9 | NamedTuple, Optional, Set, Tuple, Type, Union) 10 | import unicodedata 11 | 12 | from kitty.boss import Boss 13 | from kitty.cli import parse_args 14 | from kitten_options_types import Options, defaults 15 | from kitten_options_parse import create_result_dict, merge_result_dicts, parse_conf_item 16 | from kitty.conf.utils import load_config as _load_config, parse_config_base, resolve_config 17 | from kitty.constants import config_dir 18 | from kitty.fast_data_types import truncate_point_for_length, wcswidth 19 | import kitty.key_encoding as kk 20 | from kitty.key_encoding import KeyEvent 21 | from kitty.rgb import color_as_sgr 22 | from kittens.tui.handler import Handler 23 | from kittens.tui.loop import Loop 24 | 25 | 26 | try: 27 | from kitty.clipboard import set_clipboard_string 28 | except ImportError: 29 | from kitty.fast_data_types import set_clipboard_string 30 | 31 | 32 | if TYPE_CHECKING: 33 | from typing_extensions import TypedDict 34 | ResultDict = TypedDict('ResultDict', {'copy': str}) 35 | 36 | AbsoluteLine = int 37 | ScreenLine = int 38 | ScreenColumn = int 39 | SelectionInLine = Union[Tuple[ScreenColumn, ScreenColumn], 40 | Tuple[None, None]] 41 | 42 | 43 | PositionBase = NamedTuple('Position', [ 44 | ('x', ScreenColumn), ('y', ScreenLine), ('top_line', AbsoluteLine)]) 45 | class Position(PositionBase): 46 | """ 47 | Coordinates of a cell. 48 | 49 | :param x: 0-based, left of window, to the right 50 | :param y: 0-based, top of window, down 51 | :param top_line: 1-based, start of scrollback, down 52 | """ 53 | @property 54 | def line(self) -> AbsoluteLine: 55 | """ 56 | Return 1-based absolute line number. 57 | """ 58 | return self.y + self.top_line 59 | 60 | def moved(self, dx: int = 0, dy: int = 0, 61 | dtop: int = 0) -> 'Position': 62 | """ 63 | Return a new position specified relative to self. 64 | """ 65 | return self._replace(x=self.x + dx, y=self.y + dy, 66 | top_line=self.top_line + dtop) 67 | 68 | def scrolled(self, dtop: int = 0) -> 'Position': 69 | """ 70 | Return a new position equivalent to self 71 | but scrolled dtop lines. 72 | """ 73 | return self.moved(dy=-dtop, dtop=dtop) 74 | 75 | def scrolled_up(self, rows: ScreenLine) -> 'Position': 76 | """ 77 | Return a new position equivalent to self 78 | but with top_line as small as possible. 79 | """ 80 | return self.scrolled(-min(self.top_line - 1, 81 | rows - 1 - self.y)) 82 | 83 | def scrolled_down(self, rows: ScreenLine, 84 | lines: AbsoluteLine) -> 'Position': 85 | """ 86 | Return a new position equivalent to self 87 | but with top_line as large as possible. 88 | """ 89 | return self.scrolled(min(lines - rows + 1 - self.top_line, 90 | self.y)) 91 | 92 | def scrolled_towards(self, other: 'Position', rows: ScreenLine, 93 | lines: Optional[AbsoluteLine] = None) -> 'Position': 94 | """ 95 | Return a new position equivalent to self. 96 | If self and other fit within a single screen, 97 | scroll as little as possible to make both visible. 98 | Otherwise, scroll as much as possible towards other. 99 | """ 100 | # @ 101 | # .| . @| . . 102 | # |.| |. |.| |. |.| 103 | # |*| |*| |*| |*| |*| 104 | # |. |.| |. |.| |@| 105 | # . .| . @| . 106 | # @ 107 | if other.line <= self.line - rows: # above, unreachable 108 | return self.scrolled_up(rows) 109 | if other.line >= self.line + rows: # below, unreachable 110 | assert lines is not None 111 | return self.scrolled_down(rows, lines) 112 | if other.line < self.top_line: # above, reachable 113 | return self.scrolled(other.line - self.top_line) 114 | if other.line > self.top_line + rows - 1: # below, reachable 115 | return self.scrolled(other.line - self.top_line - rows + 1) 116 | return self # visible 117 | 118 | def __str__(self) -> str: 119 | return '{},{}+{}'.format(self.x, self.y, self.top_line) 120 | 121 | def __lt__(self, other: Any) -> bool: 122 | if not isinstance(other, Position): 123 | return NotImplemented 124 | return (self.line, self.x) < (other.line, other.x) 125 | 126 | def __le__(self, other: Any) -> bool: 127 | if not isinstance(other, Position): 128 | return NotImplemented 129 | return (self.line, self.x) <= (other.line, other.x) 130 | 131 | def __gt__(self, other: Any) -> bool: 132 | if not isinstance(other, Position): 133 | return NotImplemented 134 | return (self.line, self.x) > (other.line, other.x) 135 | 136 | def __ge__(self, other: Any) -> bool: 137 | if not isinstance(other, Position): 138 | return NotImplemented 139 | return (self.line, self.x) >= (other.line, other.x) 140 | 141 | def __eq__(self, other: Any) -> bool: 142 | if not isinstance(other, Position): 143 | return NotImplemented 144 | return (self.line, self.x) == (other.line, other.x) 145 | 146 | def __ne__(self, other: Any) -> bool: 147 | if not isinstance(other, Position): 148 | return NotImplemented 149 | return (self.line, self.x) != (other.line, other.x) 150 | 151 | 152 | def _span(line: AbsoluteLine, *lines: AbsoluteLine) -> Set[AbsoluteLine]: 153 | return set(range(min(line, *lines), max(line, *lines) + 1)) 154 | 155 | 156 | class Region: 157 | name = None # type: Optional[str] 158 | uses_mark = False 159 | 160 | @staticmethod 161 | def line_inside_region(current_line: AbsoluteLine, 162 | start: Position, end: Position) -> bool: 163 | """ 164 | Return True if current_line is entirely inside the region 165 | defined by start and end. 166 | """ 167 | return False 168 | 169 | @staticmethod 170 | def line_outside_region(current_line: AbsoluteLine, 171 | start: Position, end: Position) -> bool: 172 | """ 173 | Return True if current_line is entirely outside the region 174 | defined by start and end. 175 | """ 176 | return current_line < start.line or end.line < current_line 177 | 178 | @staticmethod 179 | def adjust(start: Position, end: Position) -> Tuple[Position, Position]: 180 | """ 181 | Return the normalized pair of markers 182 | equivalent to start and end. This is region-type-specific. 183 | """ 184 | return start, end 185 | 186 | @staticmethod 187 | def selection_in_line( 188 | current_line: int, start: Position, end: Position, 189 | maxx: int) -> SelectionInLine: 190 | """ 191 | Return bounds of the part of current_line 192 | that are within the region defined by start and end. 193 | """ 194 | return None, None 195 | 196 | @staticmethod 197 | def lines_affected(mark: Optional[Position], old_point: Position, 198 | point: Position) -> Set[AbsoluteLine]: 199 | """ 200 | Return the set of lines (1-based, top of scrollback, down) 201 | that must be redrawn when point moves from old_point. 202 | """ 203 | return set() 204 | 205 | @staticmethod 206 | def page_up(mark: Optional[Position], point: Position, 207 | rows: ScreenLine, lines: AbsoluteLine) -> Position: 208 | """ 209 | Return the position page up from point. 210 | """ 211 | # ........ 212 | # ....$...| 213 | # ........ ....$...| ........| 214 | # |....$...| |....^...| |....^...| 215 | # |....^...| |........| |........ 216 | # |........| |........ |........ 217 | # ........ ........ ........ 218 | if point.y > 0: 219 | return Position(point.x, 0, point.top_line) 220 | assert point.y == 0 221 | return Position(point.x, 0, 222 | max(1, point.top_line - rows + 1)) 223 | 224 | @staticmethod 225 | def page_down(mark: Optional[Position], point: Position, 226 | rows: ScreenLine, lines: AbsoluteLine) -> Position: 227 | """ 228 | Return the position page down from point. 229 | """ 230 | # ........ ........ ........ 231 | # |........| |........ |........ 232 | # |....^...| |........| |........ 233 | # |....$...| |....^...| |....^...| 234 | # ........ ....$...| ........| 235 | # ....$...| 236 | # ........ 237 | maxy = rows - 1 238 | if point.y < maxy: 239 | return Position(point.x, maxy, point.top_line) 240 | assert point.y == maxy 241 | return Position(point.x, maxy, 242 | min(lines - maxy, point.top_line + maxy)) 243 | 244 | 245 | class NoRegion(Region): 246 | name = 'unselected' 247 | uses_mark = False 248 | 249 | @staticmethod 250 | def line_outside_region(current_line: AbsoluteLine, 251 | start: Position, end: Position) -> bool: 252 | return False 253 | 254 | 255 | class MarkedRegion(Region): 256 | uses_mark = True 257 | 258 | # When a region is marked, 259 | # override page up and down motion 260 | # to keep as much region visible as possible. 261 | # 262 | # This means, 263 | # after computing the position in the usual way, 264 | # do the minimum possible scroll adjustment 265 | # to bring both mark and point on screen. 266 | # If that is not possible, 267 | # do the maximum possible scroll adjustment 268 | # towards mark 269 | # that keeps point on screen. 270 | @staticmethod 271 | def page_up(mark: Optional[Position], point: Position, 272 | rows: ScreenLine, lines: AbsoluteLine) -> Position: 273 | assert mark is not None 274 | return (Region.page_up(mark, point, rows, lines) 275 | .scrolled_towards(mark, rows, lines)) 276 | 277 | @staticmethod 278 | def page_down(mark: Optional[Position], point: Position, 279 | rows: ScreenLine, lines: AbsoluteLine) -> Position: 280 | assert mark is not None 281 | return (Region.page_down(mark, point, rows, lines) 282 | .scrolled_towards(mark, rows, lines)) 283 | 284 | 285 | class StreamRegion(MarkedRegion): 286 | name = 'stream' 287 | 288 | @staticmethod 289 | def line_inside_region(current_line: AbsoluteLine, 290 | start: Position, end: Position) -> bool: 291 | return start.line < current_line < end.line 292 | 293 | @staticmethod 294 | def selection_in_line( 295 | current_line: AbsoluteLine, start: Position, end: Position, 296 | maxx: ScreenColumn) -> SelectionInLine: 297 | if StreamRegion.line_outside_region(current_line, start, end): 298 | return None, None 299 | return (start.x if current_line == start.line else 0, 300 | end.x if current_line == end.line else maxx) 301 | 302 | @staticmethod 303 | def lines_affected(mark: Optional[Position], old_point: Position, 304 | point: Position) -> Set[AbsoluteLine]: 305 | return _span(old_point.line, point.line) 306 | 307 | 308 | class ColumnarRegion(MarkedRegion): 309 | name = 'columnar' 310 | 311 | @staticmethod 312 | def adjust(start: Position, end: Position) -> Tuple[Position, Position]: 313 | return (start._replace(x=min(start.x, end.x)), 314 | end._replace(x=max(start.x, end.x))) 315 | 316 | @staticmethod 317 | def selection_in_line( 318 | current_line: AbsoluteLine, start: Position, end: Position, 319 | maxx: ScreenColumn) -> SelectionInLine: 320 | if ColumnarRegion.line_outside_region(current_line, start, end): 321 | return None, None 322 | return start.x, end.x 323 | 324 | @staticmethod 325 | def lines_affected(mark: Optional[Position], old_point: Position, 326 | point: Position) -> Set[AbsoluteLine]: 327 | assert mark is not None 328 | # If column changes, all lines change. 329 | if old_point.x != point.x: 330 | return _span(mark.line, old_point.line, point.line) 331 | # If point passes mark, all passed lines change except mark line. 332 | if old_point < mark < point or point < mark < old_point: 333 | return _span(old_point.line, point.line) - {mark.line} 334 | # If point moves away from mark, 335 | # all passed lines change except old point line. 336 | elif mark < old_point < point or point < old_point < mark: 337 | return _span(old_point.line, point.line) - {old_point.line} 338 | # Otherwise, point moves toward mark, 339 | # and all passed lines change except new point line. 340 | else: 341 | return _span(old_point.line, point.line) - {point.line} 342 | 343 | 344 | ActionName = str 345 | ActionArgs = tuple 346 | ShortcutMods = int 347 | KeyName = str 348 | Namespace = Any # kitty.cli.Namespace (< 0.17.0) 349 | OptionName = str 350 | OptionValues = Dict[OptionName, Any] 351 | TypeMap = Dict[OptionName, Callable[[Any], Any]] 352 | 353 | 354 | def load_config(*paths: str, overrides: Optional[Iterable[str]] = None) -> Options: 355 | 356 | def parse_config(lines: Iterable[str]) -> Dict[str, Any]: 357 | ans: Dict[str, Any] = create_result_dict() 358 | parse_config_base( 359 | lines, 360 | parse_conf_item, 361 | ans, 362 | ) 363 | return ans 364 | 365 | configs = list(resolve_config('/etc/xdg/kitty/grab.conf', 366 | os.path.join(config_dir, 'grab.conf'), 367 | config_files_on_cmd_line=[])) 368 | overrides = tuple(overrides) if overrides is not None else () 369 | opts_dict, paths = _load_config(defaults, parse_config, merge_result_dicts, *configs, overrides=overrides) 370 | opts = Options(opts_dict) 371 | opts.config_paths = paths 372 | opts.config_overrides = overrides 373 | return opts 374 | 375 | 376 | def unstyled(s: str) -> str: 377 | s = re.sub(r'\x1b\[[0-9;:]*m', '', s) 378 | s = re.sub(r'\x1b\](?:[^\x07\x1b]+|\x1b[^\\])*(?:\x1b\\|\x07)', '', s) 379 | return s 380 | 381 | 382 | def string_slice(s: str, start_x: ScreenColumn, 383 | end_x: ScreenColumn) -> Tuple[str, bool]: 384 | prev_pos = (truncate_point_for_length(s, start_x - 1) if start_x > 0 385 | else None) 386 | start_pos = truncate_point_for_length(s, start_x) 387 | end_pos = truncate_point_for_length(s, end_x - 1) + 1 388 | return s[start_pos:end_pos], prev_pos == start_pos 389 | 390 | 391 | DirectionStr = str 392 | RegionTypeStr = str 393 | ModeTypeStr = str 394 | 395 | 396 | class GrabHandler(Handler): 397 | def __init__(self, args: Namespace, opts: Options, 398 | lines: List[str]) -> None: 399 | super().__init__() 400 | self.args = args 401 | self.opts = opts 402 | self.lines = lines 403 | self.point = Position(args.x, args.y, args.top_line) 404 | self.mark = None # type: Optional[Position] 405 | self.mark_type = NoRegion # type: Type[Region] 406 | self.mode = 'normal' # type: ModeTypeStr 407 | self.result = None # type: Optional[ResultDict] 408 | 409 | # Operating System Command (OSC); command number 52 410 | # c — clipboard 411 | # p — primary 412 | # s — secondary 413 | self.copy_to = {'primary': b'p', 'secondary': b's'}.get(args.copy_to, b'c') 414 | 415 | 416 | for spec, action in self.opts.map: 417 | self.add_shortcut(action, spec) 418 | 419 | def _start_end(self) -> Tuple[Position, Position]: 420 | start, end = sorted([self.point, self.mark or self.point]) 421 | return self.mark_type.adjust(start, end) 422 | 423 | def _draw_line(self, current_line: AbsoluteLine) -> None: 424 | y = current_line - self.point.top_line # type: ScreenLine 425 | line = self.lines[current_line - 1] 426 | clear_eol = '\x1b[m\x1b[K' 427 | sgr0 = '\x1b[m' 428 | 429 | plain = unstyled(line) 430 | selection_sgr = '\x1b[38{};48{}m'.format( 431 | color_as_sgr(self.opts.selection_foreground), 432 | color_as_sgr(self.opts.selection_background)) 433 | start, end = self._start_end() 434 | 435 | # anti-flicker optimization 436 | if self.mark_type.line_inside_region(current_line, start, end): 437 | self.cmd.set_cursor_position(0, y) 438 | self.print('{}{}'.format(selection_sgr, plain), 439 | end=clear_eol) 440 | return 441 | 442 | self.cmd.set_cursor_position(0, y) 443 | self.print('{}{}'.format(sgr0, line), end=clear_eol) 444 | 445 | if self.mark_type.line_outside_region(current_line, start, end): 446 | return 447 | 448 | start_x, end_x = self.mark_type.selection_in_line( 449 | current_line, start, end, wcswidth(plain)) 450 | if start_x is None or end_x is None: 451 | return 452 | 453 | line_slice, half = string_slice(plain, start_x, end_x) 454 | self.cmd.set_cursor_position(start_x - (1 if half else 0), y) 455 | self.print('{}{}'.format(selection_sgr, line_slice), end='') 456 | 457 | def _update(self) -> None: 458 | self.cmd.set_window_title('Grab – {} {} {},{}+{} to {},{}+{}'.format( 459 | self.args.title, 460 | self.mark_type.name, 461 | getattr(self.mark, 'x', None), getattr(self.mark, 'y', None), 462 | getattr(self.mark, 'top_line', None), 463 | self.point.x, self.point.y, self.point.top_line)) 464 | self.cmd.set_cursor_position(self.point.x, self.point.y) 465 | 466 | def _redraw_lines(self, lines: Iterable[AbsoluteLine]) -> None: 467 | for line in lines: 468 | self._draw_line(line) 469 | self._update() 470 | 471 | def _redraw(self) -> None: 472 | self._redraw_lines(range( 473 | self.point.top_line, 474 | self.point.top_line + self.screen_size.rows)) 475 | 476 | def initialize(self) -> None: 477 | self.cmd.set_window_title('Grab – {}'.format(self.args.title)) 478 | self.cmd.set_default_colors(cursor=self.opts.cursor) 479 | self._redraw() 480 | 481 | def perform_default_key_action(self, key_event: KeyEvent) -> bool: 482 | return False 483 | 484 | def on_key_event(self, key_event: KeyEvent, in_bracketed_paste: bool = False) -> None: 485 | action = self.shortcut_action(key_event) 486 | if (key_event.type not in [kk.PRESS, kk.REPEAT] 487 | or action is None): 488 | return 489 | self.perform_action(action) 490 | 491 | def perform_action(self, action: Tuple[ActionName, ActionArgs]) -> None: 492 | func, args = action 493 | getattr(self, func)(*args) 494 | 495 | def quit(self, *args: Any) -> None: 496 | self.quit_loop(1) 497 | 498 | region_types = {'stream': StreamRegion, 499 | 'columnar': ColumnarRegion 500 | } # type: Dict[RegionTypeStr, Type[Region]] 501 | 502 | mode_types = {'normal': NoRegion, 503 | 'visual': StreamRegion, 504 | 'block': ColumnarRegion, 505 | } # type: Dict[ModeTypeStr, Type[Region]] 506 | 507 | def _ensure_mark(self, mark_type: Type[Region] = StreamRegion) -> None: 508 | need_redraw = mark_type is not self.mark_type 509 | self.mark_type = mark_type 510 | self.mark = (self.mark or self.point) if mark_type.uses_mark else None 511 | if need_redraw: 512 | self._redraw() 513 | 514 | def _scroll(self, dtop: int) -> None: 515 | rows = self.screen_size.rows 516 | new_point = self.point.moved(dtop=dtop) 517 | if not (0 < new_point.top_line <= 1 + len(self.lines) - rows): 518 | return 519 | self.point = new_point 520 | self._redraw() 521 | 522 | def scroll(self, direction: DirectionStr) -> None: 523 | self._scroll(dtop={'up': -1, 'down': 1}[direction]) 524 | 525 | def left(self) -> Position: 526 | return self.point.moved(dx=-1) if self.point.x > 0 else self.point 527 | 528 | def right(self) -> Position: 529 | return (self.point.moved(dx=1) 530 | if self.point.x + 1 < self.screen_size.cols 531 | else self.point) 532 | 533 | def up(self) -> Position: 534 | return (self.point.moved(dy=-1) if self.point.y > 0 else 535 | self.point.moved(dtop=-1) if self.point.top_line > 0 else 536 | self.point) 537 | 538 | def down(self) -> Position: 539 | return (self.point.moved(dy=1) 540 | if self.point.y + 1 < self.screen_size.rows 541 | else self.point.moved(dtop=1) 542 | if self.point.line < len(self.lines) 543 | else self.point) 544 | 545 | def page_up(self) -> Position: 546 | return self.mark_type.page_up( 547 | self.mark, self.point, self.screen_size.rows, 548 | max(self.screen_size.rows, len(self.lines))) 549 | 550 | def page_down(self) -> Position: 551 | return self.mark_type.page_down( 552 | self.mark, self.point, self.screen_size.rows, 553 | max(self.screen_size.rows, len(self.lines))) 554 | 555 | def first(self) -> Position: 556 | return Position(0, self.point.y, self.point.top_line) 557 | 558 | def first_nonwhite(self) -> Position: 559 | line = unstyled(self.lines[self.point.line - 1]) 560 | prefix = ''.join(takewhile(str.isspace, line)) 561 | return Position(wcswidth(prefix), self.point.y, self.point.top_line) 562 | 563 | def last_nonwhite(self) -> Position: 564 | line = unstyled(self.lines[self.point.line - 1]) 565 | suffix = ''.join(takewhile(str.isspace, reversed(line))) 566 | return Position(wcswidth(line[:len(line) - len(suffix)]), 567 | self.point.y, self.point.top_line) 568 | 569 | def last(self) -> Position: 570 | return Position(self.screen_size.cols, 571 | self.point.y, self.point.top_line) 572 | 573 | def top(self) -> Position: 574 | return Position(0, 0, 1) 575 | 576 | def bottom(self) -> Position: 577 | x = wcswidth(unstyled(self.lines[-1])) 578 | y = min(len(self.lines) - self.point.top_line, 579 | self.screen_size.rows - 1) 580 | return Position(x, y, len(self.lines) - y) 581 | 582 | def noop(self) -> Position: 583 | return self.point 584 | 585 | @property 586 | def _select_by_word_characters(self) -> str: 587 | return (self.opts.select_by_word_characters 588 | or (json.loads(os.getenv('KITTY_COMMON_OPTS', '{}')) 589 | .get('select_by_word_characters', '@-./_~?&=%+#'))) 590 | 591 | def _is_word_char(self, c: str) -> bool: 592 | return (unicodedata.category(c)[0] in 'LN' 593 | or c in self._select_by_word_characters) 594 | 595 | def _is_word_separator(self, c: str) -> bool: 596 | return (unicodedata.category(c)[0] not in 'LN' 597 | and c not in self._select_by_word_characters) 598 | 599 | def word_left(self) -> Position: 600 | if self.point.x > 0: 601 | line = unstyled(self.lines[self.point.line - 1]) 602 | pos = truncate_point_for_length(line, self.point.x) 603 | pred = (self._is_word_char if self._is_word_char(line[pos - 1]) 604 | else self._is_word_separator) 605 | new_pos = pos - len(''.join(takewhile(pred, reversed(line[:pos])))) 606 | return Position(wcswidth(line[:new_pos]), 607 | self.point.y, self.point.top_line) 608 | if self.point.y > 0: 609 | return Position(wcswidth(unstyled(self.lines[self.point.line - 2])), 610 | self.point.y - 1, self.point.top_line) 611 | if self.point.top_line > 1: 612 | return Position(wcswidth(unstyled(self.lines[self.point.line - 2])), 613 | self.point.y, self.point.top_line - 1) 614 | return self.point 615 | 616 | def word_right(self) -> Position: 617 | line = unstyled(self.lines[self.point.line - 1]) 618 | pos = truncate_point_for_length(line, self.point.x) 619 | if pos < len(line): 620 | pred = (self._is_word_char if self._is_word_char(line[pos]) 621 | else self._is_word_separator) 622 | new_pos = pos + len(''.join(takewhile(pred, line[pos:]))) 623 | return Position(wcswidth(line[:new_pos]), 624 | self.point.y, self.point.top_line) 625 | if self.point.y < self.screen_size.rows - 1: 626 | return Position(0, self.point.y + 1, self.point.top_line) 627 | if self.point.top_line + self.point.y < len(self.lines): 628 | return Position(0, self.point.y, self.point.top_line + 1) 629 | return self.point 630 | 631 | def _select(self, direction: DirectionStr, 632 | mark_type: Type[Region]) -> None: 633 | self._ensure_mark(mark_type) 634 | old_point = self.point 635 | self.point = (getattr(self, direction))() 636 | if self.point.top_line != old_point.top_line: 637 | self._redraw() 638 | else: 639 | self._redraw_lines(self.mark_type.lines_affected( 640 | self.mark, old_point, self.point)) 641 | 642 | def move(self, direction: DirectionStr) -> None: 643 | self._select(direction, self.mode_types[self.mode]) 644 | 645 | def select(self, region_type: RegionTypeStr, 646 | direction: DirectionStr) -> None: 647 | self._select(direction, self.region_types[region_type]) 648 | 649 | def set_mode(self, mode: ModeTypeStr) -> None: 650 | self.mode = mode 651 | self._select('noop', self.mode_types[mode]) 652 | 653 | def confirm(self, *args: Any) -> None: 654 | start, end = self._start_end() 655 | self.result = {'copy': '\n'.join( 656 | line_slice 657 | for line in range(start.line, end.line + 1) 658 | for plain in [unstyled(self.lines[line - 1])] 659 | for start_x, end_x in [self.mark_type.selection_in_line( 660 | line, start, end, len(plain))] 661 | if start_x is not None and end_x is not None 662 | for line_slice, _half in [string_slice(plain, start_x, end_x)])} 663 | self.quit_loop(0) 664 | 665 | 666 | def main(args: List[str]) -> Optional['ResultDict']: 667 | 668 | def ospec() -> str: 669 | return ''' 670 | --copy-to 671 | dest=copy_to 672 | type=str 673 | Copy to: 'clipboard' or 'primary'/selection or 'secondary' buffer 674 | 675 | 676 | --cursor-x 677 | dest=x 678 | type=int 679 | (Internal) Starting cursor column, 0-based. 680 | 681 | 682 | --cursor-y 683 | dest=y 684 | type=int 685 | (Internal) Starting cursor line, 0-based. 686 | 687 | 688 | --top-line 689 | dest=top_line 690 | type=int 691 | (Internal) Window scroll offset, 1-based. 692 | 693 | 694 | --title 695 | (Internal)''' 696 | 697 | try: 698 | args, _rest = parse_args(args[1:], ospec) 699 | tty = open(os.ctermid()) 700 | lines = (sys.stdin.buffer.read().decode('utf-8') 701 | .split('\n')[:-1]) # last line ends with \n, too 702 | sys.stdin = tty 703 | opts = load_config() 704 | handler = GrabHandler(args, opts, lines) 705 | loop = Loop() 706 | loop.loop(handler) 707 | if loop.return_code == 0 and 'copy' in handler.result: 708 | sys.stdout.buffer.write(b''.join((b'\x1b]52;', handler.copy_to, b';', 709 | b64encode(handler.result['copy'].encode('utf-8')), 710 | b'\x1b\\'))) 711 | return {} 712 | except Exception as e: 713 | from kittens.tui.loop import debug 714 | from traceback import format_exc 715 | debug(format_exc()) 716 | raise 717 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------