Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.91 KB | None | 0 0
  1. menu.addSeparator()
  2. menu.addMenuitem('Extra item')
  3.  
  4. from __future__ import unicode_literals
  5. # Import the PyQt and QGIS libraries
  6. import os
  7. import sys
  8. from qgis.core import *
  9.  
  10. from PyQt4 import QtWebKit
  11. from PyQt4.QtCore import *
  12. from PyQt4.QtGui import *
  13. from PyQt4 import QtXml
  14.  
  15. from menu_conf_dlg import menu_conf_dlg
  16.  
  17. # Initialize Qt resources from file resources.py
  18. import resources
  19.  
  20.  
  21. def getFirstChildByTagNameValue(elt, tagName, key, value):
  22. nodes = elt.elementsByTagName(tagName)
  23. for node in (nodes.at(i) for i in range(nodes.size())):
  24. idNode = node.namedItem(key)
  25. if idNode and value == idNode.firstChild().toText().data():
  26. # layer founds
  27. return node
  28.  
  29. return None
  30.  
  31. class menu_from_project:
  32.  
  33. def __init__(self, iface):
  34. self.path = QFileInfo(os.path.realpath(__file__)).path()
  35. self.iface = iface
  36. self.toolBar = None
  37.  
  38. # new multi projects var
  39. self.projects = []
  40. self.menubarActions = []
  41. self.canvas = self.iface.mapCanvas()
  42. self.optionTooltip = (False)
  43. self.optionCreateGroup = (False)
  44. self.optionLoadAll = (False)
  45. self.read()
  46.  
  47. # default lang
  48. locale = QSettings().value("locale/userLocale")
  49. self.myLocale = locale[0:2]
  50.  
  51.  
  52. def store(self):
  53. s = QSettings()
  54. s.remove("menu_from_project/projectFilePath")
  55.  
  56. index = 0
  57.  
  58. s.setValue("menu_from_project/optionTooltip", (self.optionTooltip))
  59. s.setValue("menu_from_project/optionCreateGroup", (self.optionCreateGroup))
  60. s.setValue("menu_from_project/optionLoadAll", (self.optionLoadAll))
  61.  
  62. s.beginWriteArray("menu_from_project/projects")
  63. for project in self.projects:
  64. s.setArrayIndex(index)
  65. s.setValue("file", project["file"])
  66. s.setValue("name", project["name"])
  67. index = index + 1
  68.  
  69. s.endArray()
  70.  
  71. def read(self):
  72. s = QSettings()
  73. try:
  74. # old single project conf
  75. filePath = s.value("menu_from_project/projectFilePath", "")
  76.  
  77. if filePath:
  78. title = str(filePath).split('/')[-1]
  79. title = str(title).split('.')[0]
  80. self.projects.append({"file":filePath, "name":title})
  81. self.store()
  82. else:
  83. # patch : lecture ancienne conf
  84. size = s.beginReadArray("projects")
  85. for i in range(size):
  86. s.setArrayIndex(i)
  87. file = ((s.value("file").toString()))
  88. name = ((s.value("name").toString()))
  89. if file:
  90. self.projects.append({"file":file, "name":(name)})
  91. s.endArray()
  92.  
  93. size = s.beginReadArray("menu_from_project/projects")
  94. for i in range(size):
  95. s.setArrayIndex(i)
  96. file = s.value("file", "")
  97. name = s.value("name", "")
  98. if file != "":
  99. self.projects.append({"file":file, "name":name})
  100.  
  101. s.endArray()
  102.  
  103. self.optionTooltip = s.value("menu_from_project/optionTooltip", (True), type=bool)
  104.  
  105. # create group option only since 1.9
  106. self.optionCreateGroup = s.value("menu_from_project/optionCreateGroup", (False), type=bool)
  107. self.optionLoadAll = s.value("menu_from_project/optionLoadAll", (False), type=bool)
  108.  
  109. except:
  110. pass
  111.  
  112. def isAbsolute(self, doc):
  113. absolute = False
  114. try:
  115. props = doc.elementsByTagName("properties")
  116. if props.count()==1:
  117. node = props.at(0)
  118. pathNode = node.namedItem("Paths")
  119. absoluteNode = pathNode.namedItem("Absolute")
  120. absolute = ("true" == absoluteNode.firstChild().toText().data())
  121. except:
  122. pass
  123.  
  124. return absolute
  125.  
  126. def _actionHovered(self, action):
  127. tip = action.toolTip()
  128. if (tip != "-"):
  129. QToolTip.showText(QCursor.pos(), tip)
  130. else:
  131. QToolTip.hideText()
  132.  
  133. def getMaplayerDomFromQgs(self, fileName, layerId):
  134. xml = file(unicode(fileName)).read()
  135. doc = QtXml.QDomDocument()
  136. doc.setContent(xml)
  137.  
  138. maplayers = doc.elementsByTagName("maplayer")
  139. for ml in (maplayers.item(i) for i in range(maplayers.size())):
  140. idelt = ml.namedItem("id")
  141. id = ""
  142.  
  143. if idelt and layerId == idelt.firstChild().toText().data():
  144. return ml
  145.  
  146. return None
  147.  
  148. def addMenuItem(self, filename, node, menu, domdoc):
  149. yaLayer = False
  150. initialFilename = filename
  151.  
  152. if node == None:
  153. return yaLayer
  154.  
  155. element = node.toElement()
  156.  
  157. # if legendlayer tag
  158. if node.nodeName() == "legendlayer":
  159. try:
  160. legendlayerfileElt = element.firstChild().firstChildElement("legendlayerfile")
  161. layerId = legendlayerfileElt.attribute("layerid")
  162. action = QAction(element.attribute("name"), self.iface.mainWindow())
  163.  
  164. if (self.optionTooltip == (True)):
  165. try:
  166. maplayers = domdoc.elementsByTagName("maplayer")
  167. for ml in (maplayers.item(i) for i in range(maplayers.size())):
  168. idelt = ml.namedItem("id")
  169. id = ""
  170.  
  171. if (idelt != None):
  172. id = idelt.firstChild().toText().data()
  173.  
  174. attrEmbedded = ml.toElement().attribute("embedded", "0")
  175. if (attrEmbedded == "1"):
  176. id = ml.toElement().attribute("id", "")
  177.  
  178. if (id == layerId):
  179. # embedded layers ?
  180. embeddedFilename = ""
  181. if (attrEmbedded == "1"):
  182. try:
  183. embeddedFilename = ml.toElement().attribute("project", "")
  184. # read embedded project
  185. if not self.absolute and (embeddedFilename.find(".")==0):
  186. embeddedFilename = self.projectpath + "/" + embeddedFilename
  187.  
  188. ml = self.getMaplayerDomFromQgs(embeddedFilename, id)
  189. filename = embeddedFilename
  190. except:
  191. pass
  192.  
  193. if ml != None:
  194. try:
  195. title = ml.namedItem("title").firstChild().toText().data()
  196. abstract = ml.namedItem("abstract").firstChild().toText().data()
  197.  
  198. action.setStatusTip(title)
  199. if (abstract != "") and (title == ""):
  200. action.setToolTip("<p>%s</p>" % (abstract))
  201. else:
  202. if (abstract != "" or title != ""):
  203. action.setToolTip("<b>%s</b><br/>%s" % (title, abstract))
  204. else:
  205. action.setToolTip("-")
  206. except:
  207. pass
  208. else:
  209. QgsMessageLog.logMessage(id+" not found in project "+embeddedFilename, 'Extensions')
  210.  
  211. break
  212. except:
  213. pass
  214.  
  215. menu.addAction(action)
  216. yaLayer = True
  217. helper = lambda _filename,_who,_menu: (lambda: self.do_aeag_menu(_filename, _who, _menu))
  218. action.triggered.connect(helper(filename, layerId, menu))
  219. except:
  220. pass
  221.  
  222. nextNode = node.nextSibling()
  223. if (nextNode != None):
  224. # ! recursion
  225. self.addMenuItem(initialFilename, nextNode, menu, domdoc)
  226. # / if element.tagName() == "legendlayer":
  227.  
  228. # if legendgroup tag
  229. if node.nodeName() == "legendgroup":
  230. name = element.attribute("name")
  231. if name == "-":
  232. menu.addSeparator()
  233. nextNode = node.nextSibling()
  234. if (nextNode != None):
  235. # ! recursion
  236. self.addMenuItem(initialFilename, nextNode, menu, domdoc)
  237.  
  238. elif name.startswith("-"):
  239. action = QAction(name[1:], self.iface.mainWindow())
  240. font = QFont()
  241. font.setBold(True)
  242. action.setFont(font)
  243. menu.addAction(action)
  244.  
  245. nextNode = node.nextSibling()
  246. if (nextNode != None):
  247. # ! recursion
  248. self.addMenuItem(initialFilename, nextNode, menu, domdoc)
  249.  
  250. else:
  251. #messageLog("Group %s" % (element.attribute("name")))
  252.  
  253. # construire sous-menu
  254. sousmenu = menu.addMenu('&'+element.attribute("name"))
  255. sousmenu.menuAction().setToolTip("-")
  256.  
  257. childNode = node.firstChild()
  258.  
  259. # ! recursion
  260. r = self.addMenuItem(initialFilename, childNode, sousmenu, domdoc)
  261.  
  262. if r and self.optionLoadAll and (len(sousmenu.actions()) > 1):
  263. action = QAction(QApplication.translate("menu_from_project", "&Load all", None, QApplication.UnicodeUTF8), self.iface.mainWindow())
  264. font = QFont()
  265. font.setBold(True)
  266. action.setFont(font)
  267. sousmenu.addAction(action)
  268. helper = lambda _filename,_who,_menu: (lambda: self.do_aeag_menu(_filename, _who, _menu))
  269. action.triggered.connect(helper(None, None, sousmenu))
  270.  
  271. nextNode = node.nextSibling()
  272. if (nextNode != None):
  273. # ! recursion
  274. self.addMenuItem(initialFilename, nextNode, menu, domdoc)
  275. # / if element.tagName() == "legendgroup":
  276. #below works but add a lot
  277. #menu.addSeparator()
  278. #menu.addMenuitem('actiontest')
  279. return yaLayer
  280.  
  281.  
  282. def addMenu(self, name, filename, domdoc):
  283. # main project menu
  284. menuBar = self.iface.editMenu().parentWidget()
  285. projectMenu = QMenu('&'+name, menuBar)
  286.  
  287. if (self.optionTooltip == (True)):
  288. projectMenu.hovered.connect(self._actionHovered)
  289.  
  290. projectAction = menuBar.addMenu(projectMenu)
  291. self.menubarActions.append(projectAction);
  292.  
  293. self.absolute = self.isAbsolute(domdoc)
  294. self.projectpath = QFileInfo(os.path.realpath(filename)).path()
  295.  
  296. # build menu on legend schema
  297. legends = domdoc.elementsByTagName("legend")
  298. if (legends.length() > 0):
  299. node = legends.item(0)
  300. if node:
  301. node = node.firstChild()
  302. self.addMenuItem(filename, node, projectMenu, domdoc)
  303.  
  304. # Seperate settings from actual content
  305.  
  306. def initMenus(self):
  307. menuBar = self.iface.editMenu().parentWidget()
  308. for action in self.menubarActions:
  309. menuBar.removeAction(action)
  310. del(action)
  311.  
  312. self.menubarActions = []
  313.  
  314. QgsApplication.setOverrideCursor(Qt.WaitCursor)
  315. for project in self.projects:
  316. try:
  317. xml = file(unicode(project["file"])).read()
  318. doc = QtXml.QDomDocument()
  319. doc.setContent(xml)
  320.  
  321. self.addMenu(project["name"], project["file"], doc)
  322. except:
  323. QgsMessageLog.logMessage('Menu from layer : invalid ' + str(project["file"]), 'Extensions')
  324. pass
  325.  
  326. QgsApplication.restoreOverrideCursor()
  327.  
  328.  
  329.  
  330. def initGui(self):
  331. # build menu
  332. self.initMenus()
  333.  
  334.  
  335.  
  336.  
  337. # run method that performs all the real work
  338. def do_aeag_menu(self, filename, who, menu=None):
  339. self.canvas.freeze(True)
  340. self.canvas.setRenderFlag(False)
  341. idxGroup = None
  342. theLayer = None
  343. groupName = None
  344. QgsApplication.setOverrideCursor(Qt.WaitCursor)
  345.  
  346. try:
  347. if type(menu.parentWidget()) == QMenu and self.optionCreateGroup:
  348. groupName = menu.title().replace("&", "")
  349.  
  350. idxGroup = self.iface.legendInterface().groups().index(groupName) if groupName in self.iface.legendInterface().groups() else -1
  351.  
  352. if idxGroup < 0:
  353. idxGroup = self.iface.legendInterface().addGroup(groupName, True)
  354.  
  355. # load all layers
  356. if filename == None and who == None and self.optionLoadAll:
  357. i = 0
  358. for action in reversed(menu.actions()):
  359. if action.text() != QApplication.translate("menu_from_project", "&Load all", None, QApplication.UnicodeUTF8):
  360. action.trigger()
  361. else:
  362. # read QGis project
  363. xml = file(unicode(filename)).read()
  364. doc = QtXml.QDomDocument()
  365. doc.setContent(xml)
  366.  
  367. # is project in relative path ?
  368. absolute = self.isAbsolute(doc)
  369.  
  370. node = getFirstChildByTagNameValue(doc.documentElement(), "maplayer", "id", who)
  371. if node:
  372. idNode = node.namedItem("id")
  373. # give it a new id (for multiple import)
  374. try:
  375. import uuid
  376. import re
  377. newLayerId = "L%s" % re.sub("[{}-]", "", QUuid.createUuid().toString())
  378. idNode.firstChild().toText().setData(newLayerId)
  379. except:
  380. pass
  381.  
  382. # if relative path, adapt datasource
  383. if not absolute:
  384. try:
  385. datasourceNode = node.namedItem("datasource")
  386. datasource = datasourceNode.firstChild().toText().data()
  387. providerNode = node.namedItem("provider")
  388. provider = providerNode.firstChild().toText().data()
  389.  
  390. if provider == "ogr" and (datasource.find(".")==0):
  391. projectpath = QFileInfo(os.path.realpath(filename)).path()
  392. newlayerpath = projectpath + "/" + datasource
  393. datasourceNode.firstChild().toText().setData(newlayerpath)
  394. except:
  395. pass
  396.  
  397. # read modified layer node
  398. QgsProject.instance().read(node)
  399.  
  400. if self.optionCreateGroup:
  401. theLayer = QgsMapLayerRegistry.instance().mapLayer(newLayerId)
  402.  
  403. if idxGroup >= 0 and theLayer != None:
  404. self.iface.mainWindow().statusBar().showMessage("Move to group "+str(idxGroup))
  405. self.iface.legendInterface().refreshLayerSymbology(theLayer)
  406. self.iface.legendInterface().moveLayer(theLayer, idxGroup)
  407. self.iface.legendInterface().refreshLayerSymbology(theLayer)
  408.  
  409.  
  410. except:
  411. QgsMessageLog.logMessage('Menu from layer : invalid ' + filename, 'Extensions')
  412. pass
  413.  
  414. self.canvas.freeze(False)
  415. self.canvas.setRenderFlag(True)
  416. self.canvas.refresh()
  417. QgsApplication.restoreOverrideCursor()
  418.  
  419.  
  420. def doLink( self, url ):
  421. if url.host() == "" :
  422. self.hdialog.ui.helpContent.page().currentFrame().load(url)
  423. else:
  424. QDesktopServices.openUrl( url )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement