dirnotes 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. @staticmethod
  71. def getShortDate(longDate):
  72. e = DataBase.DbToEpoch(longDate)
  73. sd = time.strptime(longDate,"%Y-%m-%d %H:%M:%S")
  74. # check for this year, or today
  75. ty = time.mktime((time.localtime()[0],1,1,0,0,0,0,1,-1))
  76. today = time.mktime((time.localtime()[0:3]+(0,0,0,0,1,-1)))
  77. if e < ty:
  78. return time.strftime("%b %d %Y",sd)
  79. elif e < today:
  80. return time.strftime("%b %d",sd)
  81. else:
  82. return time.strftime("%X",sd)
  83. #~ test code for this routine
  84. #~ for i in range(int(time.time() - 370*24*3600),
  85. #~ int(time.time() + 48*3600),
  86. #~ 3599):
  87. #~ ds = DataBase.epochToDb(i)
  88. #~ print("%d\t%s\t%s" % (i,ds,DataBase.getShortDate(ds)))
  89. def parse():
  90. parser = argparse.ArgumentParser(description='dirnotes application')
  91. parser.add_argument('dirname',metavar='dirname',type=str,
  92. help='directory [default=current dir]',default=".",nargs='?')
  93. parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
  94. parser.add_argument('-n','--nogui',action="store_const",const="1",
  95. help='use text base interface')
  96. parser.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
  97. group = parser.add_mutually_exclusive_group()
  98. group.add_argument('-s','--sort-by-name',metavar='sort',action="store_const",const='n')
  99. group.add_argument('-m','--sort-by-date',metavar='sort',action='store_const',const='d')
  100. return parser.parse_args()
  101. class FileObj():
  102. def __init__(self, fileName):
  103. self.fileName = fileName
  104. s = os.stat(fileName)
  105. self.date = DataBase.epochToDb(s.st_mtime)
  106. if stat.S_ISDIR(s.st_mode):
  107. self.size = -1
  108. else:
  109. self.size = s.st_size
  110. self.comment = ''
  111. try:
  112. self.comment = xattr.getxattr(fileName,COMMENT_KEY)
  113. except Exception as e:
  114. #print("comment read on %s failed, execption %s" % (self.fileName,e))
  115. pass
  116. def getName(self):
  117. return self.fileName
  118. def getComment(self):
  119. return self.comment
  120. def setComment(self,newComment):
  121. self.comment = newComment
  122. try:
  123. xattr.setxattr(self.fileName,COMMENT_KEY,self.comment)
  124. return True
  125. # we need to move these cases out to a handler
  126. except Exception as e:
  127. print("problem setting the comment on file %s" % (self.fileName,))
  128. if os.access(self.fileName, os.W_OK)!=True:
  129. print("you don't appear to have write permissions on this file")
  130. # change the listbox background to yellow
  131. self.displayBox.notifyUnchanged()
  132. elif "Errno 95" in str(e):
  133. print("is this a VFAT or EXFAT volume? these don't allow comments")
  134. return False
  135. def getDate(self):
  136. return self.date
  137. def getSize(self):
  138. return self.size
  139. # sortable TableWidgetItem, based on idea by Aledsandar
  140. # http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
  141. class SortableTableWidgetItem(QTableWidgetItem):
  142. def __init__(self, text, sortValue):
  143. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  144. self.sortValue = sortValue
  145. def __lt__(self, other):
  146. return self.sortValue < other.sortValue
  147. class DirNotes(QMainWindow):
  148. ''' the main window of the app
  149. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  150. '''
  151. def __init__(self, argFilename, db, parent=None):
  152. super(DirNotes,self).__init__(parent)
  153. self.db = db
  154. win = QWidget()
  155. self.setCentralWidget(win)
  156. lb = QTableWidget()
  157. self.lb = lb
  158. lb.setColumnCount(4)
  159. lb.horizontalHeader().setResizeMode( 3, QHeaderView.Stretch );
  160. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  161. lb.verticalHeader().setVisible(False)
  162. # resize the comments column
  163. # and resize the parent window to match the directory size
  164. # allow multiple entries on the line at this point
  165. #d = os.listdir(p.filename[0])
  166. #d.sort()
  167. self.curPath, filename = os.path.split(argFilename)
  168. print("working on <"+self.curPath+"> and <"+filename+">")
  169. self.refill()
  170. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  171. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  172. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  173. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  174. lb.resizeColumnsToContents()
  175. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  176. b1 = QPushButton("restore from database",win)
  177. self.dirLeft = dirLeft = DirWidget(self.curPath,win)
  178. dirLeft.setMaximumHeight(140)
  179. dirLeft.setMaximumWidth(200)
  180. dirRight = DirWidget(self.curPath,win)
  181. dirRight.setMaximumHeight(140)
  182. dirRight.setMaximumWidth(200)
  183. dirRight.setEnabled(False)
  184. dirLeft.selected.connect(self.newDir)
  185. rDate = QRadioButton("Sort by date",win)
  186. rSize = QRadioButton("Sort by size",win)
  187. layout = QVBoxLayout()
  188. upperLayout = QHBoxLayout()
  189. innerLayout = QVBoxLayout()
  190. layout.addWidget(e)
  191. upperLayout.addWidget(dirLeft)
  192. innerLayout.addWidget(rDate)
  193. innerLayout.addWidget(rSize)
  194. innerLayout.addWidget(b1)
  195. upperLayout.addLayout(innerLayout)
  196. upperLayout.addWidget(dirRight)
  197. layout.addLayout(upperLayout)
  198. layout.addWidget(lb)
  199. win.setLayout(layout)
  200. lb.itemChanged.connect(self.change)
  201. b1.pressed.connect(self.restore_from_database)
  202. mb = self.menuBar()
  203. mf = mb.addMenu('&File')
  204. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  205. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  206. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  207. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  208. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  209. QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  210. self.setWindowTitle("DirNotes")
  211. self.setMinimumSize(600,700)
  212. lb.setFocus()
  213. def closeEvent(self,e):
  214. print("closing")
  215. def sbd(self):
  216. print("sort by date")
  217. self.lb.sortItems(1,QtCore.Qt.DescendingOrder)
  218. def sbs(self):
  219. print("sort by size")
  220. self.lb.sortItems(2)
  221. def sbn(self):
  222. print("sort by name")
  223. self.lb.sortItems(0)
  224. def sbc(self):
  225. print("sort by comment")
  226. self.lb.sortItems(3,QtCore.Qt.DescendingOrder)
  227. def newDir(self):
  228. print("change dir to "+self.dirLeft.currentPath())
  229. def refill(self):
  230. small_font = QFont("",8)
  231. dirIcon = QIcon.fromTheme('folder')
  232. fileIcon = QIcon.fromTheme('text-x-generic')
  233. current, dirs, files = os.walk(self.curPath,followlinks=True).next()
  234. dirs = map(lambda x:x+'/', dirs)
  235. dirs.sort()
  236. files.sort()
  237. d = dirs + files
  238. self.lb.setRowCount(len(d))
  239. self.files = []
  240. for i in range(len(d)):
  241. this_file = FileObj(current+'/'+d[i])
  242. self.files = self.files + [this_file]
  243. item = QTableWidgetItem(d[i])
  244. item.setFlags(QtCore.Qt.ItemIsEnabled)
  245. self.lb.setItem(i,0,item)
  246. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  247. comment = this_file.getComment()
  248. self.lb.setItem(i,3,QTableWidgetItem(comment))
  249. dt = this_file.getDate()
  250. da = SortableTableWidgetItem(DataBase.getShortDate(dt),dt)
  251. #da.setFont(small_font)
  252. da.setFlags(QtCore.Qt.ItemIsEnabled)
  253. self.lb.setItem(i,1,da)
  254. si = this_file.getSize()
  255. if si>=0:
  256. sa = SortableTableWidgetItem(str(si),si)
  257. item.setIcon(fileIcon)
  258. else:
  259. sa = SortableTableWidgetItem('',0)
  260. item.setIcon(dirIcon)
  261. sa.setTextAlignment(QtCore.Qt.AlignRight)
  262. sa.setFlags(QtCore.Qt.ItemIsEnabled)
  263. self.lb.setItem(i,2,sa)
  264. self.lb.resizeColumnToContents(1)
  265. def change(self,x):
  266. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  267. the_file = dn.files[x.row()]
  268. r = the_file.setComment(str(x.text()))
  269. if r:
  270. self.db.log(the_file.getName(),x.text())
  271. def restore_from_database(self):
  272. print("restore from database")
  273. fileName = str(self.lb.item(self.lb.currentRow(),0).text())
  274. fo_row = self.db.getData(fileName)
  275. if fo_row and len(fo_row)>1:
  276. comment = fo_row[3]
  277. print(fileName,fo_row[0],comment)
  278. the_file = dn.files[self.lb.currentRow()]
  279. the_file.setComment(comment)
  280. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  281. if __name__=="__main__":
  282. p = parse()
  283. if p.dirname[-1]=='/':
  284. p.dirname = p.dirname[:-1]
  285. if os.path.isdir(p.dirname):
  286. p.dirname = p.dirname + '/'
  287. print(p.dirname)
  288. db = DataBase()
  289. a = QApplication([])
  290. dn = DirNotes(p.dirname,db)
  291. dn.show()
  292. a.exec_()
  293. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  294. ''' files from directories
  295. use os.isfile()
  296. os.isdir()
  297. current, dirs, files = os.walk("path").next()
  298. possible set folllowLinks=True'''
  299. ''' notes from the wdrm project
  300. table showed
  301. filename, size, date size, date, desc
  302. at start, fills the list of all the files
  303. skip the . entry
  304. '''
  305. ''' should we also do user.xdg.tags="TagA,TagB" ?
  306. user.charset
  307. user.creator=application_name or user.xdg.creator
  308. user.xdg.origin.url
  309. user.xdg.language=[RFC3066/ISO639]
  310. user.xdg.publisher
  311. '''
  312. ''' to allow column-sorting, you use the sortByColumn and set the Horiz-header to clickable
  313. '''
  314. ''' TODO: add cut-copy-paste for comments '''
  315. ''' TODO: also need a way to display-&-restore comments from the database '''
  316. ''' QFileDialog
  317. -make my own?
  318. -existing one has
  319. -history
  320. -back button
  321. -up button
  322. -but we don't need
  323. -directory date
  324. -icon option
  325. -url browser (unless we go network file system)
  326. -new folder button
  327. -file type chooser
  328. -text entry box
  329. -choose & cancel buttons
  330. '''