SIP4 python bindings for TQt
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

324 lignes
10KB

  1. #!/usr/bin/env python
  2. #
  3. # 2005-02-12 initial version hp
  4. import os
  5. import pickle
  6. from python_tqt.qt import *
  7. from dirview import Directory, DirectoryView
  8. bookmarks = [
  9. "22 14 8 1",
  10. "# c #000080",
  11. "a c #585858",
  12. "b c #000000",
  13. "c c #ffffff",
  14. "d c #ffffff",
  15. "e c #ffffff",
  16. "f c #000000",
  17. ". c None",
  18. "...bb.................",
  19. "..bacb....bbb.........",
  20. "..badcb.bbccbab.......",
  21. "..bacccbadccbab.......",
  22. "..baecdbcccdbab.......",
  23. "..bacccbacccbab.......",
  24. "..badcdbcecdfab.......",
  25. "..bacecbacccbab.......",
  26. "..baccdbcccdbab.......",
  27. "...badcbacdbbab.......",
  28. "....bacbcbbccab.......",
  29. ".....babbaaaaab.......",
  30. ".....bbabbbbbbb.......",
  31. "......bb.............."
  32. ]
  33. home = [
  34. "16 15 4 1",
  35. "# c #000000",
  36. "a c #ffffff",
  37. "b c #c0c0c0",
  38. ". c None",
  39. ".......##.......",
  40. "..#...####......",
  41. "..#..#aabb#.....",
  42. "..#.#aaaabb#....",
  43. "..##aaaaaabb#...",
  44. "..#aaaaaaaabb#..",
  45. ".#aaaaaaaaabbb#.",
  46. "###aaaaaaaabb###",
  47. "..#aaaaaaaabb#..",
  48. "..#aaa###aabb#..",
  49. "..#aaa#.#aabb#..",
  50. "..#aaa#.#aabb#..",
  51. "..#aaa#.#aabb#..",
  52. "..#aaa#.#aabb#..",
  53. "..#####.######.."
  54. ]
  55. class PixmapView(TQScrollView):
  56. def __init__(self, parent):
  57. TQScrollView.__init__(self, parent)
  58. self.pixmap = None
  59. self.viewport().setBackgroundMode(self.PaletteBase)
  60. def setPixmap(self, pix):
  61. self.pixmap = pix
  62. self.resizeContents(pix.size().width(), pix.size().height())
  63. self.viewport().repaint(False)
  64. def drawContents(self, p, cx, cy, cw, ch):
  65. p.fillRect(cx, cy, cw, ch, self.colorGroup().brush(TQColorGroup.Base))
  66. p.drawPixmap(0, 0, self.pixmap)
  67. class Preview(TQWidgetStack):
  68. def __init__(self, parent):
  69. TQWidgetStack.__init__(self, parent)
  70. self.normalText = TQMultiLineEdit(self)
  71. self.normalText.setReadOnly(True)
  72. self.html = TQTextView(self)
  73. self.pixmap = PixmapView(self)
  74. self.raiseWidget(self.normalText)
  75. def showPreview(self, url, size):
  76. if url.isLocalFile():
  77. path = url.path()
  78. fi = TQFileInfo(path)
  79. if fi.isFile() and fi.size() > size * 1000:
  80. self.normalText.setText(
  81. "The File\n%s\nis too large, so I don't show it!" % path)
  82. self.raiseWidget(self.normalText)
  83. return
  84. pix = TQPixmap(path)
  85. if pix.isNull():
  86. if fi.isFile():
  87. err = False
  88. try:
  89. text = open(path.latin1(), "r").read()
  90. except IOError, msg:
  91. text = TQString(str(msg))
  92. err = True
  93. if not err and fi.extension().lower().contains("htm"):
  94. url = self.html.mimeSourceFactory().makeAbsolute(
  95. path, self.html.context())
  96. self.html.setText(text, url)
  97. self.raiseWidget(self.html)
  98. return
  99. else:
  100. self.normalText.setText(text)
  101. self.raiseWidget(self.normalText)
  102. return
  103. else:
  104. self.normalText.setText("")
  105. self.raiseWidget(self.normalText)
  106. else:
  107. self.pixmap.setPixmap(pix)
  108. self.raiseWidget(self.pixmap)
  109. else:
  110. self.normalText.setText("I only show local files!")
  111. self.raiseWidget(self.normalText)
  112. # We can't instantiate TQFilePreview directly because it is abstract. Note that
  113. # the previewUrl() abstract is patched in later to work around the fact that
  114. # you can't multiply inherit from more than one wrapped class.
  115. class FilePreview(TQFilePreview):
  116. pass
  117. class PreviewWidget(TQVBox):
  118. def __init__(self, parent):
  119. TQVBox.__init__(self, parent)
  120. self.setSpacing( 5 )
  121. self.setMargin( 5 )
  122. row = TQHBox(self)
  123. row.setSpacing(5)
  124. TQLabel("Only show files smaller than: ", row)
  125. self.sizeSpinBox = TQSpinBox(1, 10000, 1, row)
  126. self.sizeSpinBox.setSuffix(" KB")
  127. self.sizeSpinBox.setValue(128)
  128. row.setFixedHeight(10 + self.sizeSpinBox.sizeHint().height())
  129. self.__preview = Preview(self)
  130. # workaround sip inability of multiple inheritance
  131. # create a local TQFilePreview instance and redirect
  132. # the method, which is called on preview, to us
  133. self.preview = FilePreview()
  134. self.preview.previewUrl = self.previewUrl
  135. def previewUrl(self, url):
  136. self.__preview.showPreview(url, self.sizeSpinBox.value())
  137. class CustomFileDialog(TQFileDialog):
  138. def __init__(self, preview = False):
  139. TQFileDialog.__init__(self, None, None, True)
  140. self.bookmarkFile = ".pybookmarks"
  141. self.bookmarkList = []
  142. if os.path.exists(self.bookmarkFile):
  143. try:
  144. self.bookmarkList = pickle.loads(open(self.bookmarkFile, "rb").read())
  145. except IOError, msg:
  146. print msg
  147. self.setDir("/")
  148. self.dirView = DirectoryView(self, None, True)
  149. self.dirView.addColumn("")
  150. self.dirView.header().hide()
  151. root = Directory(self.dirView, "/")
  152. root.setOpen(True)
  153. self.dirView.setFixedWidth(200)
  154. self.addLeftWidget(self.dirView)
  155. p = TQPushButton(self)
  156. p.setPixmap(TQPixmap(bookmarks))
  157. TQToolTip.add(p, "Bookmarks")
  158. self.bookmarkMenu = TQPopupMenu(self)
  159. self.connect(self.bookmarkMenu, SIGNAL("activated(int)"),
  160. self.bookmarkChosen)
  161. self.addId = self.bookmarkMenu.insertItem("Add bookmark")
  162. self.bookmarkMenu.insertSeparator()
  163. for l in self.bookmarkList:
  164. self.bookmarkMenu.insertItem(l)
  165. p.setPopup(self.bookmarkMenu)
  166. self.addToolButton(p, True)
  167. self.connect(self.dirView, PYSIGNAL("folderSelected(const TQString &)"),
  168. self.setDir2)
  169. self.connect(self, SIGNAL("dirEntered(const TQString &)"),
  170. self.dirView.setDir)
  171. b = TQToolButton(self)
  172. TQToolTip.add(b, "Go Home!")
  173. b.setPixmap(TQPixmap(home))
  174. self.connect(b, SIGNAL("clicked()"), self.goHome)
  175. self.addToolButton(b)
  176. if preview:
  177. self.setContentsPreviewEnabled(True)
  178. pw = PreviewWidget(self)
  179. self.setContentsPreview(pw, pw.preview)
  180. self.setViewMode(TQFileDialog.List)
  181. self.setPreviewMode(TQFileDialog.Contents)
  182. w = self.width()
  183. h = self.height()
  184. if preview:
  185. self.resize(w + w / 2, h + h / 3)
  186. else:
  187. self.resize(w + w / 3, h + h / 4)
  188. def done(self, r):
  189. if self.bookmarkList:
  190. try:
  191. open(self.bookmarkFile, "wb").write(pickle.dumps(self.bookmarkList))
  192. except IOError, msg:
  193. print msg
  194. return TQFileDialog.done(self, r)
  195. def showEvent(self, e):
  196. TQFileDialog.showEvent(self, e)
  197. self.dirView.setDir(self.dirPath())
  198. def setDir2(self, path):
  199. self.blockSignals(True)
  200. self.setDir(path)
  201. self.blockSignals(False)
  202. def bookmarkChosen(self, i):
  203. if i == self.addId:
  204. # keep bookmarks pythonic
  205. dp = self.dirPath().latin1()
  206. if dp not in self.bookmarkList:
  207. self.bookmarkList.append(dp)
  208. self.bookmarkMenu.insertItem(dp)
  209. else:
  210. self.setDir(self.bookmarkMenu.text(i))
  211. def goHome(self):
  212. if os.getenv("HOME"):
  213. self.setDir(os.getenv("HOME"))
  214. else:
  215. self.setDir("/")
  216. if __name__ == '__main__':
  217. import sys
  218. import getopt
  219. def usage(msg = None):
  220. if msg:
  221. print >> sys.stderr, msg
  222. print >> sys.stderr, """\
  223. usage: qdir [--any | --dir | --custom] [--preview] [--default f] {--filter f} [caption ...]
  224. --any Get any filename, need not exist.
  225. --dir Return a directory rather than a file.
  226. --custom Opens a customized TQFileDialog with
  227. dir browser, bookmark menu, etc.
  228. --preview Show a preview widget.
  229. --default f Start from directory/file f.
  230. --filter f eg. '*.gif' '*.bmp'
  231. caption ... Caption for dialog.
  232. """
  233. sys.exit(1)
  234. def main():
  235. options = ["help", "any", "dir", "custom", "preview", "default=", "filter="]
  236. mode = TQFileDialog.ExistingFile
  237. preview = False
  238. custom = False
  239. start = None
  240. filter = TQString.null
  241. app = TQApplication(sys.argv)
  242. try:
  243. optlist, args = getopt.getopt(sys.argv[1:], "h", options)
  244. except getopt.error, msg:
  245. usage(msg)
  246. for opt, par in optlist:
  247. if opt in ("-h", "--help"):
  248. usage()
  249. elif opt == "--any":
  250. mode = TQFileDialog.AnyFile
  251. elif opt == "--dir":
  252. mode = TQFileDialog.Directory
  253. elif opt == "--default":
  254. start = par
  255. elif opt == "--filter":
  256. filter = par
  257. elif opt == "--preview":
  258. preview = True
  259. elif opt == "--custom":
  260. custom = True
  261. if args:
  262. caption = " ".join(args)
  263. elif mode == TQFileDialog.Directory:
  264. caption = "Choose directory..."
  265. else:
  266. caption = "Choose file..."
  267. if not start:
  268. start = TQDir.currentDirPath()
  269. if not custom:
  270. fd = TQFileDialog(TQString.null, filter, None, None, True)
  271. fd.setMode(mode)
  272. if preview:
  273. fd.setContentsPreviewEnabled(True)
  274. pw = PreviewWidget(fd)
  275. fd.setContentsPreview(pw, pw.preview)
  276. fd.setViewMode(TQFileDialog.List)
  277. fd.setPreviewMode(TQFileDialog.Contents)
  278. w = fd.width()
  279. h = fd.height()
  280. fd.resize(w + w / 3, h + h / 4)
  281. fd.setCaption(caption)
  282. fd.setSelection(start)
  283. if fd.exec_loop() == TQDialog.Accepted:
  284. print "%s\n" % fd.selectedFile().latin1()
  285. return 0
  286. else:
  287. return 1
  288. else:
  289. fd = CustomFileDialog(preview)
  290. fd.exec_loop()
  291. return 1
  292. sys.exit(main())