tools.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2013 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. """
  20. Define the CLI interface for pwman3 and the helper functions
  21. """
  22. import pwman.util.config as config
  23. import subprocess as sp
  24. import getpass
  25. import sys
  26. import struct
  27. # import traceback
  28. if sys.platform != 'win32':
  29. import tty
  30. import termios
  31. import fcntl
  32. _defaultwidth = 10
  33. class ANSI(object):
  34. """
  35. ANSI Colors
  36. """
  37. Reset = 0
  38. Bold = 1
  39. Underscore = 2
  40. Black = 30
  41. Red = 31
  42. Green = 32
  43. Yellow = 33
  44. Blue = 34
  45. Magenta = 35
  46. Cyan = 36
  47. White = 37
  48. def typeset(text, color, bold=False, underline=False):
  49. """print colored strings"""
  50. if not config.get_value("Global", "colors") == 'yes':
  51. return text
  52. if (bold):
  53. bold = "%d ;" % (ANSI.Bold)
  54. else:
  55. bold = ""
  56. if (underline):
  57. underline = "%d;" % (ANSI.Underscore)
  58. else:
  59. underline = ""
  60. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  61. text, ANSI.Reset)
  62. def select(question, possible):
  63. """
  64. select input from user
  65. """
  66. for i in range(0, len(possible)):
  67. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  68. while 1:
  69. uinput = getonechar(question)
  70. if uinput.isdigit() and int(uinput) in range(1, len(possible)+1):
  71. return possible[int(uinput)-1]
  72. def text_to_clipboards(text):
  73. """
  74. copy text to clipboard
  75. credit:
  76. https://pythonadventures.wordpress.com/tag/xclip/
  77. """
  78. # "primary":
  79. try:
  80. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  81. xsel_proc.communicate(text)
  82. # "clipboard":
  83. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  84. xsel_proc.communicate(text)
  85. except OSError, e:
  86. print e, "\nExecuting xsel failed, is it installed ?\n \
  87. please check your configuration file ... "
  88. def text_to_mcclipboard(text):
  89. """
  90. copy text to mac os x clip board
  91. credit:
  92. https://pythonadventures.wordpress.com/tag/xclip/
  93. """
  94. # "primary":
  95. try:
  96. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  97. pbcopy_proc.communicate(text)
  98. except OSError, e:
  99. print e, "\nExecuting pbcoy failed..."
  100. def open_url(link, macosx=False):
  101. """
  102. launch xdg-open or open in MacOSX with url
  103. """
  104. uopen = "xdg-open"
  105. if macosx:
  106. uopen = "open"
  107. try:
  108. sp.Popen([uopen, link], stdin=sp.PIPE)
  109. except OSError, e:
  110. print "Executing open_url failed with:\n", e
  111. def getpassword(question, width=_defaultwidth, echo=False):
  112. if echo:
  113. print question.ljust(width),
  114. return sys.stdin.readline().rstrip()
  115. else:
  116. while 1:
  117. a1 = getpass.getpass(question.ljust(width))
  118. if len(a1) == 0:
  119. return a1
  120. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  121. if a1 == a2:
  122. return a1
  123. else:
  124. print "Passwords don't match. Try again."
  125. def gettermsize():
  126. s = struct.pack("HHHH", 0, 0, 0, 0)
  127. f = sys.stdout.fileno()
  128. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  129. rows, cols, width, height = struct.unpack("HHHH", x)
  130. return rows, cols
  131. def getinput(question, default="", completer=None, width=_defaultwidth):
  132. if (not _readline_available):
  133. return raw_input(question.ljust(width))
  134. else:
  135. def defaulter():
  136. """define default behavior startup"""
  137. readline.insert_text(default)
  138. readline.set_startup_hook(defaulter)
  139. oldcompleter = readline.get_completer()
  140. readline.set_completer(completer)
  141. x = raw_input(question.ljust(width))
  142. readline.set_completer(oldcompleter)
  143. readline.set_startup_hook()
  144. return x
  145. def getyesno(question, defaultyes=False, width=tools._defaultwidth):
  146. if (defaultyes):
  147. default = "[Y/n]"
  148. else:
  149. default = "[y/N]"
  150. ch = getonechar("%s %s" % (question, default), width)
  151. if (ch == '\n'):
  152. if (defaultyes):
  153. return True
  154. else:
  155. return False
  156. elif (ch == 'y' or ch == 'Y'):
  157. return True
  158. elif (ch == 'n' or ch == 'N'):
  159. return False
  160. else:
  161. return getyesno(question, defaultyes, width)