dirnotes 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #!/usr/bin/python
  2. """ a simple gui or command line app
  3. to view and create/edit file comments
  4. comments are stored in xattr user.xdg.comment
  5. depends on python-pyxattr
  6. because files are so often over-written, save a copy
  7. of the comments in a database ~/.dirnotes.db
  8. these comments stick to the symlink
  9. """
  10. import sys,os,argparse,stat
  11. from dirWidget import DirWidget
  12. from PyQt4.QtGui import *
  13. from PyQt4 import QtGui, QtCore
  14. import xattr, sqlite3, time
  15. VERSION = "0.2"
  16. COMMENT_KEY = "user.xdg.comment"
  17. DATABASE_NAME = "~/.dirnotes.db"
  18. # convert the ~/ form to a fully qualified path
  19. DATABASE_NAME = os.path.expanduser(DATABASE_NAME)
  20. class DataBase:
  21. ''' the database is flat
  22. fileName: fully qualified name
  23. st_mtime: a float
  24. size: a long
  25. comment: a string
  26. comment_time: a float, the time of the comment save
  27. this is effectively a log file, as well as a resource for a restore
  28. (in case a file-move is done without comment)
  29. the database is associated with a user, in the $HOME dir
  30. '''
  31. def __init__(self):
  32. '''try to open the database; if not found, create it'''
  33. try:
  34. self.db = sqlite3.connect(DATABASE_NAME)
  35. except sqlite3.OperationalError:
  36. print("Database %s not found" % DATABASE_NAME)
  37. raise OperationalError
  38. c = self.db.cursor()
  39. try:
  40. c.execute("select * from dirnotes")
  41. except sqlite3.OperationalError:
  42. print("Table %s created" % ("dirnotes"))
  43. c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME)")
  44. def getData(self, fileName):
  45. c = self.db.cursor()
  46. c.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
  47. return c.fetchone()
  48. def setData(self, fileName, _date, _size, comment):
  49. c = self.db.cursor()
  50. c.execute("insert into dirnotes values (?,?,?,?,?)",
  51. (fileName, _date, _size, comment, time.time()))
  52. self.db.commit()
  53. return True
  54. def log(self, fileName, comment):
  55. ''' TODO: convert filename to canonical '''
  56. c = self.db.cursor()
  57. s = os.stat(fileName)
  58. print "params: %s %s %d %s %s" % ((os.path.abspath(fileName),
  59. DataBase.epochToDb(s.st_mtime), s.st_size, comment,
  60. DataBase.epochToDb(time.time())))
  61. c.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'))",
  62. (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time()))
  63. self.db.commit()
  64. @staticmethod
  65. def epochToDb(epoch):
  66. return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(epoch))
  67. @staticmethod
  68. def DbToEpoch(dbTime):
  69. return time.mktime(time.strptime(dbTime,"%Y-%m-%d %H:%M:%S"))
  70. def parse():
  71. parser = argparse.ArgumentParser(description='dirnotes application')
  72. parser.add_argument('dirname',metavar='dirname',type=str,
  73. help='directory [default=current dir]',default=".",nargs='?')
  74. parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
  75. parser.add_argument('-n','--nogui',action="store_const",const="1",
  76. help='use text base interface')
  77. parser.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
  78. group = parser.add_mutually_exclusive_group()
  79. group.add_argument('-s','--sort-by-name',metavar='sort',action="store_const",const='n')
  80. group.add_argument('-m','--sort-by-date',metavar='sort',action='store_const',const='d')
  81. return parser.parse_args()
  82. class FileObj():
  83. def __init__(self, fileName):
  84. self.fileName = fileName
  85. s = os.stat(fileName)
  86. self.date = DataBase.epochToDb(s.st_mtime)
  87. if stat.S_ISDIR(s.st_mode):
  88. self.size = -1
  89. else:
  90. self.size = s.st_size
  91. self.comment = ''
  92. try:
  93. self.comment = xattr.getxattr(fileName,COMMENT_KEY)
  94. except Exception as e:
  95. #print("comment read on %s failed, execption %s" % (self.fileName,e))
  96. pass
  97. def getName(self):
  98. return self.fileName
  99. def getComment(self):
  100. return self.comment
  101. def setComment(self,newComment):
  102. self.comment = newComment
  103. try:
  104. xattr.setxattr(self.fileName,COMMENT_KEY,self.comment)
  105. return True
  106. # we need to move these cases out to a handler
  107. except Exception as e:
  108. print("problem setting the comment on file %s" % (self.fileName,))
  109. if os.access(self.fileName, os.W_OK)!=True:
  110. print("you don't appear to have write permissions on this file")
  111. # change the listbox background to yellow
  112. self.displayBox.notifyUnchanged()
  113. elif "Errno 95" in str(e):
  114. print("is this a VFAT or EXFAT volume? these don't allow comments")
  115. return False
  116. def getDate(self):
  117. return self.date
  118. def getSize(self):
  119. return self.size
  120. class DirNotes(QMainWindow):
  121. ''' the main window of the app
  122. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  123. '''
  124. def __init__(self, argFilename, db, parent=None):
  125. super(DirNotes,self).__init__(parent)
  126. self.db = db
  127. win = QWidget()
  128. self.setCentralWidget(win)
  129. lb = QTableWidget()
  130. self.lb = lb
  131. lb.setColumnCount(4)
  132. lb.horizontalHeader().setResizeMode( 3, QHeaderView.Stretch );
  133. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  134. lb.verticalHeader().setVisible(False)
  135. # resize the comments column
  136. # and resize the parent window to match the directory size
  137. # allow multiple entries on the line at this point
  138. #d = os.listdir(p.filename[0])
  139. #d.sort()
  140. self.curPath, filename = os.path.split(argFilename)
  141. print("working on <"+self.curPath+"> and <"+filename+">")
  142. self.refill()
  143. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  144. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  145. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  146. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  147. lb.resizeColumnsToContents()
  148. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  149. b1 = QPushButton("restore from database",win)
  150. self.dirLeft = dirLeft = DirWidget(self.curPath,win)
  151. dirLeft.setMaximumHeight(140)
  152. dirLeft.setMaximumWidth(200)
  153. dirRight = DirWidget(self.curPath,win)
  154. dirRight.setMaximumHeight(140)
  155. dirRight.setMaximumWidth(200)
  156. dirRight.setEnabled(False)
  157. dirLeft.selected.connect(self.newDir)
  158. rDate = QRadioButton("Sort by date",win)
  159. rSize = QRadioButton("Sort by size",win)
  160. layout = QVBoxLayout()
  161. upperLayout = QHBoxLayout()
  162. innerLayout = QVBoxLayout()
  163. layout.addWidget(e)
  164. upperLayout.addWidget(dirLeft)
  165. innerLayout.addWidget(rDate)
  166. innerLayout.addWidget(rSize)
  167. innerLayout.addWidget(b1)
  168. upperLayout.addLayout(innerLayout)
  169. upperLayout.addWidget(dirRight)
  170. layout.addLayout(upperLayout)
  171. layout.addWidget(lb)
  172. win.setLayout(layout)
  173. lb.itemChanged.connect(self.change)
  174. b1.pressed.connect(self.restore_from_database)
  175. mb = self.menuBar()
  176. mf = mb.addMenu('&File')
  177. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  178. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  179. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  180. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  181. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  182. QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  183. self.setWindowTitle("DirNotes")
  184. self.setMinimumSize(600,700)
  185. lb.setFocus()
  186. def closeEvent(self,e):
  187. print("closing")
  188. def sbd(self):
  189. print("sort by date")
  190. self.lb.sortItems(1,QtCore.Qt.DescendingOrder)
  191. def sbs(self):
  192. print("sort by size")
  193. self.lb.sortItems(2)
  194. def sbn(self):
  195. print("sort by name")
  196. self.lb.sortItems(0)
  197. def sbc(self):
  198. print("sort by comment")
  199. self.lb.sortItems(3,QtCore.Qt.DescendingOrder)
  200. def newDir(self):
  201. print("change dir to "+self.dirLeft.currentPath())
  202. class DnTableWidgetItem(QTableWidgetItem):
  203. def __init__(self, text, value):
  204. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  205. self.value = value
  206. def __lt__(self, other):
  207. return self.value < other.value
  208. def refill(self):
  209. small_font = QFont("",8)
  210. dirIcon = QIcon.fromTheme('folder')
  211. fileIcon = QIcon.fromTheme('text-x-generic')
  212. current, dirs, files = os.walk(self.curPath,followlinks=True).next()
  213. dirs = map(lambda x:x+'/', dirs)
  214. dirs.sort()
  215. files.sort()
  216. d = dirs + files
  217. self.lb.setRowCount(len(d))
  218. self.files = []
  219. for i in range(len(d)):
  220. this_file = FileObj(current+'/'+d[i])
  221. self.files = self.files + [this_file]
  222. item = QTableWidgetItem(d[i])
  223. item.setFlags(QtCore.Qt.ItemIsEnabled)
  224. self.lb.setItem(i,0,item)
  225. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  226. comment = this_file.getComment()
  227. self.lb.setItem(i,3,QTableWidgetItem(comment))
  228. da = QTableWidgetItem(this_file.getDate())
  229. da.setFont(small_font)
  230. da.setFlags(QtCore.Qt.ItemIsEnabled)
  231. self.lb.setItem(i,1,da)
  232. si = this_file.getSize()
  233. if si>=0:
  234. sa = self.DnTableWidgetItem(str(si),si)
  235. item.setIcon(fileIcon)
  236. else:
  237. sa = self.DnTableWidgetItem('',0)
  238. item.setIcon(dirIcon)
  239. sa.setTextAlignment(QtCore.Qt.AlignRight)
  240. sa.setFlags(QtCore.Qt.ItemIsEnabled)
  241. self.lb.setItem(i,2,sa)
  242. self.lb.resizeColumnToContents(1)
  243. def change(self,x):
  244. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  245. the_file = dn.files[x.row()]
  246. r = the_file.setComment(str(x.text()))
  247. if r:
  248. self.db.log(the_file.getName(),x.text())
  249. def restore_from_database(self):
  250. print("restore from database")
  251. fileName = str(self.lb.item(self.lb.currentRow(),0).text())
  252. fo_row = self.db.getData(fileName)
  253. if fo_row and len(fo_row)>1:
  254. comment = fo_row[3]
  255. print(fileName,fo_row[0],comment)
  256. the_file = dn.files[self.lb.currentRow()]
  257. the_file.setComment(comment)
  258. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  259. if __name__=="__main__":
  260. p = parse()
  261. if p.dirname[-1]=='/':
  262. p.dirname = p.dirname[:-1]
  263. if os.path.isdir(p.dirname):
  264. p.dirname = p.dirname + '/'
  265. print(p.dirname)
  266. db = DataBase()
  267. a = QApplication([])
  268. dn = DirNotes(p.dirname,db)
  269. dn.show()
  270. a.exec_()
  271. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  272. ''' files from directories
  273. use os.isfile()
  274. os.isdir()
  275. current, dirs, files = os.walk("path").next()
  276. possible set folllowLinks=True'''
  277. ''' notes from the wdrm project
  278. table showed
  279. filename, size, date size, date, desc
  280. at start, fills the list of all the files
  281. skip the . entry
  282. '''
  283. ''' should we also do user.xdg.tags="TagA,TagB" ?
  284. user.charset
  285. user.creator=application_name or user.xdg.creator
  286. user.xdg.origin.url
  287. user.xdg.language=[RFC3066/ISO639]
  288. user.xdg.publisher
  289. '''
  290. ''' to allow column-sorting, you use the sortByColumn and set the Horiz-header to clickable
  291. '''
  292. ''' TODO: also need a way to display-&-restore comments from the database '''
  293. ''' QFileDialog
  294. -make my own?
  295. -existing one has
  296. -history
  297. -back button
  298. -up button
  299. -but we don't need
  300. -directory date
  301. -icon option
  302. -url browser (unless we go network file system)
  303. -new folder button
  304. -file type chooser
  305. -text entry box
  306. -choose & cancel buttons
  307. '''