Curses.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. # Curses-based interfaces
  2. # Copyright (C) 2003-2016 John Goerzen & contributors.
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. from threading import RLock, currentThread, Lock, Event
  18. from collections import deque
  19. import time
  20. import sys
  21. import os
  22. import curses
  23. import logging
  24. from offlineimap.ui.UIBase import UIBase
  25. from offlineimap.threadutil import ExitNotifyThread
  26. import offlineimap
  27. class CursesUtil:
  28. def __init__(self, *args, **kwargs):
  29. # iolock protects access to the
  30. self.iolock = RLock()
  31. self.tframe_lock = RLock()
  32. # tframe_lock protects the self.threadframes manipulation to
  33. # only happen from 1 thread.
  34. self.colormap = {}
  35. """dict, translating color string to curses color pair number"""
  36. def curses_colorpair(self, col_name):
  37. """Return the curses color pair, that corresponds to the color."""
  38. return curses.color_pair(self.colormap[col_name])
  39. def init_colorpairs(self):
  40. """Initialize the curses color pairs available."""
  41. # set special colors 'gray' and 'banner'
  42. self.colormap['white'] = 0 #hardcoded by curses
  43. curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
  44. self.colormap['banner'] = 1 # color 'banner' for bannerwin
  45. bcol = curses.COLOR_BLACK
  46. colors = ( # name, color, bold?
  47. ('black', curses.COLOR_BLACK, False),
  48. ('blue', curses.COLOR_BLUE,False),
  49. ('red', curses.COLOR_RED, False),
  50. ('purple', curses.COLOR_MAGENTA, False),
  51. ('cyan', curses.COLOR_CYAN, False),
  52. ('green', curses.COLOR_GREEN, False),
  53. ('orange', curses.COLOR_YELLOW, False))
  54. #set the rest of all colors starting at pair 2
  55. i = 1
  56. for name, fcol, bold in colors:
  57. i += 1
  58. self.colormap[name] = i
  59. curses.init_pair(i, fcol, bcol)
  60. def lock(self, block=True):
  61. """Locks the Curses ui thread.
  62. Can be invoked multiple times from the owning thread. Invoking
  63. from a non-owning thread blocks and waits until it has been
  64. unlocked by the owning thread."""
  65. return self.iolock.acquire(block)
  66. def unlock(self):
  67. """Unlocks the Curses ui thread.
  68. Decrease the lock counter by one and unlock the ui thread if the
  69. counter reaches 0. Only call this method when the calling
  70. thread owns the lock. A RuntimeError is raised if this method is
  71. called when the lock is unlocked."""
  72. self.iolock.release()
  73. def exec_locked(self, target, *args, **kwargs):
  74. """Perform an operation with full locking."""
  75. self.lock()
  76. try:
  77. target(*args, **kwargs)
  78. finally:
  79. self.unlock()
  80. def refresh(self):
  81. def lockedstuff():
  82. curses.panel.update_panels()
  83. curses.doupdate()
  84. self.exec_locked(lockedstuff)
  85. def isactive(self):
  86. return hasattr(self, 'stdscr')
  87. class CursesAccountFrame:
  88. """Notable instance variables:
  89. - account: corresponding Account()
  90. - children
  91. - ui
  92. - key
  93. - window: curses window associated with an account
  94. """
  95. def __init__(self, ui, account):
  96. """
  97. :param account: An Account() or None (for eg SyncrunnerThread)"""
  98. self.children = []
  99. self.account = account if account else '*Control'
  100. self.ui = ui
  101. self.window = None
  102. # Curses window associated with this acc.
  103. self.acc_num = None
  104. # Account number (& hotkey) associated with this acc.
  105. self.location = 0
  106. # length of the account prefix string
  107. def drawleadstr(self, secs = 0):
  108. """Draw the account status string.
  109. secs tells us how long we are going to sleep."""
  110. sleepstr = '%3d:%02d'% (secs // 60, secs % 60) if secs else 'active'
  111. accstr = '%s: [%s] %12.12s: '% (self.acc_num, sleepstr, self.account)
  112. self.ui.exec_locked(self.window.addstr, 0, 0, accstr)
  113. self.location = len(accstr)
  114. def setwindow(self, curses_win, acc_num):
  115. """Register an curses win and a hotkey as Account window.
  116. :param curses_win: the curses window associated with an account
  117. :param acc_num: int denoting the hotkey associated with this account."""
  118. self.window = curses_win
  119. self.acc_num = acc_num
  120. self.drawleadstr()
  121. self.ui.exec_locked(self.window.noutrefresh)
  122. # Update the child ThreadFrames
  123. for child in self.children:
  124. child.update(curses_win, self.location, 0)
  125. self.location += 1
  126. def get_new_tframe(self):
  127. """Create a new ThreadFrame and append it to self.children.
  128. :returns: The new ThreadFrame"""
  129. tf = CursesThreadFrame(self.ui, self.window, self.location, 0)
  130. self.location += 1
  131. self.children.append(tf)
  132. return tf
  133. def sleeping(self, sleepsecs, remainingsecs):
  134. """Show how long we are going to sleep and sleep.
  135. :returns: Boolean, whether we want to abort the sleep"""
  136. self.drawleadstr(remainingsecs)
  137. self.ui.exec_locked(self.window.refresh)
  138. time.sleep(sleepsecs)
  139. return self.account.get_abort_event()
  140. def syncnow(self):
  141. """Request that we stop sleeping asap and continue to sync."""
  142. # if this belongs to an Account (and not *Control), set the
  143. # skipsleep pref
  144. if isinstance(self.account, offlineimap.accounts.Account):
  145. self.ui.info("Requested synchronization for acc: %s"% self.account)
  146. self.account.config.set('Account %s'% self.account.name,
  147. 'skipsleep', '1')
  148. class CursesThreadFrame:
  149. """curses_color: current color pair for logging."""
  150. def __init__(self, ui, acc_win, x, y):
  151. """
  152. :param ui: is a Blinkenlights() instance
  153. :param acc_win: curses Account window"""
  154. self.ui = ui
  155. self.window = acc_win
  156. self.x = x
  157. self.y = y
  158. self.curses_color = curses.color_pair(0) #default color
  159. def setcolor(self, color, modifier=0):
  160. """Draw the thread symbol '@' in the specified color
  161. :param modifier: Curses modified, such as curses.A_BOLD
  162. """
  163. self.curses_color = modifier | self.ui.curses_colorpair(color)
  164. self.colorname = color
  165. self.display()
  166. def display(self):
  167. def locked_display():
  168. self.window.addch(self.y, self.x, '@', self.curses_color)
  169. self.window.refresh()
  170. # lock the curses IO while fudging stuff
  171. self.ui.exec_locked(locked_display)
  172. def update(self, acc_win, x, y):
  173. """Update the xy position of the '.' (and possibly the aframe)."""
  174. self.window = acc_win
  175. self.y = y
  176. self.x = x
  177. self.display()
  178. def std_color(self):
  179. self.setcolor('black')
  180. class InputHandler(ExitNotifyThread):
  181. """Listens for input via the curses interfaces"""
  182. #TODO, we need to use the ugly exitnotifythread (rather than simply
  183. #threading.Thread here, so exiting this thread via the callback
  184. #handler, kills off all parents too. Otherwise, they would simply
  185. #continue.
  186. def __init__(self, ui):
  187. super(InputHandler, self).__init__()
  188. self.char_handler = None
  189. self.ui = ui
  190. self.enabled = Event()
  191. # We will only parse input if we are enabled.
  192. self.inputlock = RLock()
  193. # denotes whether we should be handling the next char.
  194. self.start() #automatically start the thread
  195. def get_next_char(self):
  196. """Return the key pressed or -1.
  197. Wait until `enabled` and loop internally every stdscr.timeout()
  198. msecs, releasing the inputlock.
  199. :returns: char or None if disabled while in here"""
  200. self.enabled.wait()
  201. while self.enabled.is_set():
  202. with self.inputlock:
  203. char = self.ui.stdscr.getch()
  204. if char != -1: yield char
  205. def run(self):
  206. while True:
  207. char_gen = self.get_next_char()
  208. for char in char_gen:
  209. self.char_handler(char)
  210. #curses.ungetch(char)
  211. def set_char_hdlr(self, callback):
  212. """Sets a character callback handler.
  213. If a key is pressed it will be passed to this handler. Keys
  214. include the curses.KEY_RESIZE key.
  215. callback is a function taking a single arg -- the char pressed.
  216. If callback is None, input will be ignored."""
  217. with self.inputlock:
  218. self.char_handler = callback
  219. # start or stop the parsing of things
  220. if callback is None:
  221. self.enabled.clear()
  222. else:
  223. self.enabled.set()
  224. def input_acquire(self):
  225. """Call this method when you want exclusive input control.
  226. Make sure to call input_release afterwards! While this lockis
  227. held, input can go to e.g. the getpass input."""
  228. self.enabled.clear()
  229. self.inputlock.acquire()
  230. def input_release(self):
  231. """Call this method when you are done getting input."""
  232. self.inputlock.release()
  233. self.enabled.set()
  234. class CursesLogHandler(logging.StreamHandler):
  235. """self.ui has been set to the UI class before anything is invoked"""
  236. def emit(self, record):
  237. log_str = logging.StreamHandler.format(self, record)
  238. color = self.ui.gettf().curses_color
  239. # We must acquire both locks. Otherwise, deadlock can result.
  240. # This can happen if one thread calls _msg (locking curses, then
  241. # tf) and another tries to set the color (locking tf, then curses)
  242. #
  243. # By locking both up-front here, in this order, we prevent deadlock.
  244. self.ui.tframe_lock.acquire()
  245. self.ui.lock()
  246. try:
  247. y,x = self.ui.logwin.getyx()
  248. if y or x: self.ui.logwin.addch(10) # no \n before 1st item
  249. self.ui.logwin.addstr(log_str, color)
  250. finally:
  251. self.ui.unlock()
  252. self.ui.tframe_lock.release()
  253. self.ui.logwin.noutrefresh()
  254. self.ui.stdscr.refresh()
  255. class Blinkenlights(UIBase, CursesUtil):
  256. """Curses-cased fancy UI.
  257. Notable instance variables self. ....:
  258. - stdscr: THe curses std screen
  259. - bannerwin: The top line banner window
  260. - width|height: The total curses screen dimensions
  261. - logheight: Available height for the logging part
  262. - log_con_handler: The CursesLogHandler()
  263. - threadframes:
  264. - accframes[account]: 'Accountframe'"""
  265. def __init__(self, *args, **kwargs):
  266. super(Blinkenlights, self).__init__(*args, **kwargs)
  267. CursesUtil.__init__(self)
  268. ################################################## UTILS
  269. def setup_consolehandler(self):
  270. """Backend specific console handler.
  271. Sets up things and adds them to self.logger.
  272. :returns: The logging.Handler() for console output"""
  273. # create console handler with a higher log level
  274. ch = CursesLogHandler()
  275. #ch.setLevel(logging.DEBUG)
  276. # create formatter and add it to the handlers
  277. self.formatter = logging.Formatter("%(message)s")
  278. ch.setFormatter(self.formatter)
  279. # add the handlers to the logger
  280. self.logger.addHandler(ch)
  281. # the handler is not usable yet. We still need all the
  282. # intialization stuff currently done in init_banner. Move here?
  283. return ch
  284. def isusable(s):
  285. """Returns true if the backend is usable ie Curses works."""
  286. # Not a terminal? Can't use curses.
  287. if not sys.stdout.isatty() and sys.stdin.isatty():
  288. return False
  289. # No TERM specified? Can't use curses.
  290. if not os.environ.get('TERM', None):
  291. return False
  292. # Test if ncurses actually starts up fine. Only do so for
  293. # python>=2.6.6 as calling initscr() twice messing things up.
  294. # see http://bugs.python.org/issue7567 in python 2.6 to 2.6.5
  295. if sys.version_info[0:3] < (2,6) or sys.version_info[0:3] >= (2,6,6):
  296. try:
  297. curses.initscr()
  298. curses.endwin()
  299. except:
  300. return False
  301. return True
  302. def init_banner(self):
  303. self.availablethreadframes = {}
  304. self.threadframes = {}
  305. self.accframes = {}
  306. self.aflock = Lock()
  307. self.stdscr = curses.initscr()
  308. # turn off automatic echoing of keys to the screen
  309. curses.noecho()
  310. # react to keys instantly, without Enter key
  311. curses.cbreak()
  312. # return special key values, eg curses.KEY_LEFT
  313. self.stdscr.keypad(1)
  314. # wait 1s for input, so we don't block the InputHandler infinitely
  315. self.stdscr.timeout(1000)
  316. curses.start_color()
  317. # turn off cursor and save original state
  318. self.oldcursor = None
  319. try:
  320. self.oldcursor = curses.curs_set(0)
  321. except:
  322. pass
  323. self.stdscr.clear()
  324. self.stdscr.refresh()
  325. self.init_colorpairs()
  326. # set log handlers ui to ourself
  327. self._log_con_handler.ui = self
  328. self.setupwindows()
  329. # Settup keyboard handler
  330. self.inputhandler = InputHandler(self)
  331. self.inputhandler.set_char_hdlr(self.on_keypressed)
  332. self.gettf().setcolor('red')
  333. self.info(offlineimap.banner)
  334. def acct(self, *args):
  335. """Output that we start syncing an account (and start counting)."""
  336. self.gettf().setcolor('purple')
  337. super(Blinkenlights, self).acct(*args)
  338. def connecting(self, *args):
  339. self.gettf().setcolor('white')
  340. super(Blinkenlights, self).connecting(*args)
  341. def syncfolders(self, *args):
  342. self.gettf().setcolor('blue')
  343. super(Blinkenlights, self).syncfolders(*args)
  344. def syncingfolder(self, *args):
  345. self.gettf().setcolor('cyan')
  346. super(Blinkenlights, self).syncingfolder(*args)
  347. def skippingfolder(self, *args):
  348. self.gettf().setcolor('cyan')
  349. super(Blinkenlights, self).skippingfolder(*args)
  350. def loadmessagelist(self, *args):
  351. self.gettf().setcolor('green')
  352. super(Blinkenlights, self).loadmessagelist(*args)
  353. def syncingmessages(self, *args):
  354. self.gettf().setcolor('blue')
  355. super(Blinkenlights, self).syncingmessages(*args)
  356. def ignorecopyingmessage(self, *args):
  357. self.gettf().setcolor('red')
  358. super(Blinkenlights, self).ignorecopyingmessage(*args)
  359. def copyingmessage(self, *args):
  360. self.gettf().setcolor('orange')
  361. super(Blinkenlights, self).copyingmessage(*args)
  362. def deletingmessages(self, *args):
  363. self.gettf().setcolor('red')
  364. super(Blinkenlights, self).deletingmessages(*args)
  365. def addingflags(self, *args):
  366. self.gettf().setcolor('blue')
  367. super(Blinkenlights, self).addingflags(*args)
  368. def deletingflags(self, *args):
  369. self.gettf().setcolor('blue')
  370. super(Blinkenlights, self).deletingflags(*args)
  371. def callhook(self, *args):
  372. self.gettf().setcolor('white')
  373. super(Blinkenlights, self).callhook(*args)
  374. ############ Generic logging functions #############################
  375. def warn(self, msg, minor=0):
  376. self.gettf().setcolor('red', curses.A_BOLD)
  377. super(Blinkenlights, self).warn(msg)
  378. def threadExited(self, thread):
  379. acc = self.getthreadaccount(thread)
  380. with self.tframe_lock:
  381. if thread in self.threadframes[acc]:
  382. tf = self.threadframes[acc][thread]
  383. tf.setcolor('black')
  384. self.availablethreadframes[acc].append(tf)
  385. del self.threadframes[acc][thread]
  386. super(Blinkenlights, self).threadExited(thread)
  387. def gettf(self):
  388. """Return the ThreadFrame() of the current thread."""
  389. cur_thread = currentThread()
  390. acc = self.getthreadaccount() #Account() or None
  391. with self.tframe_lock:
  392. # Ideally we already have self.threadframes[accountname][thread]
  393. try:
  394. if cur_thread in self.threadframes[acc]:
  395. return self.threadframes[acc][cur_thread]
  396. except KeyError:
  397. # Ensure threadframes already has an account dict
  398. self.threadframes[acc] = {}
  399. self.availablethreadframes[acc] = deque()
  400. # If available, return a ThreadFrame()
  401. if len(self.availablethreadframes[acc]):
  402. tf = self.availablethreadframes[acc].popleft()
  403. tf.std_color()
  404. else:
  405. tf = self.getaccountframe(acc).get_new_tframe()
  406. self.threadframes[acc][cur_thread] = tf
  407. return tf
  408. def on_keypressed(self, key):
  409. # received special KEY_RESIZE, resize terminal
  410. if key == curses.KEY_RESIZE:
  411. self.resizeterm()
  412. return
  413. if key < 1 or key > 255:
  414. return
  415. if chr(key) == 'q':
  416. # Request to quit completely.
  417. self.warn("Requested shutdown via 'q'")
  418. offlineimap.accounts.Account.set_abort_event(self.config, 3)
  419. try:
  420. index = int(chr(key))
  421. except ValueError:
  422. return # Key not a valid number: exit.
  423. if index >= len(self.hotkeys):
  424. # Not in our list of valid hotkeys.
  425. return
  426. # Trying to end sleep somewhere.
  427. self.getaccountframe(self.hotkeys[index]).syncnow()
  428. def sleep(self, sleepsecs, account):
  429. self.gettf().setcolor('red')
  430. self.info("Next sync in %d:%02d"% (sleepsecs / 60, sleepsecs % 60))
  431. return super(Blinkenlights, self).sleep(sleepsecs, account)
  432. def sleeping(self, sleepsecs, remainingsecs):
  433. if not sleepsecs:
  434. # reset color to default if we are done sleeping.
  435. self.gettf().setcolor('white')
  436. accframe = self.getaccountframe(self.getthreadaccount())
  437. return accframe.sleeping(sleepsecs, remainingsecs)
  438. def resizeterm(self):
  439. """Resize the current windows."""
  440. self.exec_locked(self.setupwindows, True)
  441. def mainException(self):
  442. UIBase.mainException(self)
  443. def getpass(self, accountname, config, errmsg=None):
  444. # disable the hotkeys inputhandler
  445. self.inputhandler.input_acquire()
  446. # See comment on _msg for info on why both locks are obtained.
  447. self.lock()
  448. try:
  449. #s.gettf().setcolor('white')
  450. self.warn(" *** Input Required")
  451. self.warn(" *** Please enter password for account %s: " % \
  452. accountname)
  453. self.logwin.refresh()
  454. password = self.logwin.getstr()
  455. finally:
  456. self.unlock()
  457. self.inputhandler.input_release()
  458. return password
  459. def setupwindows(self, resize=False):
  460. """Setup and draw bannerwin and logwin.
  461. If `resize`, don't create new windows, just adapt size. This
  462. function should be invoked with CursesUtils.locked()."""
  463. self.height, self.width = self.stdscr.getmaxyx()
  464. self.logheight = self.height - len(self.accframes) - 1
  465. if resize:
  466. if curses.is_term_resized(self.height, self.width):
  467. curses.resizeterm(self.height, self.width)
  468. self.bannerwin.resize(1, self.width)
  469. self.logwin.resize(self.logheight, self.width)
  470. self.stdscr.clear()
  471. self.stdscr.noutrefresh()
  472. else:
  473. self.bannerwin = curses.newwin(1, self.width, 0, 0)
  474. self.logwin = curses.newwin(self.logheight, self.width, 1, 0)
  475. self.draw_bannerwin()
  476. self.logwin.idlok(True) # needed for scrollok below
  477. self.logwin.scrollok(True) # scroll window when too many lines added
  478. self.draw_logwin()
  479. self.accounts = reversed(sorted(self.accframes.keys()))
  480. pos = self.height - 1
  481. index = 0
  482. self.hotkeys = []
  483. for account in self.accounts:
  484. acc_win = curses.newwin(1, self.width, pos, 0)
  485. self.accframes[account].setwindow(acc_win, index)
  486. self.hotkeys.append(account)
  487. index += 1
  488. pos -= 1
  489. curses.doupdate()
  490. def draw_bannerwin(self):
  491. """Draw the top-line banner line."""
  492. if curses.has_colors():
  493. color = curses.A_BOLD | self.curses_colorpair('banner')
  494. else:
  495. color = curses.A_REVERSE
  496. self.bannerwin.clear() # Delete old content (eg before resizes)
  497. self.bannerwin.bkgd(' ', color) # Fill background with that color
  498. string = "%s %s"% (offlineimap.__productname__,
  499. offlineimap.__version__)
  500. self.bannerwin.addstr(0, 0, string, color)
  501. self.bannerwin.addstr(0, self.width -len(offlineimap.__copyright__) -1,
  502. offlineimap.__copyright__, color)
  503. self.bannerwin.noutrefresh()
  504. def draw_logwin(self):
  505. """(Re)draw the current logwindow."""
  506. if curses.has_colors():
  507. color = curses.color_pair(0) #default colors
  508. else:
  509. color = curses.A_NORMAL
  510. self.logwin.move(0, 0)
  511. self.logwin.clear()
  512. self.logwin.bkgd(' ', color)
  513. self.logwin.noutrefresh()
  514. def getaccountframe(self, acc_name):
  515. """Return an AccountFrame() corresponding to acc_name.
  516. Note that the *control thread uses acc_name `None`."""
  517. with self.aflock:
  518. # 1) Return existing or 2) create a new CursesAccountFrame.
  519. if acc_name in self.accframes: return self.accframes[acc_name]
  520. self.accframes[acc_name] = CursesAccountFrame(self, acc_name)
  521. # update the window layout
  522. self.setupwindows(resize= True)
  523. return self.accframes[acc_name]
  524. def terminate(self, *args, **kwargs):
  525. curses.nocbreak();
  526. self.stdscr.keypad(0);
  527. curses.echo()
  528. curses.endwin()
  529. # need to remove the Curses console handler now and replace with
  530. # basic one, so exceptions and stuff are properly displayed
  531. self.logger.removeHandler(self._log_con_handler)
  532. UIBase.setup_consolehandler(self)
  533. # reset the warning method, we do not have curses anymore
  534. self.warn = super(Blinkenlights, self).warn
  535. # finally call parent terminate which prints out exceptions etc
  536. super(Blinkenlights, self).terminate(*args, **kwargs)
  537. def threadException(self, thread):
  538. #self._log_con_handler.stop()
  539. UIBase.threadException(self, thread)