tabs.py 13.1 KB
Newer Older
mathieui's avatar
mathieui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
"""
Tabs management module

Provide a class holding the current tabs of the application.
Supported list modification operations:
    - Appending a tab
    - Deleting a tab (and going back to the previous one)
    - Inserting a tab from a position to another
    - Replacing the whole tab list with another (used for rearranging the
      list from outside)

This class holds a cursor to the current tab, which allows:
    - Going left (prev()) or right (next()) in the list, cycling
    - Getting a reference to the current tab
    - Setting the current tab by index or reference

It supports the poezio "gap tab" concept, aka empty tabs taking a space in the
tab list in order to avoid shifting the tab numbers when closing a tab.
Example tab list: [0|1|2|3|4]
We then close the tab 3: [0|1|2|4]
The tab has been closed and replaced with a "gap tab", which the user cannot
switch to, but which avoids shifting numbers (in the case above, the list would
have become [0|1|2|3], with the tab "4" renumbered to "3" if gap tabs are
disabled.
"""

27
from typing import List, Dict, Type, Optional, Union, Tuple
mathieui's avatar
mathieui committed
28
from collections import defaultdict
29
from slixmpp import JID
mathieui's avatar
mathieui committed
30
from poezio import tabs
31
from poezio.events import EventHandler
Jonas Schäfer's avatar
Jonas Schäfer committed
32
from poezio.config import config
mathieui's avatar
mathieui committed
33 34 35 36 37 38 39


class Tabs:
    """
    Tab list class
    """
    __slots__ = [
40 41 42
        '_current_index',
        '_current_tab',
        '_tabs',
43
        '_tab_jids',
44 45 46 47
        '_tab_types',
        '_tab_names',
        '_previous_tab',
        '_events',
mathieui's avatar
mathieui committed
48 49
    ]

50
    def __init__(self, events: EventHandler) -> None:
mathieui's avatar
mathieui committed
51 52 53 54 55 56
        """
        Initialize the Tab List. Even though the list is initially
        empty, all methods are only valid once append() has been called
        once. Otherwise, mayhem is expected.
        """
        # cursor
57 58 59 60 61
        self._current_index = 0  # type: int
        self._current_tab = None  # type: Optional[tabs.Tab]

        self._previous_tab = None  # type: Optional[tabs.Tab]
        self._tabs = []  # type: List[tabs.Tab]
62
        self._tab_jids = dict()  # type: Dict[JID, tabs.Tab]
63 64 65
        self._tab_types = defaultdict(
            list)  # type: Dict[Type[tabs.Tab], List[tabs.Tab]]
        self._tab_names = dict()  # type: Dict[str, tabs.Tab]
66
        self._events = events  # type: EventHandler
mathieui's avatar
mathieui committed
67 68 69 70 71 72 73

    def __len__(self):
        return len(self._tabs)

    def __iter__(self):
        return iter(self._tabs)

Maxime Buquet's avatar
Maxime Buquet committed
74 75 76 77
    def __getitem__(self, index: Union[int, str, slice]):
        if isinstance(index, str):
            return self.by_name(index)
        return self._tabs[index]
mathieui's avatar
mathieui committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91

    def first(self) -> tabs.Tab:
        """Return the Roster tab"""
        return self._tabs[0]

    @property
    def current_index(self) -> int:
        """Current tab index"""
        return self._current_index

    def set_current_index(self, value: int) -> bool:
        """Set the current tab index"""
        if 0 <= value < len(self._tabs):
            tab = self._tabs[value]
92
            return self.set_current_tab(tab)
mathieui's avatar
mathieui committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106
        return False

    @property
    def current_tab(self) -> Optional[tabs.Tab]:
        """Current tab"""
        return self._current_tab

    def set_current_tab(self, tab: tabs.Tab) -> bool:
        """Set the current tab"""
        if (not isinstance(tab, tabs.GapTab)
                and 0 <= tab.nb < len(self._tabs)):
            self._store_previous()
            self._current_index = tab.nb
            self._current_tab = tab
107 108 109 110
            self._events.trigger(
                'tab_change',
                old_tab=self._previous_tab,
                new_tab=self._current_tab)
mathieui's avatar
mathieui committed
111 112 113 114 115 116 117
            return True
        return False

    def get_tabs(self) -> List[tabs.Tab]:
        """Return the tab list"""
        return self._tabs

118 119 120 121
    def by_jid(self, jid: JID) -> Optional[tabs.Tab]:
        """Get a tab with a specific jid"""
        return self._tab_jids.get(jid)

122
    def by_name(self, name: str) -> Optional[tabs.Tab]:
