├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── cursed ├── __init__.py ├── app.py ├── exceptions.py ├── menu.py ├── meta.py └── window.py ├── docs ├── Makefile ├── conf.py └── index.rst ├── examples ├── browser.py ├── menu.py ├── pad.py ├── pad.txt ├── printkey.py ├── scrolls.py ├── state.py └── test.py ├── setup.cfg ├── setup.py └── tests └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | syntax: glob 2 | *.pyc 3 | *.log 4 | build/* 5 | cursed.egg-info/* 6 | dist/* 7 | cursed/.ropeproject/ 8 | .ropeproject/ 9 | venv/ 10 | _build/ 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | cursed 2 | Simplified curses 3 | Copyright (C) 2014 Johan Nestaas 4 | 5 | cursed is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU General Public License 7 | as published by the Free Software Foundation; either version 2 8 | of the License, or (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE README.rst 2 | recursive-include cursed *.py 3 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | cursed!:: 2 | 3 | ______ __ __ ______ ______ ______ _____ 4 | /\ ___\ /\ \/\ \ /\ == \ /\ ___\ /\ ___\ /\ __-. 5 | \ \ \____ \ \ \_\ \ \ \ __< \ \___ \ \ \ __\ \ \ \/\ \ 6 | \ \_____\ \ \_____\ \ \_\ \_\ \/\_____\ \ \_____\ \ \____- 7 | \/_____/ \/_____/ \/_/ /_/ \/_____/ \/_____/ \/____/ 8 | 9 | 10 | Simplified curses interface with concurrency, for quick and sane curses apps. 11 | 12 | Allows easy creation of windows and menus. Code for each window runs concurrently. 13 | 14 | Please see full documentation available here: http://pythonhosted.org/cursed/ 15 | 16 | cursed was tested with Python 3.4 and 2.7, and depends on the Python package six for compatibility. 17 | 18 | Installation 19 | ------------ 20 | 21 | With pip, for the latest stable:: 22 | 23 | $ pip install cursed 24 | 25 | Or from the project root directory:: 26 | 27 | $ python setup.py install 28 | 29 | Usage 30 | ----- 31 | 32 | Example:: 33 | 34 | from cursed import CursedApp, CursedWindow 35 | 36 | # the main context of the curses application 37 | app = CursedApp() 38 | 39 | # Derive from CursedWindow to declare curses windows to be created after app.run() 40 | # It is required to declare X, Y, WIDTH, and HEIGHT for each window. 41 | # You'll want to put the main looping code for each window thread in the `update` class function. 42 | 43 | class MainWindow(CursedWindow): 44 | 45 | # Coordinate for top-left of window. 46 | X, Y = (0, 0) 47 | 48 | # WIDTH and HEIGHT can be 'max' or integers. 49 | WIDTH, HEIGHT = ('max', 'max') 50 | 51 | # Create a default border around the window. 52 | BORDERED = True 53 | 54 | @classmethod 55 | def update(cls): 56 | ''' update runs every tick ''' 57 | 58 | # Hello world printed at x,y of 0,0 59 | cls.addstr('Hello, world!', 0, 0) 60 | 61 | # Get character keycode of keypress, or None. 62 | if cls.getch() == 27: 63 | # Escape was pressed. Quit. 64 | # 'quit' must be triggered for each open window for the program to quit. 65 | # Call cls.trigger('quit') to quit the window you're in, and to quit the other 66 | # declared windows, call OtherWindow.trigger('quit') which will run in that 67 | # window's thread, regardless of where it's called. 68 | cls.trigger('quit') 69 | 70 | # To trigger app to start 71 | result = app.run() 72 | 73 | # check if ctrl-C was pressed 74 | if result.interrupted(): 75 | print('Quit!') 76 | else: 77 | # Raises an exception if any thread ran into a different exception. 78 | result.unwrap() 79 | 80 | Many more examples are available in the root of the repository at examples/ 81 | 82 | Release Notes 83 | ------------- 84 | 85 | :0.2.0: 86 | - exposed gevent.sleep through a classmethod ``cls.sleep(seconds=0)``. 87 | This allows users to fix issues with long running update functions causing other windows to 88 | not respond. 89 | - Added a CursedWindow PAD, like the curses pad. This can have a huge width and height greater than 90 | the terminal width, but allow you to scroll around it. Useful for windows which need only display 91 | a smaller rectange of a larger window, like a map that scrolls around with arrow keys. 92 | :0.1.9: 93 | - fixed the ``write`` and ``getstr`` classmethods, since they called _fix_xy twice 94 | - added info to menu example to explain ``addstr`` in update will overwrite menu display 95 | :0.1.8: 96 | - added tons of documentation and examples 97 | :0.1.7: 98 | - Better CursedMenu API 99 | :0.1.6: 100 | - WIDTH or HEIGHT specified as 'max' will stretch to the full width or height of the terminal 101 | :0.1.5: 102 | - patched issue with returning bytes in getstr 103 | :0.1.4: 104 | - Implemented getstr 105 | :0.1.3: 106 | - Fixed menu to fill up right side with whitespace 107 | :0.1.2: 108 | - fixed menus stealing keypresses 109 | :0.1.1: 110 | - left and right open menus to sides 111 | - refactored menus 112 | :0.1.0: 113 | - implemented menus! 114 | :0.0.2: 115 | - implemented lots from the following: 116 | 1. https://docs.python.org/2/library/curses.html 117 | 2. https://docs.python.org/2/howto/curses.html 118 | :0.0.1: 119 | - Project created 120 | -------------------------------------------------------------------------------- /cursed/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | cursed 3 | 4 | Simplified curses interface with concurrency, for quick and sane curses apps. 5 | Allows easy creation of windows and menus. Code for each window runs concurrently. 6 | 7 | ''' 8 | from cursed.app import CursedApp 9 | from cursed.window import CursedWindow 10 | from cursed.menu import CursedMenu 11 | 12 | __author__ = 'Johan Nestaas ' 13 | __title__ = 'cursed' 14 | __version__ = '0.2.1' 15 | __license__ = 'GPLv3' 16 | __copyright__ = 'Copyright 2016 Johan Nestaas' 17 | __all__ = ['CursedApp', 'CursedWindow', 'CursedMenu'] 18 | -------------------------------------------------------------------------------- /cursed/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | Welcome to cursed! 4 | 5 | This is a simplified wrapper around the curses library to provide an easy API 6 | to create a curses application, with easy concurrency across windows. It 7 | provides a simple menu implementation as well. 8 | 9 | The best way to get started is to look at an example. Here's the 10 | examples/menu.py example from the main repository, with extra comments to 11 | explain the various parts: 12 | 13 | :: 14 | 15 | from cursed import CursedApp, CursedWindow, CursedMenu 16 | 17 | # You instanciate the application through instanciating a CursedApp 18 | app = CursedApp() 19 | 20 | # The way to create windows is by creating classes derived from the 21 | # CursedWindow class. These must have X, Y, WIDTH, and HEIGHT specified 22 | # as class variables. 'max' or an integer value are valid for WIDTH and 23 | # HEIGHT. 24 | # A new gevent thread will be spawned for each window class. 25 | # These act like singletons, and all functions should be class methods. 26 | # The class itself will never be instanciated. 27 | class MainWindow(CursedWindow): 28 | X, Y = (0, 0) 29 | WIDTH, HEIGHT = 'max', 23 30 | 31 | # To create a menubar, you create a CursedMenu instance in a MENU 32 | # class variable. 33 | # You add a menu to it with the add_menu function, and specify the 34 | # title, optional hotkey, and a list of menu items in the form of 35 | # (name, hotkey, callback) or (name, callback). 36 | # Menu items can be chosen by hotkeys or by the arrow keys and enter. 37 | MENU = CursedMenu() 38 | MENU.add_menu('File', key='f', items=[ 39 | ('Save', 's', 'save'), 40 | ('Quit', 'q', 'quit'), 41 | ]) 42 | MENU.add_menu('Edit', key='e', items=[ 43 | ('Copy', 'c', 'copy'), 44 | ('Delete', 'delete') 45 | ]) 46 | 47 | # Decorate your methods with @classmethod since no instance will ever 48 | # be instanciated. 49 | @classmethod 50 | def save(cls): 51 | # cls.addstr will write a string to x and y location (5, 5) 52 | cls.addstr('File->Save', 5, 5) 53 | 54 | @classmethod 55 | def quit(cls): 56 | # The quit function will run before the window exits. 57 | # Killing the window is triggered with cls.trigger('quit'), 58 | # which is the same way to trigger any other function in the 59 | # CursedWindow. 60 | cls.addstr('Quitting', 5, 5) 61 | 62 | @classmethod 63 | def copy(cls): 64 | cls.addstr('edit->copy', 5, 5) 65 | 66 | @classmethod 67 | def delete(cls): 68 | cls.addstr('edit->delete', 5, 5) 69 | 70 | @classmethod 71 | def update(cls): 72 | # The update function will be looped upon, so this is where you 73 | # want to put the main logic. This is what will check for key 74 | # presses, as well as trigger other functions through 75 | # cls.trigger. 76 | # Handle input here, other than what the menu will handle through 77 | # triggering callbacks itself. 78 | cls.addstr('x=10, y=12', 10, 12) 79 | # Press spacebar to open menu 80 | k = cls.getch() 81 | if k == 32: 82 | cls.openmenu() 83 | 84 | 85 | class FooterWindow(CursedWindow): 86 | # This window will appear on the bottom, print the string 87 | # "Press f then q to exit", then quit. The message will stay on the 88 | # screen. 89 | # All windows must have called 'quit' to exit out of the program, or 90 | # simply ctrl-C could be pressed. 91 | X, Y = (0, 23) 92 | WIDTH, HEIGHT = 'max', 1 93 | 94 | @classmethod 95 | def init(cls): 96 | cls.addstr('Press f then q to exit') 97 | cls.refresh() 98 | cls.trigger('quit') 99 | 100 | 101 | # You need to call app.run() to start the application, which handles 102 | # setting up the windows. 103 | result = app.run() 104 | print(result) 105 | # This checks if ctrl-C or similar was pressed to kill the application. 106 | if result.interrupted(): 107 | print('Ctrl-C pressed.') 108 | else: 109 | # This will reraise exceptions that were raised in windows. 110 | result.unwrap() 111 | 112 | That's the essentials of it. Just remember to trigger('quit') to all your 113 | windows if you want it to exit cleanly. 114 | 115 | New in 2.0 116 | ---------- 117 | 118 | Added pads! 119 | 120 | Now, you can specify a pad CursedWindow like so:: 121 | 122 | class MyPad(CursedWindow): 123 | X, Y = 0, 0 124 | WIDTH, HEIGHT = 40, 40 125 | 126 | # set PAD to True 127 | PAD = True 128 | 129 | # the top left of the region to display 130 | PAD_X, PAD_Y = 0, 0 131 | 132 | # the virtual width and height, which you can scroll around to 133 | PAD_WIDTH, PAD_HEIGHT = 500, 500 134 | 135 | @classmethod 136 | def update(cls): 137 | ... 138 | # get new coordinates for top left of region 139 | ... 140 | cls.PAD_X, cls.PAD_Y = top_left_x, top_left_y 141 | ... 142 | # will now display the correct region in a smaller 40x40 display 143 | cls.refresh() 144 | 145 | This is useful for when you might want to do something like scroll through a 146 | map. See examples/pad.py for an example which scrolls through text using the 147 | arrow keys. 148 | ''' 149 | 150 | import sys 151 | import traceback 152 | import gevent 153 | import six 154 | import curses 155 | 156 | from cursed.window import CursedWindowClass 157 | 158 | 159 | class Result(object): 160 | ''' 161 | Result represents the object returned by `app.run()`, which may contain 162 | exception information. 163 | ''' 164 | 165 | def __init__(self): 166 | self.exc_type, self.exc, self.tb = None, None, None 167 | 168 | def _extract_exception(self): 169 | self.exc_type, self.exc, self.tb = sys.exc_info() 170 | 171 | def _extract_thread_exception(self, thread): 172 | self.exc_type, self.exc, self.tb = thread.exc_info 173 | 174 | def unwrap(self): 175 | ''' 176 | Unwraps the `Result`, raising an exception if one exists. 177 | ''' 178 | if self.exc: 179 | six.reraise(self.exc_type, self.exc, self.tb) 180 | 181 | def ok(self): 182 | ''' 183 | Return True if no exception occurred. 184 | ''' 185 | return not bool(self.exc) 186 | 187 | def err(self): 188 | ''' 189 | Returns the exception or None. 190 | ''' 191 | return self.exc if self.exc else None 192 | 193 | def interrupted(self): 194 | ''' 195 | Returns True if the application was interrupted, like through Ctrl-C. 196 | ''' 197 | return self.exc_type is KeyboardInterrupt 198 | 199 | def print_exc(self): 200 | ''' 201 | Prints the exception traceback. 202 | ''' 203 | if self.tb: 204 | traceback.print_tb(self.tb) 205 | 206 | def __repr__(self): 207 | if self.exc_type is None: 208 | return 'Result(OKAY)' 209 | if self.interrupted(): 210 | return 'Result(KeyboardInterrupt)' 211 | return 'Result(%s, message=%s)' % (self.exc_type.__name__, 212 | str(self.exc)) 213 | 214 | 215 | class CursedApp(object): 216 | ''' 217 | The CursedApp is the main class which is used to track windows that are 218 | created and finally run the application. 219 | 220 | The CursedApp is initialized then run in the main function to build the 221 | windows. 222 | 223 | Example: 224 | :: 225 | 226 | from cursed import CursedApp, CursedWindow 227 | 228 | app = CursedApp() 229 | 230 | class MainWindow(CursedWindow): 231 | X, Y = (0, 0) 232 | WIDTH, HEIGHT = ('max', 'max') 233 | 234 | ... 235 | 236 | result = app.run() 237 | result.unwrap() 238 | ''' 239 | 240 | def __init__(self): 241 | ''' 242 | Initializes the CursedApp. No parameters are required. 243 | ''' 244 | self.scr = None 245 | self.menu = None 246 | self.threads = [] 247 | self.windows = None 248 | self.running = True 249 | 250 | def _run_windows(self): 251 | CursedWindowClass._fix_windows(self.MAX_WIDTH, self.MAX_HEIGHT) 252 | self.windows = CursedWindowClass.WINDOWS 253 | self.active_window = None 254 | for i, cw in enumerate(self.windows): 255 | thread = gevent.spawn(cw._cw_run, self, self.window) 256 | cw.THREAD = thread 257 | self.threads += [thread] 258 | 259 | def _input_loop(self): 260 | while self.running: 261 | for cw in self.windows: 262 | if cw.THREAD.exception is not None: 263 | for cw in self.windows: 264 | cw.RUNNING = False 265 | self.running = False 266 | break 267 | if cw.RUNNING and cw.WAIT: 268 | break 269 | else: 270 | self.running = False 271 | break 272 | gevent.sleep(0) 273 | c = self.window.getch() 274 | if c == -1: 275 | continue 276 | for cw in self.windows: 277 | cw.KEY_EVENTS.put(c) 278 | 279 | def run(self): 280 | ''' 281 | Runs all the windows added to the application, and returns a `Result` 282 | object. 283 | 284 | ''' 285 | result = Result() 286 | try: 287 | self.scr = curses.initscr() 288 | self.MAX_HEIGHT, self.MAX_WIDTH = self.scr.getmaxyx() 289 | curses.noecho() 290 | curses.cbreak() 291 | curses.start_color() 292 | curses.use_default_colors() 293 | self.window = self.scr.subwin(0, 0) 294 | self.window.keypad(1) 295 | self.window.nodelay(1) 296 | self._run_windows() 297 | self.threads += [gevent.spawn(self._input_loop)] 298 | gevent.joinall(self.threads) 299 | for thread in self.threads: 300 | if thread.exception: 301 | result._extract_thread_exception(thread) 302 | except KeyboardInterrupt: 303 | result._extract_exception() 304 | except Exception: 305 | result._extract_exception() 306 | finally: 307 | if self.scr is not None: 308 | self.scr.keypad(0) 309 | curses.echo() 310 | curses.nocbreak() 311 | curses.endwin() 312 | return result 313 | -------------------------------------------------------------------------------- /cursed/exceptions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | cursed.exceptions 4 | 5 | Base exceptions used by cursed. 6 | ''' 7 | 8 | 9 | class CursedWindowError(ValueError): 10 | ''' 11 | Raised when you screw up with the initial CursedWindow class variables, 12 | like not setting WIDTH or HEIGHT. 13 | ''' 14 | pass 15 | 16 | 17 | class CursedPadError(ValueError): 18 | ''' 19 | Raised when you screw up setting up a PAD type CursedWindow, either by not 20 | specifying the PAD_WIDTH or PAD_HEIGHT. 21 | ''' 22 | pass 23 | 24 | 25 | class CursedSizeError(RuntimeError): 26 | ''' 27 | Raised when a terminal size issue occurs, such as the menu not fitting in 28 | the width of the screen, or writing text outside of the window. 29 | ''' 30 | pass 31 | 32 | 33 | class CursedCallbackError(RuntimeError): 34 | ''' 35 | Raised when a callback issue occurs, such as triggering a callback that 36 | doesn't exist, example: 37 | :: 38 | 39 | cls.trigger('typo_in_nmae') 40 | ''' 41 | pass 42 | 43 | 44 | class CursedMenuError(RuntimeError): 45 | ''' 46 | Raised when menus aren't initialized correctly. 47 | Check in the CursedMenu documentation or the example projects for examples 48 | of proper creation of menus. 49 | ''' 50 | pass 51 | -------------------------------------------------------------------------------- /cursed/menu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | cursed.menu 4 | 5 | The menu data class. 6 | Most of the menu implementation is actually in the cursed.window module. 7 | ''' 8 | 9 | from cursed.exceptions import CursedMenuError 10 | 11 | 12 | class CursedMenu(object): 13 | ''' 14 | The CursedMenu is the class which is used to initialize all the menus and 15 | items. 16 | ''' 17 | 18 | def __init__(self): 19 | self.menus = [] 20 | 21 | def add_menu(self, title, key=None, items=None): 22 | ''' 23 | This creates a full menu with a title, an optional hotkey, and a list 24 | of items inside the menu, with their name, hotkey and callback. 25 | 26 | Example: 27 | :: 28 | 29 | MENU = CursedMenu('File', key='f', items=[ 30 | ('Save', 's', 'save_callback'), 31 | ('Open', 'open_callback'), 32 | ('Quit', 'q', 'quit'), 33 | ]) 34 | ''' 35 | title = title.strip() 36 | if not title: 37 | raise CursedMenuError('Menu must have a name.') 38 | menu = _Menu(title=title, key=key, items=[]) 39 | if not items: 40 | raise CursedMenuError('Menu must define items inside it.') 41 | menu.add_items(items) 42 | 43 | 44 | class _OpenMenu(object): 45 | 46 | def __init__(self, index=None, title=None, cb_map=None): 47 | self.index = index 48 | self.title = title 49 | self.cb_map = cb_map 50 | 51 | 52 | class _MenuItem(object): 53 | 54 | def __init__(self, name=None, key=None, cb=None): 55 | self.name = name 56 | self.key = key 57 | self.cb = cb 58 | 59 | def __str__(self): 60 | if self.key: 61 | return '[{0}] {1}'.format(self.key, self.name) 62 | return self.name 63 | 64 | 65 | class _Menu(object): 66 | ALL = [] 67 | KEY_MAP = {} 68 | TITLE_MAP = {} 69 | 70 | def __init__(self, title=None, key=None, items=None): 71 | self.title = title 72 | self.key = key 73 | self.items = [] 74 | self.item_map = {} 75 | self.index = len(_Menu.ALL) 76 | self.selected = None 77 | _Menu.ALL += [self] 78 | _Menu.TITLE_MAP[title] = self 79 | if key is not None: 80 | _Menu.KEY_MAP[key] = self 81 | 82 | @classmethod 83 | def clear_select(cls): 84 | for menu in cls.ALL: 85 | menu.selected = None 86 | 87 | def add_item(self, menu_item): 88 | self.items += [menu_item] 89 | self.item_map[menu_item.key] = menu_item 90 | 91 | def add_items(self, args): 92 | for arg in args: 93 | if len(arg) == 2: 94 | name, cb = arg 95 | key = None 96 | elif len(arg) == 3: 97 | name, key, cb = arg 98 | else: 99 | raise CursedMenuError('Format for menu item must be (Title, ' 100 | 'key, function name)') 101 | name = name.strip() 102 | if not name: 103 | raise CursedMenuError('Menu item must have a name.') 104 | self.add_item(_MenuItem(name=name, key=key, cb=cb)) 105 | 106 | def get_cb(self, key): 107 | if key in self.item_map: 108 | return self.item_map[key].cb 109 | return None 110 | 111 | @classmethod 112 | def get_menu_from_key(cls, key): 113 | return _Menu.KEY_MAP.get(key) 114 | 115 | @classmethod 116 | def get_menu_at(cls, i): 117 | if i >= len(_Menu.ALL): 118 | return None 119 | return _Menu.ALL[i] 120 | 121 | @classmethod 122 | def get_menu_from_title(cls, title): 123 | return _Menu.TITLE_MAP.get(title) 124 | 125 | @classmethod 126 | def size(cls): 127 | return len(_Menu.ALL) 128 | 129 | def down(self): 130 | if self.selected is None: 131 | self.selected = self.items[0] 132 | else: 133 | i = self.items.index(self.selected) 134 | i += 1 135 | if i == len(self.items): 136 | i = 0 137 | self.selected = self.items[i] 138 | 139 | def up(self): 140 | if self.selected is None: 141 | self.selected = self.items[-1] 142 | else: 143 | i = self.items.index(self.selected) 144 | i -= 1 145 | if i == -1: 146 | i = len(self.items) - 1 147 | self.selected = self.items[i] 148 | 149 | @classmethod 150 | def right(cls, menu): 151 | if menu is None: 152 | return None 153 | i = cls.ALL.index(menu) 154 | i += 1 155 | if i == len(cls.ALL): 156 | return cls.ALL[0] 157 | return cls.ALL[i] 158 | 159 | @classmethod 160 | def left(cls, menu): 161 | if menu is None: 162 | return None 163 | i = cls.ALL.index(menu) 164 | i -= 1 165 | if i == -1: 166 | return cls.ALL[-1] 167 | return cls.ALL[i] 168 | -------------------------------------------------------------------------------- /cursed/meta.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | cursed.meta 4 | 5 | This contains the metaclass used to decorate all user classes that subclass 6 | CursedWindow, crucial for the curses interface to work. 7 | ''' 8 | from six.moves.queue import Queue 9 | from .exceptions import CursedPadError, CursedWindowError 10 | 11 | BASE_CURSED_CLASSES = ('CursedWindowClass', 'CursedWindow', 'CursedMenu') 12 | 13 | 14 | class CursedWindowClass(type): 15 | ''' 16 | The CursedWindow has this as a metaclass, to keep track of all classes 17 | that inherit from it so that the app can instanciate the correct windows. 18 | ''' 19 | 20 | WINDOWS = [] 21 | 22 | def __new__(cls, name, parents, dct): 23 | new = super(CursedWindowClass, cls).__new__(cls, name, parents, dct) 24 | if name in BASE_CURSED_CLASSES: 25 | return new 26 | new.X = dct.get('X', 0) 27 | new.Y = dct.get('Y', 0) 28 | new.WIDTH = dct.get('WIDTH') 29 | new.HEIGHT = dct.get('HEIGHT') 30 | if new.WIDTH is None or new.HEIGHT is None: 31 | raise CursedWindowError('specify WIDTH and HEIGHT for {name}, ' 32 | 'either as "max" or a positive integer' 33 | .format(name=name)) 34 | new.PAD = dct.get('PAD', False) 35 | new.PAD_WIDTH = dct.get('PAD_WIDTH') 36 | new.PAD_HEIGHT = dct.get('PAD_HEIGHT') 37 | new.PAD_X = dct.get('PAD_X', 0) 38 | new.PAD_Y = dct.get('PAD_Y', 0) 39 | new.BORDERED = dct.get('BORDERED', False) 40 | if new.PAD and (new.PAD_WIDTH is None or new.PAD_HEIGHT is None): 41 | raise CursedPadError('specify PAD_WIDTH and PAD_HEIGHT for {name}' 42 | .format(name=name)) 43 | if new.PAD and new.BORDERED: 44 | raise CursedPadError('{name} cant be both a PAD and BORDERED' 45 | .format(name=name)) 46 | new.SCROLL = dct.get('SCROLL', False) 47 | if new.PAD and new.SCROLL: 48 | raise CursedPadError('{name} cant be both a PAD and SCROLL' 49 | .format(name=name)) 50 | new.WINDOW = None 51 | new.APP = None 52 | new.EVENTS = Queue() 53 | new.RESULTS = Queue() 54 | new.KEY_EVENTS = Queue() 55 | new.WAIT = dct.get('WAIT', True) 56 | new.MENU = dct.get('MENU', None) 57 | new._MENU_MAP = {} 58 | new._OPENED_MENU = None 59 | new._SELECTED_ITEM = None 60 | cls.WINDOWS += [new] 61 | return new 62 | 63 | @classmethod 64 | def _fix_windows(cls, maxw, maxh): 65 | ''' 66 | Fixes all windows for which width or height is specified as 'max'. 67 | ''' 68 | if not cls.WINDOWS: 69 | return 70 | for win in cls.WINDOWS: 71 | if win.WIDTH == 'max': 72 | win.WIDTH = maxw - win.X 73 | if win.HEIGHT == 'max': 74 | win.HEIGHT = maxh - win.Y 75 | -------------------------------------------------------------------------------- /cursed/window.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | cursed.window 4 | 5 | This contains the core logic used by cursed to create the window and offer the 6 | ncurses interface to display everything. 7 | ''' 8 | 9 | import curses 10 | import gevent 11 | import six 12 | from cursed.exceptions import CursedSizeError, CursedCallbackError 13 | from cursed.meta import CursedWindowClass 14 | from cursed.menu import _Menu as Menu 15 | 16 | 17 | @six.add_metaclass(CursedWindowClass) 18 | class CursedWindow(object): 19 | ''' 20 | The CursedWindow should be the parent class of all Window classes you 21 | declare. 22 | Each should have class variables X, Y, WIDTH, and HEIGHT declared. 23 | WIDTH and HEIGHT can be integers or 'max'. 24 | 25 | Each function in a class derived from CursedWindow should be a classmethod, 26 | since no instances of the class will be created. The code will run as the 27 | single class, like a singleton. 28 | ''' 29 | 30 | _CW_WINDOW_SWAP_FUNCS = ( 31 | 'mvwin', 32 | ) 33 | _CW_SCREEN_SWAP_FUNCS = ( 34 | ) 35 | _CW_WINDOW_FUNCS = ( 36 | 'clear', 'deleteln', 'erase', 'insertln', 'border', 37 | 'nodelay', 'notimeout', 'clearok', 'is_linetouched', 'is_wintouched', 38 | ) 39 | _CW_SCREEN_FUNCS = ( 40 | ) 41 | 42 | @classmethod 43 | def sleep(cls, seconds=0): 44 | ''' 45 | Tell the CursedWindow's greenlet to sleep for seconds. 46 | This should be used to allow other CursedWindow's greenlets to execute, 47 | especially if you have long running code in your ``update`` classmethod. 48 | 49 | This is purely a restriction imposed by gevent, the concurrency library 50 | used for cursed. It is not truly parallel, so one long running greenlet 51 | can lock up execution of other windows. Calling cls.sleep() even with 52 | zero seconds (default) will allow other greenlets to start execution 53 | again. 54 | 55 | There is no benefit to calling sleep with a number other than zero. Zero 56 | will allow other greenlets to take over just fine. 57 | 58 | :param seconds: seconds to sleep. default zero is fine. 59 | ''' 60 | return gevent.sleep(seconds) 61 | 62 | @classmethod 63 | def getch(cls): 64 | ''' 65 | Get the integer value for the keypress, such as 27 for escape. 66 | 67 | :return: integer keycode of keypress 68 | ''' 69 | if cls.KEY_EVENTS.empty(): 70 | return None 71 | return cls.KEY_EVENTS.get() 72 | 73 | @classmethod 74 | def getkey(cls): 75 | ''' 76 | Get the key that was pressed, or None. 77 | This is useful to simply check what key was pressed on the keyboard, 78 | ignoring special keys like the arrow keys. 79 | 80 | :return: character specifying key pressed, like 'a' or 'C' 81 | ''' 82 | if cls.KEY_EVENTS.empty(): 83 | return None 84 | nchar = cls.KEY_EVENTS.get() 85 | return chr(nchar) 86 | 87 | @classmethod 88 | def addch(cls, c, x=None, y=None, attr=None): 89 | ''' 90 | Add a character to a position on the screen or at cursor. 91 | 92 | :param c: the character to insert 93 | :param x: optional x value, or current x position 94 | :param y: optional y value, or current y position 95 | :param attr: optional attribute, like 'bold' 96 | ''' 97 | attr = cls._fix_attr(attr) 98 | x, y = cls._fix_xy(x, y) 99 | if isinstance(c, int): 100 | c = chr(c) 101 | if attr is None: 102 | return cls.WINDOW.addch(y, x, c) 103 | else: 104 | return cls.WINDOW.addch(y, x, c, attr) 105 | 106 | @classmethod 107 | def delch(cls, x=None, y=None): 108 | ''' 109 | Delete a character at position, at cursor or specified position. 110 | 111 | :param x: optional x value 112 | :param y: optional y value 113 | ''' 114 | x, y = cls._fix_xy(x, y) 115 | return cls.WINDOW.delch(y, x) 116 | 117 | @classmethod 118 | def getwh(cls): 119 | ''' 120 | Get the width and height of a window. 121 | 122 | :return: (width, height) 123 | ''' 124 | h, w = cls.WINDOW.getmaxyx() 125 | return w, h 126 | 127 | @classmethod 128 | def getxy(cls): 129 | ''' 130 | Get the x and y position of the cursor. 131 | 132 | :return: (x, y) 133 | ''' 134 | y, x = cls.WINDOW.getyx() 135 | if cls.BORDERED: 136 | x -= 1 137 | y -= 1 138 | if cls.MENU: 139 | y -= 1 140 | return x, y 141 | 142 | @classmethod 143 | def inch(cls, x=None, y=None): 144 | ''' 145 | Return the character and attributes of the character at the specified 146 | position in the window or cursor. 147 | 148 | :param x: optional x value 149 | :param y: optional y value 150 | :return: (character, attributes) 151 | ''' 152 | x, y = cls._fix_xy(x, y) 153 | ret = cls.WINDOW.inch(y, x) 154 | char = 0xf & ret 155 | attrs = 0xf0 & ret 156 | return char, attrs 157 | 158 | @classmethod 159 | def insch(cls, ch, x=None, y=None, attr=None): 160 | ''' 161 | Write a character at specified position or cursor, with attributes. 162 | 163 | :param ch: character to insert 164 | :param x: optional x value 165 | :param y: optional y value 166 | :param attr: optional attributes 167 | ''' 168 | x, y = cls._fix_xy(x, y) 169 | attr = cls._fix_attr(attr) 170 | if attr is None: 171 | return cls.WINDOW.insch(y, x, ch) 172 | else: 173 | return cls.WINDOW.insch(y, x, ch, attr) 174 | 175 | @classmethod 176 | def instr(cls, x=None, y=None, n=None): 177 | ''' 178 | Return a string at cursor or specified position. 179 | If n is specified, returns at most n characters. 180 | 181 | :param x: optional x value 182 | :param y: optional y value 183 | :param n: optional max length of string 184 | :return: string at position 185 | ''' 186 | x, y = cls._fix_xy(x, y) 187 | if n is None: 188 | return cls.WINDOW.instr(y, x) 189 | else: 190 | return cls.WINDOW.instr(y, x, n) 191 | 192 | @classmethod 193 | def insstr(cls, s, x=None, y=None, attr=None): 194 | ''' 195 | Insert a string at cursor or specified position. 196 | Cursor is not moved and characters to the right are shifted right. 197 | 198 | :param s: the string 199 | :param x: optional x value 200 | :param y: optional y value 201 | :param attr: optional attributes 202 | ''' 203 | x, y = cls._fix_xy(x, y) 204 | attr = cls._fix_attr(attr) 205 | if attr is None: 206 | return cls.WINDOW.insstr(y, x, s) 207 | else: 208 | return cls.WINDOW.insstr(y, x, s, attr) 209 | 210 | @classmethod 211 | def insnstr(cls, s, x=None, y=None, n=None, attr=None): 212 | ''' 213 | Insert a string at cursor or specified position, at most n characters. 214 | Cursor is not moved and characters to the right are shifted right. 215 | If n is zero, all characters are inserted. 216 | 217 | :param s: the string 218 | :param x: optional x value 219 | :param y: optional y value 220 | :param n: max characters to insert (0 is all) 221 | :param attr: optional attributes 222 | ''' 223 | x, y = cls._fix_xy(x, y) 224 | attr = cls._fix_attr(attr) 225 | n = n if n is not None else cls.WIDTH 226 | if attr is None: 227 | return cls.WINDOW.insnstr(y, x, s, n) 228 | else: 229 | return cls.WINDOW.insnstr(y, x, s, n, attr) 230 | 231 | @classmethod 232 | def nextline(cls): 233 | ''' 234 | Goes to the next line like a carriage return. 235 | ''' 236 | x, y = cls.getxy() 237 | x = 0 238 | x, y = cls._fix_xy(x, y) 239 | if y + 1 == cls.HEIGHT: 240 | if cls.SCROLL: 241 | cls.WINDOW.scroll() 242 | cls.WINDOW.move(y, 0) 243 | else: 244 | raise CursedSizeError('Window %s reached height at %d' % ( 245 | cls.__name__, y + 1)) 246 | else: 247 | cls.WINDOW.move(y + 1, x) 248 | 249 | @classmethod 250 | def write(cls, msg, x=None, y=None): 251 | ''' 252 | Writes a msg to the screen, with optional x and y values. 253 | If newlines are present, it goes to the next line. 254 | 255 | :param msg: the message to print 256 | :param x: optional x value 257 | :param y: optional y value 258 | ''' 259 | x, y = cls._fix_xy(x, y) 260 | for i, line in enumerate(msg.splitlines()): 261 | if y == cls.HEIGHT - 1: 262 | break 263 | if len(line) + x >= cls.WIDTH: 264 | line = line[:cls.WIDTH - x - 1] 265 | cls.WINDOW.addstr(y, x, line) 266 | y += 1 267 | 268 | @classmethod 269 | def _fix_xy(cls, x, y): 270 | win_x, win_y = x, y 271 | curs_y, curs_x = cls.WINDOW.getyx() 272 | if x is None: 273 | win_x = curs_x 274 | if y is None: 275 | win_y = curs_y 276 | if x is not None and cls.BORDERED: 277 | win_x += 1 278 | if y is not None and cls.BORDERED: 279 | win_y += 1 280 | if y is not None and cls.MENU: 281 | win_y += 1 282 | return win_x, win_y 283 | 284 | @classmethod 285 | def _fix_attr(cls, attr): 286 | if isinstance(attr, six.string_types): 287 | return getattr(curses, 'A_%s' % attr.upper()) 288 | return attr 289 | 290 | @classmethod 291 | def addstr(cls, s, x=None, y=None, attr=None): 292 | ''' 293 | write the string onto specified position or cursor, overwriting anything 294 | already at position. 295 | 296 | :param s: string to write 297 | :param x: optional x value 298 | :param y: optional y value 299 | :param attr: optional attributes 300 | ''' 301 | x, y = cls._fix_xy(x, y) 302 | attr = cls._fix_attr(attr) 303 | if attr is None: 304 | return cls.WINDOW.addstr(y, x, s) 305 | else: 306 | return cls.WINDOW.addstr(y, x, s, attr) 307 | 308 | @classmethod 309 | def addnstr(cls, s, x=None, y=None, n=None, attr=None): 310 | ''' 311 | write at most n characters at specified position or cursor. 312 | 313 | :param s: string to write 314 | :param x: optional x value 315 | :param y: optional y value 316 | :param n: max number of characters 317 | :param attr: optional attributes 318 | ''' 319 | x, y = cls._fix_xy(x, y) 320 | attr = cls._fix_attr(attr) 321 | n = cls.WIDTH if n is None else n 322 | if attr is None: 323 | return cls.WINDOW.addnstr(y, x, s, n) 324 | else: 325 | return cls.WINDOW.addnstr(y, x, s, n, attr) 326 | 327 | @classmethod 328 | def getstr(cls, x=None, y=None, prompt=None): 329 | ''' 330 | Get string input from user at position, with optional prompt message. 331 | 332 | :param x: optional x value 333 | :param y: optional y value 334 | :param prompt: message to prompt user with, example: "Name: " 335 | :return: the string the user input 336 | ''' 337 | x, y = cls._fix_xy(x, y) 338 | if prompt is not None: 339 | cls.WINDOW.addstr(y, x, prompt) 340 | x += len(prompt) 341 | curses.echo() 342 | s = cls.WINDOW.getstr(y, x) 343 | curses.noecho() 344 | return s.decode('utf-8') 345 | 346 | @classmethod 347 | def hline(cls, x=None, y=None, char='-', n=None): 348 | ''' 349 | Insert a horizontal line at position, at most n characters or width of 350 | window. 351 | 352 | :param x: optional x value 353 | :param y: optional y value 354 | :param char: the character to print, default '-' 355 | :param n: the number of characters, default rest of width of window 356 | ''' 357 | x, y = cls._fix_xy(x, y) 358 | n = cls.WIDTH if n is None else n 359 | return cls.WINDOW.hline(y, x, char, n) 360 | 361 | @classmethod 362 | def vline(cls, x=None, y=None, char='|', n=None): 363 | ''' 364 | Insert a vertical line at position, at most n characters or height of 365 | window. 366 | 367 | :param x: optional x value 368 | :param y: optional y value 369 | :param char: the character to print, default '|' 370 | :param n: the number of characters, default rest of height of window 371 | ''' 372 | x, y = cls._fix_xy(x, y) 373 | n = cls.HEIGHT if n is None else n 374 | return cls.WINDOW.vline(y, x, char, n) 375 | 376 | @classmethod 377 | def _cw_set_window_func(cls, attr): 378 | setattr(cls, attr, getattr(cls.WINDOW, attr)) 379 | 380 | @classmethod 381 | def _cw_set_screen_func(cls, attr): 382 | setattr(cls, attr, getattr(cls.APP.scr, attr)) 383 | 384 | @classmethod 385 | def _cw_swap_window_func(cls, attr): 386 | func = getattr(cls.WINDOW, attr) 387 | 388 | def new_func(s, x, y, *args, **kwargs): 389 | x, y = cls._fix_xy(x, y) 390 | return func(y, x, *args, **kwargs) 391 | setattr(cls, attr, new_func) 392 | 393 | @classmethod 394 | def _cw_swap_screen_func(cls, attr): 395 | func = getattr(cls.APP.scr, attr) 396 | 397 | def new_func(s, x, y, *args, **kwargs): 398 | x, y = cls._fix_xy(x, y) 399 | return func(y, x, *args, **kwargs) 400 | setattr(cls, attr, new_func) 401 | 402 | @classmethod 403 | def cx(cls, *args): 404 | ''' 405 | Either the x position of cursor, or sets the x position. 406 | Example: 407 | :: 408 | 409 | # gets the x position of cursor 410 | my_x = cls.cx() 411 | 412 | # set the x position to 20 413 | cls.cx(20) 414 | 415 | # moves right 2 spots 416 | cls.cx(cls.cx() + 2) 417 | 418 | :param x: optional x position to move to 419 | :return: if x not specified, returns the x position of cursor 420 | ''' 421 | x, y = cls.getxy() 422 | if not args: 423 | return x 424 | return cls.move(args[0], y) 425 | 426 | @classmethod 427 | def cy(cls, *args): 428 | ''' 429 | Either the y position of cursor, or sets the y position. 430 | Example: 431 | :: 432 | 433 | # gets the y position of cursor 434 | my_y = cls.cy() 435 | 436 | # set the y position to 20 437 | cls.cy(20) 438 | 439 | # moves down 2 spots 440 | cls.cy(cls.cy() + 2) 441 | 442 | :param y: optional y position to move to 443 | :return: if y not specified, returns the y position of cursor 444 | ''' 445 | x, y = cls.getxy() 446 | if not args: 447 | return y 448 | return cls.move(x, args[0]) 449 | 450 | @classmethod 451 | def move(cls, x, y): 452 | ''' 453 | Moves cursor to x and y specified. 454 | 455 | :param x: the x value, required 456 | :param y: the y value, required 457 | ''' 458 | x, y = cls._fix_xy(x, y) 459 | cls.WINDOW.move(y, x) 460 | 461 | @classmethod 462 | def pad_move(cls, x, y): 463 | ''' 464 | Reorients where the top left of the PAD should be, so it knows which 465 | region to display to the user. 466 | 467 | :param x: the x element of the top left of the region to display 468 | :param y: the y element of the top left of the region to display 469 | ''' 470 | cls.PAD_X, cls.PAD_Y = x, y 471 | 472 | @classmethod 473 | def _cw_setup_run(cls, app, window): 474 | cls.RUNNING = True 475 | cls.APP = app 476 | height, width = window.getmaxyx() 477 | if width < cls.WIDTH: 478 | raise CursedSizeError('terminal width is %d and window width is ' 479 | '%d' % (width, cls.WIDTH)) 480 | if height < cls.HEIGHT: 481 | raise CursedSizeError('terminal height is %d and window height ' 482 | 'is %d' % (height, cls.HEIGHT)) 483 | if cls.PAD: 484 | cls.WINDOW = curses.newpad(cls.PAD_HEIGHT, cls.PAD_WIDTH) 485 | else: 486 | cls.WINDOW = window.subwin(cls.HEIGHT, cls.WIDTH, cls.Y, cls.X) 487 | if cls.SCROLL: 488 | cls.WINDOW.scrollok(True) 489 | cls.WINDOW.idlok(1) 490 | if cls.BORDERED: 491 | cls.WINDOW.border() 492 | for attr in cls._CW_WINDOW_FUNCS: 493 | cls._cw_set_window_func(attr) 494 | for attr in cls._CW_SCREEN_FUNCS: 495 | cls._cw_set_screen_func(attr) 496 | for attr in cls._CW_WINDOW_SWAP_FUNCS: 497 | cls._cw_swap_window_func(attr) 498 | for attr in cls._CW_SCREEN_SWAP_FUNCS: 499 | cls._cw_swap_screen_func(attr) 500 | 501 | @classmethod 502 | def redraw(cls): 503 | ''' 504 | Redraws the window. 505 | ''' 506 | cls.erase() 507 | if cls.BORDERED: 508 | cls.WINDOW.border() 509 | if cls.MENU: 510 | cls._cw_menu_display() 511 | cls.refresh() 512 | 513 | @classmethod 514 | def refresh(cls): 515 | if cls.PAD: 516 | # First two arguments the top left of the pad region to be displayed 517 | # Next four arguments represent the minrow, mincol, maxrow, maxcol 518 | # which are the top left on the screen and bottom right. 519 | cls.WINDOW.refresh( 520 | # Which location on the pad we scrolled to 521 | cls.PAD_Y, cls.PAD_X, 522 | # The top left of the pad where it is on the screen 523 | cls.Y, cls.X, 524 | # The bottom right of the pad where it is on the screen 525 | cls.Y + cls.HEIGHT - 1, cls.X + cls.WIDTH - 1 526 | ) 527 | else: 528 | cls.WINDOW.refresh() 529 | 530 | @classmethod 531 | def openmenu(cls): 532 | ''' 533 | Opens the menu, if menu is specified for the window. 534 | ''' 535 | if cls._OPENED_MENU: 536 | return 537 | if not Menu.size(): 538 | return 539 | cls._OPENED_MENU = Menu.get_menu_at(0) 540 | cls.redraw() 541 | 542 | @classmethod 543 | def _cw_handle_events(cls): 544 | while not cls.EVENTS.empty(): 545 | func_name, args, kwargs = cls.EVENTS.get() 546 | if func_name == 'quit': 547 | if hasattr(cls, 'quit') and callable(cls.quit): 548 | result = cls.quit(*args, **kwargs) 549 | cls.RESULTS.put(('quit', args, kwargs, result)) 550 | cls.RUNNING = False 551 | break 552 | if not hasattr(cls, func_name): 553 | raise CursedCallbackError('%s has no function %s' % ( 554 | cls.__name__, func_name)) 555 | func = getattr(cls, func_name) 556 | if not callable(func): 557 | raise CursedCallbackError('%s has no callable %s' % ( 558 | cls.__name__, func_name)) 559 | cls.RESULTS.put( 560 | (func_name, args, kwargs, func(*args, **kwargs)) 561 | ) 562 | 563 | @classmethod 564 | def _cw_menu_display(cls): 565 | x = 0 566 | # Because cls with MENU will add 1 to y in _fix_xy, we need true origin 567 | y = -1 568 | # Makes the menu standout 569 | menu_attrs = curses.A_REVERSE | curses.A_BOLD 570 | saved_pos = cls.getxy() 571 | for menu in Menu.ALL: 572 | # double check we're not going to write out of bounds 573 | if x + len(menu.title) + 2 >= cls.WIDTH: 574 | raise CursedSizeError('Menu %s exceeds width of window: x=%d' % 575 | (menu.title, x)) 576 | y = -1 577 | cls.addstr(menu.title + ' ', x, y, attr=menu_attrs) 578 | mxlen = max([len(str(i)) for i in menu.items]) 579 | if menu is cls._OPENED_MENU: 580 | for item in menu.items: 581 | y += 1 582 | itemstr = str(item) 583 | wspace = (mxlen - len(itemstr)) * ' ' 584 | itemstr = itemstr + wspace 585 | if item is menu.selected: 586 | attr = curses.A_UNDERLINE 587 | else: 588 | attr = curses.A_REVERSE 589 | cls.addstr(itemstr, x, y, attr=attr) 590 | # For the empty space filler 591 | x += len(menu.title) + 2 592 | # color the rest of the top of the window 593 | extra = 2 if cls.BORDERED else 0 594 | cls.addstr(' ' * (cls.WIDTH - x - extra), x, -1, attr=menu_attrs) 595 | cls.move(*saved_pos) 596 | 597 | @classmethod 598 | def _cw_menu_down(cls): 599 | cls._OPENED_MENU.down() 600 | cls.redraw() 601 | 602 | @classmethod 603 | def _cw_menu_up(cls): 604 | cls._OPENED_MENU.up() 605 | cls.redraw() 606 | 607 | @classmethod 608 | def _cw_menu_left(cls): 609 | Menu.clear_select() 610 | cls._OPENED_MENU = Menu.left(cls._OPENED_MENU) 611 | cls.redraw() 612 | 613 | @classmethod 614 | def _cw_menu_right(cls): 615 | Menu.clear_select() 616 | cls._OPENED_MENU = Menu.right(cls._OPENED_MENU) 617 | cls.redraw() 618 | 619 | @classmethod 620 | def _cw_menu_key(cls, k): 621 | cb = cls._OPENED_MENU.get_cb(k) 622 | cls._OPENED_MENU = None 623 | Menu.clear_select() 624 | cls.redraw() 625 | if cb: 626 | # Run callback associated with menu item 627 | cls.trigger(cb) 628 | 629 | @classmethod 630 | def _cw_menu_enter(cls): 631 | cb = None 632 | if cls._OPENED_MENU.selected: 633 | cb = cls._OPENED_MENU.selected.cb 634 | cls._OPENED_MENU = None 635 | Menu.clear_select() 636 | cls.redraw() 637 | if cb: 638 | cls.trigger(cb) 639 | 640 | @classmethod 641 | def _cw_menu_update(cls): 642 | if cls.KEY_EVENTS.empty(): 643 | return None 644 | c = cls.KEY_EVENTS.get() 645 | k = None 646 | if 0 < c < 256: 647 | k = chr(c) 648 | if cls._OPENED_MENU is None: 649 | if k: 650 | cls._OPENED_MENU = Menu.get_menu_from_key(k) 651 | Menu.clear_select() 652 | cls.redraw() 653 | if cls._OPENED_MENU is None: 654 | cls.KEY_EVENTS.put(c) 655 | else: 656 | # If a menu is open, check if they pressed a key or up/down/enter 657 | if k and c != 0xa: 658 | cls._cw_menu_key(k) 659 | elif c == 0x102: 660 | cls._cw_menu_down() 661 | elif c == 0x103: 662 | cls._cw_menu_up() 663 | elif c == 0x104: 664 | cls._cw_menu_right() 665 | elif c == 0x105: 666 | cls._cw_menu_left() 667 | elif c == 0xa: 668 | cls._cw_menu_enter() 669 | else: 670 | # clear the menu 671 | cls._OPENED_MENU = None 672 | Menu.clear_select() 673 | cls.redraw() 674 | 675 | @classmethod 676 | def _cw_run(cls, app, window): 677 | cls._cw_setup_run(app, window) 678 | cls.redraw() 679 | has_update = hasattr(cls, 'update') and callable(cls.update) 680 | if hasattr(cls, 'init') and callable(cls.init): 681 | cls.trigger('init') 682 | while cls.RUNNING: 683 | # Yield to others for a bit 684 | gevent.sleep(0) 685 | if cls.MENU and cls.RUNNING: 686 | cls._cw_menu_update() 687 | cls._cw_handle_events() 688 | if has_update and cls.RUNNING: 689 | cls.update() 690 | 691 | @classmethod 692 | def trigger(cls, func_name, *args, **kwargs): 693 | ''' 694 | Triggers a class function to be run by that window. 695 | This can be run across gevent coroutines to trigger other CursedWindow 696 | classes to run functions in their context. 697 | 698 | This is also used to cause a window to "quit" by running something 699 | like: 700 | :: 701 | 702 | MainWindow.trigger('quit') 703 | 704 | :param func_name: the name of the function to run 705 | :param args: the positional arguments, *args 706 | :param kwargs: the keyword arguments, **kwargs 707 | ''' 708 | cls.EVENTS.put((func_name, args, kwargs)) 709 | 710 | 711 | def _debug(s): 712 | ''' 713 | It's pretty hard to debug with all the threads running updates constantly... 714 | remote-pdb is the best solution besides some debug log hackery. 715 | ''' 716 | with open('debug.log', 'a') as f: 717 | f.write(s + '\n') 718 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/cursed.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/cursed.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/cursed" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/cursed" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # cursed documentation build configuration file, created by 4 | # sphinx-quickstart on Sun May 29 01:31:23 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | sys.path.insert(0, os.path.abspath('..')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | # 'sphinx.ext.coverage', 34 | # 'sphinx.ext.viewcode', 35 | ] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix of source filenames. 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | #source_encoding = 'utf-8-sig' 45 | 46 | # The master toctree document. 47 | master_doc = 'index' 48 | 49 | # General information about the project. 50 | project = u'cursed' 51 | copyright = u'2016, Johan Nestaas' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = '0.1.7' 59 | # The full version, including alpha/beta/rc tags. 60 | release = '0.1.7' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | #language = None 65 | 66 | # There are two options for replacing |today|: either, you set today to some 67 | # non-false value, then it is used: 68 | #today = '' 69 | # Else, today_fmt is used as the format for a strftime call. 70 | #today_fmt = '%B %d, %Y' 71 | 72 | # List of patterns, relative to source directory, that match files and 73 | # directories to ignore when looking for source files. 74 | exclude_patterns = ['_build'] 75 | 76 | # The reST default role (used for this markup: `text`) to use for all 77 | # documents. 78 | #default_role = None 79 | 80 | # If true, '()' will be appended to :func: etc. cross-reference text. 81 | #add_function_parentheses = True 82 | 83 | # If true, the current module name will be prepended to all description 84 | # unit titles (such as .. function::). 85 | #add_module_names = True 86 | 87 | # If true, sectionauthor and moduleauthor directives will be shown in the 88 | # output. They are ignored by default. 89 | #show_authors = False 90 | 91 | # The name of the Pygments (syntax highlighting) style to use. 92 | pygments_style = 'sphinx' 93 | 94 | # A list of ignored prefixes for module index sorting. 95 | #modindex_common_prefix = [] 96 | 97 | # If true, keep warnings as "system message" paragraphs in the built documents. 98 | #keep_warnings = False 99 | 100 | 101 | # -- Options for HTML output ---------------------------------------------- 102 | 103 | # The theme to use for HTML and HTML Help pages. See the documentation for 104 | # a list of builtin themes. 105 | html_theme = 'default' 106 | 107 | # Theme options are theme-specific and customize the look and feel of a theme 108 | # further. For a list of options available for each theme, see the 109 | # documentation. 110 | #html_theme_options = {} 111 | 112 | # Add any paths that contain custom themes here, relative to this directory. 113 | #html_theme_path = [] 114 | 115 | # The name for this set of Sphinx documents. If None, it defaults to 116 | # " v documentation". 117 | #html_title = None 118 | 119 | # A shorter title for the navigation bar. Default is the same as html_title. 120 | #html_short_title = None 121 | 122 | # The name of an image file (relative to this directory) to place at the top 123 | # of the sidebar. 124 | #html_logo = None 125 | 126 | # The name of an image file (within the static path) to use as favicon of the 127 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 128 | # pixels large. 129 | #html_favicon = None 130 | 131 | # Add any paths that contain custom static files (such as style sheets) here, 132 | # relative to this directory. They are copied after the builtin static files, 133 | # so a file named "default.css" will overwrite the builtin "default.css". 134 | html_static_path = ['_static'] 135 | 136 | # Add any extra paths that contain custom files (such as robots.txt or 137 | # .htaccess) here, relative to this directory. These files are copied 138 | # directly to the root of the documentation. 139 | #html_extra_path = [] 140 | 141 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 142 | # using the given strftime format. 143 | #html_last_updated_fmt = '%b %d, %Y' 144 | 145 | # If true, SmartyPants will be used to convert quotes and dashes to 146 | # typographically correct entities. 147 | #html_use_smartypants = True 148 | 149 | # Custom sidebar templates, maps document names to template names. 150 | #html_sidebars = {} 151 | 152 | # Additional templates that should be rendered to pages, maps page names to 153 | # template names. 154 | #html_additional_pages = {} 155 | 156 | # If false, no module index is generated. 157 | #html_domain_indices = True 158 | 159 | # If false, no index is generated. 160 | #html_use_index = True 161 | 162 | # If true, the index is split into individual pages for each letter. 163 | #html_split_index = False 164 | 165 | # If true, links to the reST sources are added to the pages. 166 | #html_show_sourcelink = True 167 | 168 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 169 | #html_show_sphinx = True 170 | 171 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 172 | #html_show_copyright = True 173 | 174 | # If true, an OpenSearch description file will be output, and all pages will 175 | # contain a tag referring to it. The value of this option must be the 176 | # base URL from which the finished HTML is served. 177 | #html_use_opensearch = '' 178 | 179 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 180 | #html_file_suffix = None 181 | 182 | # Output file base name for HTML help builder. 183 | htmlhelp_basename = 'curseddoc' 184 | 185 | 186 | # -- Options for LaTeX output --------------------------------------------- 187 | 188 | latex_elements = { 189 | # The paper size ('letterpaper' or 'a4paper'). 190 | #'papersize': 'letterpaper', 191 | 192 | # The font size ('10pt', '11pt' or '12pt'). 193 | #'pointsize': '10pt', 194 | 195 | # Additional stuff for the LaTeX preamble. 196 | #'preamble': '', 197 | } 198 | 199 | # Grouping the document tree into LaTeX files. List of tuples 200 | # (source start file, target name, title, 201 | # author, documentclass [howto, manual, or own class]). 202 | latex_documents = [ 203 | ('index', 'cursed.tex', u'cursed Documentation', 204 | u'Johan Nestaas', 'manual'), 205 | ] 206 | 207 | # The name of an image file (relative to this directory) to place at the top of 208 | # the title page. 209 | #latex_logo = None 210 | 211 | # For "manual" documents, if this is true, then toplevel headings are parts, 212 | # not chapters. 213 | #latex_use_parts = False 214 | 215 | # If true, show page references after internal links. 216 | #latex_show_pagerefs = False 217 | 218 | # If true, show URL addresses after external links. 219 | #latex_show_urls = False 220 | 221 | # Documents to append as an appendix to all manuals. 222 | #latex_appendices = [] 223 | 224 | # If false, no module index is generated. 225 | #latex_domain_indices = True 226 | 227 | 228 | # -- Options for manual page output --------------------------------------- 229 | 230 | # One entry per manual page. List of tuples 231 | # (source start file, name, description, authors, manual section). 232 | man_pages = [ 233 | ('index', 'cursed', u'cursed Documentation', 234 | [u'Johan Nestaas'], 1) 235 | ] 236 | 237 | # If true, show URL addresses after external links. 238 | #man_show_urls = False 239 | 240 | 241 | # -- Options for Texinfo output ------------------------------------------- 242 | 243 | # Grouping the document tree into Texinfo files. List of tuples 244 | # (source start file, target name, title, author, 245 | # dir menu entry, description, category) 246 | texinfo_documents = [ 247 | ('index', 'cursed', u'cursed Documentation', 248 | u'Johan Nestaas', 'cursed', 'One line description of project.', 249 | 'Miscellaneous'), 250 | ] 251 | 252 | # Documents to append as an appendix to all manuals. 253 | #texinfo_appendices = [] 254 | 255 | # If false, no module index is generated. 256 | #texinfo_domain_indices = True 257 | 258 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 259 | #texinfo_show_urls = 'footnote' 260 | 261 | # If true, do not generate a @detailmenu in the "Top" node's menu. 262 | #texinfo_no_detailmenu = False 263 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | cursed package 2 | ============== 3 | 4 | Submodules 5 | ---------- 6 | 7 | cursed.app module 8 | ----------------- 9 | 10 | .. automodule:: cursed.app 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | cursed.window module 16 | -------------------- 17 | 18 | .. automodule:: cursed.window 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | cursed.exceptions module 24 | -------------------- 25 | 26 | .. automodule:: cursed.exceptions 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | cursed.meta module 32 | -------------------- 33 | 34 | .. automodule:: cursed.meta 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | cursed.menu module 40 | -------------------- 41 | 42 | .. automodule:: cursed.menu 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | 48 | Module contents 49 | --------------- 50 | 51 | .. automodule:: cursed 52 | :members: 53 | :undoc-members: 54 | :show-inheritance: 55 | -------------------------------------------------------------------------------- /examples/browser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import requests 4 | from cursed import CursedApp, CursedWindow, CursedMenu 5 | app = CursedApp() 6 | 7 | 8 | class HeaderWindow(CursedWindow): 9 | X, Y = (0, 0) 10 | WIDTH, HEIGHT = ('max', 3) 11 | MENU = CursedMenu() 12 | MENU.add_menu('File', key='f', items=[ 13 | ('Save response', 's', 'save'), 14 | ('Quit', 'q', 'quit'), 15 | ]) 16 | MENU.add_menu('Browse', key='b', items=[ 17 | ('Open URL', 'o', 'open_url'), 18 | ]) 19 | 20 | @classmethod 21 | def update(cls): 22 | k = cls.getch() 23 | # space bar 24 | if k == 32: 25 | cls.openmenu() 26 | # tab 27 | elif k == 9: 28 | cls.open_url() 29 | 30 | @classmethod 31 | def open_url(cls): 32 | cls.redraw() 33 | url = cls.getstr(0, 1, prompt='URL: ') 34 | if url: 35 | DisplayWindow.trigger('get_request', url) 36 | 37 | @classmethod 38 | def save(cls): 39 | cls.redraw() 40 | if not ( 41 | hasattr(DisplayWindow, 'response') and 42 | DisplayWindow.response.content 43 | ): 44 | cls.addstr('Error: No response content to save yet', 0, 1) 45 | else: 46 | path = cls.getstr(0, 1, prompt='save to file: ') 47 | if path: 48 | cls.redraw() 49 | if os.path.exists(path): 50 | cls.addstr('Error: {0} exists! please save to a new path.' 51 | .format(path), 0, 1) 52 | else: 53 | with open(path, 'wb') as f: 54 | f.write(DisplayWindow.response.content) 55 | cls.addstr('Saved to {0}'.format(path), 0, 1) 56 | else: 57 | cls.redraw() 58 | cls.addstr('Error: please enter a path to a new file.', 0, 1) 59 | 60 | @classmethod 61 | def quit(cls): 62 | DisplayWindow.trigger('quit') 63 | 64 | 65 | class DisplayWindow(CursedWindow): 66 | X, Y = (0, 3) 67 | WIDTH, HEIGHT = ('max', 'max') 68 | BORDERED = True 69 | 70 | @classmethod 71 | def get_request(cls, url): 72 | cls.redraw() 73 | try: 74 | cls.response = requests.get(url) 75 | except Exception as e: 76 | cls.addstr('Error: {0}'.format(e), 0, 0) 77 | else: 78 | cls.write(cls.response.content, 0, 0) 79 | 80 | 81 | result = app.run() 82 | print(result) 83 | if result.interrupted(): 84 | print('Ctrl-C pressed.') 85 | else: 86 | result.unwrap() 87 | -------------------------------------------------------------------------------- /examples/menu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from cursed import CursedApp, CursedWindow, CursedMenu 3 | app = CursedApp() 4 | 5 | 6 | class MainWindow(CursedWindow): 7 | X, Y = (0, 0) 8 | WIDTH, HEIGHT = 'max', 23 9 | 10 | MENU = CursedMenu() 11 | MENU.add_menu('File', key='f', items=[ 12 | ('Save', 's', 'save'), 13 | ('Quit', 'q', 'quit'), 14 | ]) 15 | MENU.add_menu('Edit', key='e', items=[ 16 | ('Copy', 'c', 'copy'), 17 | ('Paste', 'v', 'paste'), 18 | ('Delete', 'delete') 19 | ]) 20 | 21 | @classmethod 22 | def save(cls): 23 | cls.addstr('File->Save', 0, 7) 24 | 25 | @classmethod 26 | def quit(cls): 27 | cls.addstr('Quitting', 0, 7) 28 | 29 | @classmethod 30 | def copy(cls): 31 | cls.addstr('edit->copy', 0, 7) 32 | 33 | @classmethod 34 | def paste(cls): 35 | cls.addstr('edit->paste', 0, 7) 36 | 37 | @classmethod 38 | def delete(cls): 39 | cls.addstr('edit->delete', 0, 7) 40 | 41 | @classmethod 42 | def update(cls): 43 | cls.addstr('x=10, y=12', 10, 12) 44 | # Press spacebar to open menu 45 | cls.addstr('Constantly updating with addstr ', 2, 2) 46 | cls.nextline() 47 | cls.addstr('overwrites the menu.', 2, 3) 48 | cls.addstr('The "Edit" menu should have "Delete"', 2, 4) 49 | cls.addstr('as the third menu item.', 2, 5) 50 | k = cls.getch() 51 | if k == 32: 52 | cls.openmenu() 53 | 54 | 55 | class FooterWindow(CursedWindow): 56 | X, Y = (0, 23) 57 | WIDTH, HEIGHT = 'max', 1 58 | 59 | @classmethod 60 | def init(cls): 61 | cls.addstr('Press f then q to exit') 62 | cls.refresh() 63 | cls.trigger('quit') 64 | 65 | 66 | result = app.run() 67 | print(result) 68 | if result.interrupted(): 69 | print('Ctrl-C pressed.') 70 | else: 71 | result.unwrap() 72 | -------------------------------------------------------------------------------- /examples/pad.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import random 5 | import curses 6 | from cursed import CursedApp, CursedWindow 7 | 8 | this_dir = os.path.dirname(__file__) 9 | text_path = os.path.join(this_dir, 'pad.txt') 10 | 11 | with open(text_path) as f: 12 | cursed_text = f.read() 13 | 14 | app = CursedApp() 15 | 16 | 17 | def old_generate_map(width, height): 18 | noise = [[r for r in range(width)] for i in range(height)] 19 | for y in range(0, height): 20 | for x in range(0, width): 21 | noise[y][x] = ' ' if random.randint(0, 1) == 0 else '#' 22 | return noise 23 | 24 | 25 | def generate_map(width, height): 26 | text = [[r for r in range(width)] for i in range(height)] 27 | ctext = cursed_text.splitlines() 28 | ctext = [x + ' ' for x in ctext] 29 | ctext_w = max(len(s) for s in ctext) 30 | ctext += [' ' * ctext_w] 31 | ctext_h = len(ctext) 32 | for y in range(0, height): 33 | for x in range(0, width): 34 | ym = y % ctext_h 35 | xm = x % ctext_w 36 | line = ctext[ym] 37 | if xm >= len(line): 38 | text[y][x] = ' ' 39 | else: 40 | text[y][x] = line[xm] 41 | return text 42 | 43 | 44 | class MainWindow(CursedWindow): 45 | 46 | X, Y = 0, 0 47 | WIDTH, HEIGHT = 56, 24 48 | BORDERED = True 49 | 50 | @classmethod 51 | def update(cls): 52 | cls.write( 53 | '''This is a sample application with a Pad. 54 | A Pad can be drawn on the screen but represent a small 55 | region of a much wider area, so you can effectively 56 | navigate something like a map. This one on the right 57 | is 100 by 100 even though it's 24x24 size on the 58 | screen. It has random elements drawn on it, and you 59 | can navigate with the arrow keys.''', x=0, y=0) 60 | cls.trigger('quit') 61 | 62 | 63 | class MainPad(CursedWindow): 64 | 65 | X, Y = 56, 0 66 | WIDTH, HEIGHT = 24, 24 67 | PAD = True 68 | PAD_WIDTH, PAD_HEIGHT = 100, 100 69 | PAD_X, PAD_Y = 0, 0 70 | 71 | MAP = generate_map(PAD_WIDTH, PAD_HEIGHT) 72 | 73 | @classmethod 74 | def update(cls): 75 | key = cls.getch() 76 | if key is not None: 77 | if key == curses.KEY_UP: 78 | cls.PAD_Y = max(cls.PAD_Y - 1, 0) 79 | elif key == curses.KEY_DOWN: 80 | cls.PAD_Y = min( 81 | cls.PAD_Y + 1, 82 | cls.PAD_HEIGHT - (cls.HEIGHT + 1) 83 | ) 84 | elif key == curses.KEY_LEFT: 85 | cls.PAD_X = max(cls.PAD_X - 1, 0) 86 | elif key == curses.KEY_RIGHT: 87 | cls.PAD_X = min( 88 | cls.PAD_X + 1, 89 | cls.PAD_WIDTH - (cls.WIDTH + 1) 90 | ) 91 | elif key == ord('q'): 92 | cls.trigger('quit') 93 | for y in range(cls.PAD_Y, cls.PAD_Y + cls.HEIGHT): 94 | s = cls.MAP[y][cls.PAD_X:cls.PAD_X + cls.PAD_HEIGHT] 95 | s = ''.join(x for x in s) 96 | cls.addstr(s, cls.PAD_X, y) 97 | cls.refresh() 98 | 99 | 100 | result = app.run() 101 | result.unwrap() 102 | -------------------------------------------------------------------------------- /examples/pad.txt: -------------------------------------------------------------------------------- 1 | ______ __ __ ______ ______ ______ _____ 2 | /\ ___\ /\ \/\ \ /\ == \ /\ ___\ /\ ___\ /\ __-. 3 | \ \ \____ \ \ \_\ \ \ \ __< \ \___ \ \ \ __\ \ \ \/\ \ 4 | \ \_____\ \ \_____\ \ \_\ \_\ \/\_____\ \ \_____\ \ \____- 5 | \/_____/ \/_____/ \/_/ /_/ \/_____/ \/_____/ \/____/ 6 | -------------------------------------------------------------------------------- /examples/printkey.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from cursed import CursedApp, CursedWindow 3 | 4 | app = CursedApp() 5 | 6 | 7 | class MainWindow(CursedWindow): 8 | WIDTH = 8 9 | HEIGHT = 4 10 | BORDERED = True 11 | 12 | @classmethod 13 | def update(cls): 14 | k = cls.getch() 15 | if k is None: 16 | return 17 | cls.addstr('{:6}'.format(k), x=0, y=0) 18 | cls.addstr('0x{:04x}'.format(k), x=0, y=1) 19 | cls.refresh() 20 | 21 | 22 | result = app.run() 23 | print(result) 24 | if result.interrupted(): 25 | print('Ctrl-C pressed.') 26 | else: 27 | result.unwrap() 28 | -------------------------------------------------------------------------------- /examples/scrolls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from cursed import CursedApp, CursedWindow 3 | app = CursedApp() 4 | 5 | 6 | class ScrollingWindow(CursedWindow): 7 | WIDTH = 'max' 8 | HEIGHT = 23 9 | SCROLL = True 10 | i = 0 11 | 12 | @classmethod 13 | def update(cls): 14 | c = cls.getch() 15 | if c == 27: 16 | cls.trigger('quit') 17 | return 18 | cls.addstr('{}'.format(cls.i)) 19 | cls.nextline() 20 | cls.i += 1 21 | cls.refresh() 22 | 23 | 24 | class FooterWindow(CursedWindow): 25 | WIDTH = 'max' 26 | HEIGHT = 1 27 | Y = 23 28 | 29 | @classmethod 30 | def init(cls): 31 | cls.addstr('Press ESCAPE to exit') 32 | cls.refresh() 33 | cls.trigger('quit') 34 | 35 | 36 | result = app.run() 37 | print(result) 38 | if result.interrupted(): 39 | print('Ctrl-C pressed.') 40 | else: 41 | result.unwrap() 42 | -------------------------------------------------------------------------------- /examples/state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import socket 4 | from datetime import datetime 5 | from cursed import CursedApp, CursedWindow 6 | import requests 7 | 8 | app = CursedApp() 9 | last_time = None 10 | last_ip = None 11 | hostname = socket.gethostname() 12 | username = os.getlogin() 13 | cwd = os.getcwd() 14 | 15 | 16 | def my_ip(): 17 | global last_time, last_ip 18 | now = datetime.now() 19 | if last_time is None or (now - last_time).seconds >= 10: 20 | response = requests.get('http://icanhazip.com') 21 | last_time = now 22 | last_ip = response.content.strip() 23 | return last_ip.decode('utf-8') 24 | 25 | 26 | def my_mem(): 27 | with open('/proc/meminfo') as f: 28 | lines = f.readlines() 29 | return [x.strip() for x in lines if x.startswith('Mem')] 30 | 31 | 32 | class MainWindow(CursedWindow): 33 | X, Y = (0, 0) 34 | WIDTH, HEIGHT = ('max', 23) 35 | BORDERED = True 36 | 37 | @classmethod 38 | def update(cls): 39 | cls.erase() 40 | cls.border() 41 | c = cls.getch() 42 | if c == 27: 43 | cls.trigger('quit') 44 | return 45 | cls.addstr('username: %s' % username, 0, 0) 46 | cls.nextline() 47 | cls.addstr('hostname: %s' % hostname) 48 | cls.nextline() 49 | cls.addstr('cwd: %s' % cwd) 50 | cls.nextline() 51 | cls.addstr('IP addr: %s' % my_ip()) 52 | cls.nextline() 53 | for mem_line in my_mem(): 54 | cls.addstr(mem_line) 55 | cls.nextline() 56 | cls.refresh() 57 | 58 | 59 | class BottomMessage(CursedWindow): 60 | X, Y = (0, 23) 61 | WIDTH, HEIGHT = ('max', 1) 62 | BORDERED = False 63 | 64 | @classmethod 65 | def init(cls): 66 | cls.addstr('Press ESCAPE to quit') 67 | cls.refresh() 68 | cls.trigger('quit') 69 | 70 | 71 | result = app.run() 72 | print(result) 73 | if result.interrupted(): 74 | print('Ctrl-C pressed.') 75 | else: 76 | result.unwrap() 77 | -------------------------------------------------------------------------------- /examples/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from cursed import CursedApp, CursedWindow 3 | 4 | app = CursedApp() 5 | 6 | 7 | class MainWindow(CursedWindow): 8 | X, Y = (0, 0) 9 | WIDTH = 60 10 | HEIGHT = 'max' 11 | BORDERED = True 12 | 13 | @classmethod 14 | def update(cls): 15 | c = cls.getkey() 16 | if c is None: 17 | return 18 | if c == 'q': 19 | cls.trigger('quit') 20 | return 21 | cls.addstr(c * 10, x=0, y=0, attr='reverse') 22 | cls.nextline() 23 | cls.hline(n=10) 24 | cls.refresh() 25 | 26 | 27 | class SideWindow(CursedWindow): 28 | X, Y = (60, 0) 29 | WIDTH = 20 30 | HEIGHT = 'max' 31 | BORDERED = True 32 | 33 | @classmethod 34 | def init(cls): 35 | cls.addstr('foo', 0, 0) 36 | cls.addstr('bar', x=0, y=1, attr='bold') 37 | w, h = cls.getwh() 38 | cls.nextline() 39 | cls.addstr(str(w)) 40 | cls.refresh() 41 | 42 | @classmethod 43 | def update(cls): 44 | c = cls.getkey() 45 | if c is None: 46 | return 47 | if c == 'q': 48 | cls.trigger('quit') 49 | 50 | 51 | result = app.run() 52 | print(result) 53 | if result.interrupted(): 54 | print('Ctrl-C pressed.') 55 | else: 56 | result.unwrap() 57 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [build_sphinx] 2 | source-dir = docs/ 3 | build-dir = docs/_build 4 | all_files = 1 5 | 6 | [upload_sphinx] 7 | upload-dir = docs/_build/html 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | 4 | # cursed 5 | # Simplified curses 6 | 7 | 8 | def read(fname): 9 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 10 | 11 | 12 | setup( 13 | name="cursed", 14 | version="0.2.1", 15 | description="Simplified curses", 16 | author="Johan Nestaas", 17 | author_email="johannestaas@gmail.com", 18 | license="GPLv3+", 19 | keywords="", 20 | url="https://www.bitbucket.org/johannestaas/cursed", 21 | packages=['cursed'], 22 | package_dir={'cursed': 'cursed'}, 23 | long_description=read('README.rst'), 24 | classifiers=[ 25 | # 'Development Status :: 1 - Planning', 26 | # 'Development Status :: 2 - Pre-Alpha', 27 | 'Development Status :: 3 - Alpha', 28 | # 'Development Status :: 4 - Beta', 29 | # 'Development Status :: 5 - Production/Stable', 30 | # 'Development Status :: 6 - Mature', 31 | # 'Development Status :: 7 - Inactive', 32 | 'License :: OSI Approved :: GNU General Public License v3 or later ' 33 | '(GPLv3+)', 34 | 'Environment :: Console', 35 | 'Environment :: X11 Applications :: Qt', 36 | 'Environment :: MacOS X', 37 | 'Environment :: Win32 (MS Windows)', 38 | 'Operating System :: POSIX', 39 | 'Operating System :: MacOS :: MacOS X', 40 | 'Operating System :: Microsoft :: Windows', 41 | 'Programming Language :: Python', 42 | ], 43 | install_requires=[ 44 | 'gevent', 'six', 45 | ], 46 | entry_points={ 47 | # 'console_scripts': [ 48 | # 'cursed=cursed:main', 49 | # ], 50 | }, 51 | # package_data={ 52 | # 'cursed': ['catalog/*.edb'], 53 | # }, 54 | # include_package_data=True, 55 | ) 56 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from cursed import CursedWindow, CursedApp 4 | 5 | app = CursedApp() 6 | 7 | 8 | class LeftWindow(CursedWindow): 9 | X, Y = 0, 0 10 | WIDTH = 24 11 | HEIGHT = 24 12 | BORDERED = True 13 | 14 | @classmethod 15 | def update(cls): 16 | cls.write('N,N', x=None, y=None) 17 | cls.write('0,0', x=0, y=0) 18 | cls.write('1,1', x=1, y=1) 19 | cls.write('2,2', x=2, y=2) 20 | cls.write('N,N', x=None, y=3) 21 | 22 | 23 | class RightWindow(CursedWindow): 24 | X, Y = 24, 0 25 | WIDTH, HEIGHT = 24, 24 26 | BORDERED = True 27 | 28 | @classmethod 29 | def update(cls): 30 | cls.write('N,N', x=None, y=None) 31 | cls.write('0,0', x=0, y=0) 32 | cls.write('1,1', x=1, y=1) 33 | cls.write('2,2', x=2, y=2) 34 | cls.write('N,N', x=None, y=3) 35 | 36 | 37 | class BottomLeftWindow(CursedWindow): 38 | X, Y = 0, 24 39 | WIDTH, HEIGHT = 24, 24 40 | BORDERED = True 41 | 42 | @classmethod 43 | def update(cls): 44 | cls.write('N,N', x=None, y=None) 45 | cls.write('0,0', x=0, y=0) 46 | cls.write('1,1', x=1, y=1) 47 | cls.write('2,2', x=2, y=2) 48 | cls.write('N,N', x=None, y=3) 49 | 50 | 51 | class BottomRightWindow(CursedWindow): 52 | X, Y = 24, 24 53 | WIDTH, HEIGHT = 24, 24 54 | BORDERED = True 55 | 56 | @classmethod 57 | def update(cls): 58 | cls.write('N,N', x=None, y=None) 59 | cls.write('0,0', x=0, y=0) 60 | cls.write('1,1', x=1, y=1) 61 | cls.write('2,2', x=2, y=2) 62 | cls.write('N,N', x=None, y=3) 63 | 64 | 65 | app.run().unwrap() 66 | 67 | --------------------------------------------------------------------------------