PageRenderTime 1078ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/Backup/20130305143115/SideBarEnhancements/sidebar/SideBarItem.py

https://gitlab.com/Blueprint-Marketing/sublime-config
Python | 476 lines | 444 code | 31 blank | 1 comment | 44 complexity | b105c40b47de7e69e6e6ea808bab5a49 MD5 | raw file
  1. # coding=utf8
  2. import sublime
  3. import os
  4. import re
  5. import shutil
  6. from SideBarProject import SideBarProject
  7. try:
  8. import desktop
  9. except:
  10. pass
  11. class Object():
  12. pass
  13. def expand_vars(path):
  14. for k, v in os.environ.iteritems():
  15. k = unicode(k.encode('utf8'))
  16. v = unicode(v.encode('utf8'))
  17. path = path.replace(u'%'+k+'%', v).replace(u'%'+k.lower()+'%', v)
  18. return path
  19. class SideBarItem:
  20. def __init__(self, path, is_directory):
  21. self._path = path
  22. self._is_directory = is_directory
  23. def path(self, path = ''):
  24. if path == '':
  25. return self._path
  26. else:
  27. self._path = path
  28. self._is_directory = os.path.isdir(path)
  29. return path
  30. def pathSystem(self):
  31. import sys
  32. return self.path().encode(sys.getfilesystemencoding())
  33. def pathWithoutProject(self):
  34. path = self.path()
  35. for directory in SideBarProject().getDirectories():
  36. path = path.replace(directory, '', 1)
  37. return path.replace('\\', '/')
  38. def pathProject(self):
  39. path = self.path()
  40. for directory in SideBarProject().getDirectories():
  41. path2 = path.replace(directory, '', 1)
  42. if path2 != path:
  43. return directory
  44. return False
  45. def projectURL(self, type):
  46. filename = os.path.normpath(os.path.join(sublime.packages_path(), '..', 'Settings', 'SideBarEnhancements.json'))
  47. if os.path.lexists(filename):
  48. #try:
  49. import json
  50. data = file(filename, 'r').read()
  51. data = data.replace('\t', ' ').replace('\\', '/').replace('\\', '/').replace('//', '/').replace('//', '/').replace('http:/', 'http://').replace('https:/', 'https://')
  52. data = json.loads(data, strict=False)
  53. for path in data.keys():
  54. path2 = expand_vars(path)
  55. print '-------------------------------------------------------'
  56. print 'searching:'
  57. path2 = path2.replace('\\', '/').replace('\\', '/').replace('//', '/').replace('//', '/')
  58. print path2
  59. print 'in:'
  60. path3 = self.path().replace('\\', '/').replace('\\', '/').replace('//', '/').replace('//', '/')
  61. print path3
  62. print '-------------------------------------------------------'
  63. path4 = re.sub(re.compile("^"+re.escape(path2), re.IGNORECASE), '', path3);
  64. print path4
  65. if path4 != path3:
  66. url = data[path][type]
  67. if url:
  68. if url[-1:] != '/':
  69. url = url+'/'
  70. import urllib
  71. return url+(re.sub("^/", '', urllib.quote(path4.encode('utf-8'))));
  72. #except:
  73. # return False
  74. else:
  75. return False
  76. def isUnderCurrentProject(self):
  77. path = self.path()
  78. path2 = self.path()
  79. for directory in SideBarProject().getDirectories():
  80. path2 = path2.replace(directory, '', 1)
  81. return path != path2
  82. def pathRelativeFromProject(self):
  83. return re.sub('^/+', '', self.pathWithoutProject())
  84. def pathRelativeFromProjectEncoded(self):
  85. import urllib
  86. return urllib.quote(self.pathRelativeFromProject().encode('utf-8'))
  87. def pathRelativeFromView(self):
  88. return os.path.relpath(self.path(), os.path.dirname(sublime.active_window().active_view().file_name())).replace('\\', '/')
  89. def pathRelativeFromViewEncoded(self):
  90. import urllib
  91. return urllib.quote(os.path.relpath(self.path(), os.path.dirname(sublime.active_window().active_view().file_name())).replace('\\', '/').encode('utf-8'))
  92. def pathAbsoluteFromProject(self):
  93. return self.pathWithoutProject()
  94. def pathAbsoluteFromProjectEncoded(self):
  95. import urllib
  96. return urllib.quote(self.pathAbsoluteFromProject().encode('utf-8'))
  97. def uri(self):
  98. import urllib
  99. return 'file:'+urllib.pathname2url(self.path().encode('utf-8'));
  100. def join(self, name):
  101. return os.path.join(self.path(), name)
  102. def dirname(self):
  103. branch, leaf = os.path.split(self.path())
  104. return branch;
  105. def forCwdSystemPath(self):
  106. if self.isDirectory():
  107. return self.pathSystem()
  108. else:
  109. return self.dirnameSystem()
  110. def forCwdSystemName(self):
  111. if self.isDirectory():
  112. return '.'
  113. else:
  114. path = self.pathSystem()
  115. branch = self.dirnameSystem()
  116. leaf = path.replace(branch, '', 1).replace('\\', '').replace('/', '')
  117. return leaf
  118. def forCwdSystemPathRelativeFrom(self, relativeFrom):
  119. relative = SideBarItem(relativeFrom, os.path.isdir(relativeFrom))
  120. path = self.pathSystem().replace(relative.pathSystem(), '', 1).replace('\\', '/')
  121. if path == '':
  122. return '.'
  123. else:
  124. return re.sub('^/+', '', path)
  125. def forCwdSystemPathRelativeFromRecursive(self, relativeFrom):
  126. relative = SideBarItem(relativeFrom, os.path.isdir(relativeFrom))
  127. path = self.pathSystem().replace(relative.pathSystem(), '', 1).replace('\\', '/')
  128. if path == '':
  129. return '.'
  130. else:
  131. if self.isDirectory():
  132. return re.sub('^/+', '', path)+'/'
  133. else:
  134. return re.sub('^/+', '', path)
  135. def dirnameSystem(self):
  136. import sys
  137. return self.dirname().encode(sys.getfilesystemencoding())
  138. def dirnameCreate(self):
  139. try:
  140. os.makedirs(self.dirname())
  141. except:
  142. pass
  143. def name(self):
  144. branch, leaf = os.path.split(self.path())
  145. return leaf;
  146. def nameSystem(self):
  147. import sys
  148. return self.name().encode(sys.getfilesystemencoding())
  149. def nameEncoded(self):
  150. import urllib
  151. return urllib.quote(self.name().encode('utf-8'));
  152. def namePretty(self):
  153. return self.name().replace(self.extension(), '').replace('-', ' ').replace('_', ' ').strip();
  154. def open(self):
  155. if sublime.platform() == 'osx':
  156. import subprocess
  157. subprocess.Popen(['open', '-a', self.nameSystem()], cwd=self.dirnameSystem())
  158. elif sublime.platform() == 'windows':
  159. import subprocess
  160. subprocess.Popen([self.nameSystem()], cwd=self.dirnameSystem(), shell=True)
  161. else:
  162. desktop.open(self.path())
  163. def edit(self):
  164. return sublime.active_window().open_file(self.path())
  165. def isDirectory(self):
  166. return self._is_directory
  167. def isFile(self):
  168. return self.isDirectory() == False
  169. def contentUTF8(self):
  170. import codecs
  171. return codecs.open(self.path(), 'r', 'utf-8').read()
  172. def contentBinary(self):
  173. return file(self.path(), "rb").read()
  174. def contentBase64(self):
  175. return 'data:'+self.mime()+';base64,'+(file(self.path(), "rb").read().encode("base64").replace('\n', ''))
  176. def reveal(self):
  177. sublime.active_window().run_command("open_dir", {"dir": self.dirname(), "file": self.name()} )
  178. def write(self, content):
  179. file(self.path(), 'w+').write(content)
  180. def mime(self):
  181. import mimetypes
  182. return mimetypes.guess_type(self.path())[0] or 'application/octet-stream'
  183. def extension(self):
  184. return os.path.splitext('name'+self.name())[1].lower()
  185. def exists(self):
  186. return os.path.isdir(self.path()) or os.path.isfile(self.path())
  187. def create(self):
  188. if self.isDirectory():
  189. self.dirnameCreate()
  190. os.makedirs(self.path())
  191. else:
  192. self.dirnameCreate()
  193. self.write('')
  194. def copy(self, location, replace = False):
  195. location = SideBarItem(location, os.path.isdir(location));
  196. if location.exists() and replace == False:
  197. return False
  198. elif location.exists() and location.isFile():
  199. os.remove(location.path())
  200. location.dirnameCreate();
  201. if self.isDirectory():
  202. if location.exists():
  203. self.copy_recursive(self.path(), location.path())
  204. else:
  205. shutil.copytree(self.path(), location.path())
  206. else:
  207. shutil.copy2(self.path(), location.path())
  208. return True
  209. def copy_recursive(self, _from, _to):
  210. if os.path.isfile(_from) or os.path.islink(_from):
  211. try:
  212. os.makedirs(os.path.dirname(_to));
  213. except:
  214. pass
  215. if os.path.exists(_to):
  216. os.remove(_to)
  217. shutil.copy2(_from, _to)
  218. else:
  219. try:
  220. os.makedirs(_to);
  221. except:
  222. pass
  223. for content in os.listdir(_from):
  224. __from = os.path.join(_from, content)
  225. __to = os.path.join(_to, content)
  226. self.copy_recursive(__from, __to)
  227. def move(self, location, replace = False):
  228. location = SideBarItem(location, os.path.isdir(location));
  229. if location.exists() and replace == False:
  230. if self.path().lower() == location.path().lower():
  231. pass
  232. else:
  233. return False
  234. elif location.exists() and location.isFile():
  235. os.remove(location.path())
  236. if self.path().lower() == location.path().lower():
  237. location.dirnameCreate();
  238. os.rename(self.path(), location.path()+'.sublime-temp')
  239. os.rename(location.path()+'.sublime-temp', location.path())
  240. self._move_moveViews(self.path(), location.path())
  241. else:
  242. location.dirnameCreate();
  243. if location.exists():
  244. self.move_recursive(self.path(), location.path())
  245. else:
  246. os.rename(self.path(), location.path())
  247. self._move_moveViews(self.path(), location.path())
  248. return True
  249. def move_recursive(self, _from, _to):
  250. if os.path.isfile(_from) or os.path.islink(_from):
  251. try:
  252. os.makedirs(os.path.dirname(_to));
  253. except:
  254. pass
  255. if os.path.exists(_to):
  256. os.remove(_to)
  257. os.rename(_from, _to)
  258. else:
  259. try:
  260. os.makedirs(_to);
  261. except:
  262. pass
  263. for content in os.listdir(_from):
  264. __from = os.path.join(_from, content)
  265. __to = os.path.join(_to, content)
  266. self.move_recursive(__from, __to)
  267. os.rmdir(_from)
  268. def _move_moveViews(self, old, location):
  269. for window in sublime.windows():
  270. active_view = window.active_view()
  271. views = []
  272. for view in window.views():
  273. if view.file_name():
  274. views.append(view)
  275. views.reverse();
  276. for view in views:
  277. if old == view.file_name():
  278. active_view = self._move_moveView(window, view, location, active_view)
  279. elif view.file_name().find(old+'\\') == 0:
  280. active_view = self._move_moveView(window, view, view.file_name().replace(old+'\\', location+'\\', 1), active_view)
  281. elif view.file_name().find(old+'/') == 0:
  282. active_view = self._move_moveView(window, view, view.file_name().replace(old+'/', location+'/', 1), active_view)
  283. def _move_moveView(self, window, view, location, active_view):
  284. if active_view == view:
  285. is_active_view = True
  286. else:
  287. is_active_view = False
  288. options = Object()
  289. options.scroll = view.viewport_position()
  290. options.selections = [[item.a, item.b] for item in view.sel()]
  291. options.marks = [[item.a, item.b] for item in view.get_regions("mark")]
  292. options.bookmarks = [[item.a, item.b] for item in view.get_regions("bookmarks")]
  293. if int(sublime.version()) >= 2167:
  294. options.folds = [[item.a, item.b] for item in view.folded_regions()]
  295. else:
  296. options.folds = [[item.a, item.b] for item in view.unfold(sublime.Region(0, view.size()))]
  297. options.syntax = view.settings().get('syntax')
  298. try:
  299. _window = window or view.window() or sublime.active_window()
  300. options.position = _window.get_view_index(view)
  301. except:
  302. options.position = False
  303. window.focus_view(view)
  304. if view.is_dirty():
  305. options.content = view.substr(sublime.Region(0, view.size()))
  306. view.window().run_command('revert')
  307. else:
  308. options.content = False
  309. _view = view
  310. view = window.open_file(location)
  311. window.focus_view(_view)
  312. window.run_command('close')
  313. sublime.set_timeout(lambda: self._move_restoreView(view, options, window), 200)
  314. if is_active_view:
  315. window.focus_view(view)
  316. return view
  317. else:
  318. window.focus_view(active_view)
  319. return active_view
  320. def _move_restoreView(self, view, options, window):
  321. if view.is_loading():
  322. sublime.set_timeout(lambda: self._move_restoreView(view, options, window), 100)
  323. else:
  324. if options.content != False:
  325. edit = view.begin_edit()
  326. view.replace(edit, sublime.Region(0, view.size()), options.content);
  327. view.sel().clear()
  328. view.sel().add(sublime.Region(0))
  329. view.end_edit(edit)
  330. if options.position != False:
  331. try:
  332. _window = window or view.window() or sublime.active_window()
  333. group, index = options.position
  334. _window.set_view_index(view, group, index)
  335. except:
  336. pass
  337. if options.syntax:
  338. view.settings().set('syntax', options.syntax);
  339. for r in options.folds:
  340. view.fold(sublime.Region(r[0], r[1]))
  341. view.sel().clear()
  342. for r in options.selections:
  343. view.sel().add(sublime.Region(r[0], r[1]))
  344. rs = []
  345. for r in options.marks:
  346. rs.append(sublime.Region(r[0], r[1]))
  347. if len(rs):
  348. view.add_regions("mark", rs, "mark", "dot", sublime.HIDDEN | sublime.PERSISTENT)
  349. rs = []
  350. for r in options.bookmarks:
  351. rs.append(sublime.Region(r[0], r[1]))
  352. if len(rs):
  353. view.add_regions("bookmarks", rs, "bookmarks", "bookmark", sublime.HIDDEN | sublime.PERSISTENT)
  354. view.set_viewport_position(options.scroll, False)
  355. def close_associated_buffers(self):
  356. path = self.path()
  357. closed_items = []
  358. for window in sublime.windows():
  359. active_view = window.active_view()
  360. views = []
  361. for view in window.views():
  362. if view.file_name():
  363. views.append(view)
  364. views.reverse();
  365. for view in views:
  366. if path == view.file_name():
  367. if view.window():
  368. closed_items.append([view.file_name(), view.window(), view.window().get_view_index(view)])
  369. if len(window.views()) == 1:
  370. window.new_file()
  371. window.focus_view(view)
  372. window.run_command('revert')
  373. window.run_command('close')
  374. elif view.file_name().find(path+'\\') == 0:
  375. if view.window():
  376. closed_items.append([view.file_name(), view.window(), view.window().get_view_index(view)])
  377. if len(window.views()) == 1:
  378. window.new_file()
  379. window.focus_view(view)
  380. window.run_command('revert')
  381. window.run_command('close')
  382. elif view.file_name().find(path+'/') == 0:
  383. if view.window():
  384. closed_items.append([view.file_name(), view.window(), view.window().get_view_index(view)])
  385. if len(window.views()) == 1:
  386. window.new_file()
  387. window.focus_view(view)
  388. window.run_command('revert')
  389. window.run_command('close')
  390. # try to repaint
  391. try:
  392. window.focus_view(active_view)
  393. window.focus_view(window.active_view())
  394. except:
  395. try:
  396. window.focus_view(window.active_view())
  397. except:
  398. pass
  399. return closed_items