mathieui's avatar
mathieui committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        """Get a tab with a specific name"""
        return self._tab_names.get(name)

    def by_class(self, cls: Type[tabs.Tab]) -> List[tabs.Tab]:
        """Get all the tabs of a class"""
        return self._tab_types.get(cls, [])

    def find_match(self, name: str) -> Optional[tabs.Tab]:
        """Get a tab using extended matching (tab.matching_name())"""

        def transform(tab_index):
            """Wrap the value of the range around the current index"""
            return (tab_index + self._current_index + 1) % len(self._tabs)

        for i in map(transform, range(len(self._tabs) - 1)):
            for tab_name in self._tabs[i].matching_names():
                if tab_name[1] and name in tab_name[1].lower():
                    return self._tabs[i]
        return None

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    def find_by_unique_prefix(self, prefix: str) -> Tuple[bool, Optional[tabs.Tab]]:
        """
        Get a tab by its unique name prefix, ignoring case.

        :return: A tuple indicating the presence of any match, as well as the
            uniquely matched tab (if any).

        The first element, a boolean, in the returned tuple indicates whether
        at least one tab matched.

        The second element (a Tab) in the returned tuple is the uniquely
        matched tab, if any. If multiple or no tabs match the prefix, the
        second element in the tuple is :data:`None`.
        """

        # TODO: should this maybe use something smarter than .lower()?
        # something something stringprep?
        prefix = prefix.lower()
        candidate = None
        any_matched = False
        for tab in self._tabs:
            if not tab.name.lower().startswith(prefix):
                continue
            any_matched = True
            if candidate is not None:
                # multiple tabs match -> return None
                return True, None
            candidate = tab

        return any_matched, candidate

mathieui's avatar
mathieui committed
174 175 176 177 178 179 180 181 182 183
    def by_name_and_class(self, name: str,
                          cls: Type[tabs.Tab]) -> Optional[tabs.Tab]:
        """Get a tab with its name and class"""
        cls_tabs = self._tab_types.get(cls, [])
        for tab in cls_tabs:
            if tab.name == name:
                return tab
        return None

    def _rebuild(self):
184
        self._tab_jids = dict()
mathieui's avatar
mathieui committed
185 186 187
        self._tab_types = defaultdict(list)
        self._tab_names = dict()
        for tab in self._tabs:
mathieui's avatar
mathieui committed
188 189
            for cls in _get_tab_types(tab):
                self._tab_types[cls].append(tab)
190 191
            if hasattr(tab, 'jid'):
                self._tab_jids[tab.jid] = tab
mathieui's avatar
mathieui committed
192 193 194
            self._tab_names[tab.name] = tab
        self._update_numbers()

mathieui's avatar
mathieui committed
195
    def replace_tabs(self, new_tabs: List[tabs.Tab]) -> bool:
mathieui's avatar
mathieui committed
196 197 198 199
        """
        Replace the current tab list with another, and
        rebuild the mappings.
        """
mathieui's avatar
mathieui committed
200 201
        if self._current_tab not in new_tabs:
            return False
mathieui's avatar
mathieui committed
202 203
        self._tabs = new_tabs
        self._rebuild()
mathieui's avatar
mathieui committed
204
        return True
mathieui's avatar
mathieui committed
205 206

    def _inc_cursor(self):
mathieui's avatar
mathieui committed
207
        self._current_index = (self._current_index + 1) % len(self._tabs)
mathieui's avatar
mathieui committed
208 209 210
        self._current_tab = self._tabs[self._current_index]

    def _dec_cursor(self):
mathieui's avatar
mathieui committed
211
        self._current_index = (self._current_index - 1) % len(self._tabs)
mathieui's avatar
mathieui committed
212 213 214 215 216 217 218 219 220 221 222
        self._current_tab = self._tabs[self._current_index]

    def _store_previous(self):
        self._previous_tab = self._current_tab

    def next(self):
        """Go to the right of the tab list (circular)"""
        self._store_previous()
        self._inc_cursor()
        while isinstance(self.current_tab, tabs.GapTab):
            self._inc_cursor()
223 224 225 226
        self._events.trigger(
            'tab_change',
            old_tab=self._previous_tab,
            new_tab=self._current_tab)
mathieui's avatar
mathieui committed
227 228 229 230 231 232 233

    def prev(self):
        """Go to the left of the tab list (circular)"""
        self._store_previous()
        self._dec_cursor()
        while isinstance(self.current_tab, tabs.GapTab):
            self._dec_cursor()
234 235 236 237
        self._events.trigger(
            'tab_change',
            old_tab=self._previous_tab,
            new_tab=self._current_tab)
mathieui's avatar
mathieui committed
238 239 240 241 242 243 244 245 246 247 248

    def append(self, tab: tabs.Tab):
        """
        Add a tab to the list
        """
        if not self._tabs:
            tab.nb = 0
            self._current_tab = tab
        else:
            tab.nb = self._tabs[-1].nb + 1
        self._tabs.append(tab)
mathieui's avatar
mathieui committed
249 250
        for cls in _get_tab_types(tab):
            self._tab_types[cls].append(tab)
251 252
        if hasattr(tab, 'jid'):
            self._tab_jids[tab.jid] = tab
mathieui's avatar
mathieui committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266
        self._tab_names[tab.name] = tab

    def delete(self, tab: tabs.Tab, gap=False):
        """Remove a tab"""
        if isinstance(tab, tabs.RosterInfoTab):
            return

        if gap:
            self._tabs[tab.nb] = tabs.GapTab(None)
        else:
            self._tabs.remove(tab)

        is_current = tab is self.current_tab

