dirnotes 12 KB

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