mathieui's avatar
mathieui committed
267 268
        for cls in _get_tab_types(tab):
            self._tab_types[cls].remove(tab)
269 270
        if hasattr(tab, 'jid'):
            del self._tab_jids[tab.jid]
mathieui's avatar
mathieui committed
271
        del self._tab_names[tab.name]
mathieui's avatar
mathieui committed
272 273 274 275 276 277

        if gap:
            self._collect_trailing_gaptabs()
        else:
            self._update_numbers()

mathieui's avatar
mathieui committed
278 279
        if tab is self._previous_tab:
            self._previous_tab = None
mathieui's avatar
mathieui committed
280
        if is_current:
281
            self.restore_previous_tab()
282
            self._previous_tab = None
mathieui's avatar
mathieui committed
283 284
        self._validate_current_index()

285 286 287
    def restore_previous_tab(self):
        """Restore the previous tab"""

mathieui's avatar
mathieui committed
288 289 290
        if self._previous_tab:
            if not self.set_current_tab(self._previous_tab):
                self.set_current_index(0)
mathieui's avatar
mathieui committed
291 292
        else:
            self.set_current_index(0)
mathieui's avatar
mathieui committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

    def _validate_current_index(self):
        if not 0 <= self._current_index < len(
                self._tabs) or not self.current_tab:
            self.prev()

    def _collect_trailing_gaptabs(self):
        """Remove trailing gap tabs if any"""
        i = len(self._tabs) - 1
        while isinstance(self._tabs[i], tabs.GapTab):
            self._tabs.pop()
            i -= 1

    def _update_numbers(self):
        for i, tab in enumerate(self._tabs):
            tab.nb = i
mathieui's avatar
mathieui committed
309
        self._current_index = self._current_tab.nb
mathieui's avatar
mathieui committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

    # Moving tabs around #

    def update_gaps(self, enable_gaps: bool):
        """
        Remove the present gaps from the list if enable_gaps is False.
        """
        if not enable_gaps:
            self._tabs = [tab for tab in self._tabs if tab]
            self._update_numbers()

    def _insert_nogaps(self, old_pos: int, new_pos: int) -> bool:
        """
        Move tabs without creating gaps
        old_pos: old position of the tab
        new_pos: desired position of the tab
        """
        tab = self._tabs[old_pos]
        if new_pos < old_pos:
            self._tabs.pop(old_pos)
            self._tabs.insert(new_pos, tab)
        elif new_pos > old_pos:
            self._tabs.insert(new_pos, tab)
            self._tabs.remove(tab)
        else:
            return False
        return True

    def _insert_gaps(self, old_pos: int, new_pos: int) -> bool:
        """
        Move tabs and create gaps in the eventual remaining space
        old_pos: old position of the tab
        new_pos: desired position of the tab
        """
        tab = self._tabs[old_pos]
        target = None if new_pos >= len(self._tabs) else self._tabs[new_pos]
        if not target:
            if new_pos < len(self._tabs):
                old_tab = self._tabs[old_pos]
                self._tabs[new_pos], self._tabs[
350
                    old_pos] = old_tab, tabs.GapTab(None)
mathieui's avatar
mathieui committed
351 352
            else:
                self._tabs.append(self._tabs[old_pos])
353
                self._tabs[old_pos] = tabs.GapTab(None)
mathieui's avatar
mathieui committed
354 355 356
        else:
            if new_pos > old_pos:
                self._tabs.insert(new_pos, tab)
357
                self._tabs[old_pos] = tabs.GapTab(None)
mathieui's avatar
mathieui committed
358
            elif new_pos < old_pos:
359
                self._tabs[old_pos] = tabs.GapTab(None)
mathieui's avatar
mathieui committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
                self._tabs.insert(new_pos, tab)
            else:
                return False
            i = self._tabs.index(tab)
            done = False
            # Remove the first Gap on the right in the list
            # in order to prevent global shifts when there is empty space
            while not done:
                i += 1
                if i >= len(self._tabs):
                    done = True
                elif not self._tabs[i]:
                    self._tabs.pop(i)
                    done = True
        self._collect_trailing_gaptabs()
        return True

    def insert_tab(self, old_pos: int, new_pos=99999, gaps=False) -> bool:
        """
        Insert a tab at a position, changing the number of the following tabs
        returns False if it could not move the tab, True otherwise
        """
        if (old_pos <= 0 or old_pos >= len(self._tabs) or new_pos <= 0
                or new_pos == old_pos or not self._tabs[old_pos]):
            return False
        if gaps:
            result = self._insert_gaps(old_pos, new_pos)
        else:
            result = self._insert_nogaps(old_pos, new_pos)
        self._update_numbers()
        return result
mathieui's avatar
mathieui committed
391 392 393 394 395 396 397 398 399 400


def _get_tab_types(tab: tabs.Tab) -> List[Type[tabs.Tab]]:
    """Return all parent classes of a tab type"""
    types = []
    current_cls = tab.__class__
    while current_cls != tabs.Tab:
        types.append(current_cls)
        current_cls = current_cls.__bases__[0]
    return types