dialogs.py 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624
  1. """!
  2. @package gui_core.dialogs
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - dialogs::SimpleDialog
  6. - dialogs::LocationDialog
  7. - dialogs::MapsetDialog
  8. - dialogs::NewVectorDialog
  9. - dialogs::SavedRegion
  10. - dialogs::DecorationDialog
  11. - dialogs::TextLayerDialog
  12. - dialogs::GroupDialog
  13. - dialogs::MapLayersDialog
  14. - dialogs::ImportDialog
  15. - dialogs::GdalImportDialog
  16. - dialogs::GdalOutputDialog
  17. - dialogs::DxfImportDialog
  18. - dialogs::LayersList (used by MultiImport)
  19. - dialogs::SetOpacityDialog
  20. - dialogs::ImageSizeDialog
  21. - dialogs::SqlQueryFrame
  22. - dialogs::SymbolDialog
  23. (C) 2008-2011 by the GRASS Development Team
  24. This program is free software under the GNU General Public License
  25. (>=v2). Read the file COPYING that comes with GRASS for details.
  26. @author Martin Landa <landa.martin gmail.com>
  27. @author Anna Kratochvilova <kratochanna gmail.com> (GroupDialog, SymbolDialog)
  28. """
  29. import os
  30. import sys
  31. import re
  32. from bisect import bisect
  33. import wx
  34. import wx.lib.filebrowsebutton as filebrowse
  35. import wx.lib.mixins.listctrl as listmix
  36. from grass.script import core as grass
  37. from grass.script import task as gtask
  38. from grass.pydispatch.signal import Signal
  39. from core import globalvar
  40. from core.gcmd import GError, RunCommand, GMessage
  41. from gui_core.gselect import LocationSelect, MapsetSelect, Select, OgrTypeSelect, GdalSelect, MapsetSelect
  42. from gui_core.forms import GUI
  43. from gui_core.widgets import SingleSymbolPanel, GListCtrl, SimpleValidator
  44. from core.utils import GetLayerNameFromCmd, GetValidLayerName, _
  45. from core.settings import UserSettings, GetDisplayVectSettings
  46. from core.debug import Debug
  47. class SimpleDialog(wx.Dialog):
  48. def __init__(self, parent, title, id = wx.ID_ANY,
  49. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  50. **kwargs):
  51. """!General dialog to choose given element (location, mapset, vector map, etc.)
  52. @param parent window
  53. @param title window title
  54. """
  55. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  56. self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
  57. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  58. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  59. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  60. self.btnOK.SetDefault()
  61. self.__layout()
  62. self.warning = _("Required item is not set.")
  63. def __layout(self):
  64. """!Do layout"""
  65. self.sizer = wx.BoxSizer(wx.VERTICAL)
  66. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  67. # self.informLabel = wx.StaticText(self.panel, id = wx.ID_ANY)
  68. # buttons
  69. btnSizer = wx.StdDialogButtonSizer()
  70. btnSizer.AddButton(self.btnCancel)
  71. btnSizer.AddButton(self.btnOK)
  72. btnSizer.Realize()
  73. self.sizer.Add(item = self.dataSizer, proportion = 1,
  74. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  75. # self.sizer.Add(item = self.informLabel, proportion = 0, flag = wx.ALL, border = 5)
  76. self.sizer.Add(item = btnSizer, proportion = 0,
  77. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  78. def ValidatorCallback(self, win):
  79. GMessage(parent = self, message = self.warning)
  80. # self.informLabel.SetForegroundColour(wx.Colour(255, 0, 0))
  81. # self.informLabel.SetLabel(self.warning)
  82. class LocationDialog(SimpleDialog):
  83. """!Dialog used to select location"""
  84. def __init__(self, parent, title = _("Select GRASS location and mapset")):
  85. SimpleDialog.__init__(self, parent, title)
  86. self.element1 = LocationSelect(parent = self.panel, id = wx.ID_ANY,
  87. size = globalvar.DIALOG_GSELECT_SIZE,
  88. validator = SimpleValidator(callback = self.ValidatorCallback))
  89. self.element1.Bind(wx.EVT_TEXT, self.OnLocation)
  90. self.element2 = MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  91. size = globalvar.DIALOG_GSELECT_SIZE,
  92. setItems = False, skipCurrent = True,
  93. validator = SimpleValidator(callback = self.ValidatorCallback))
  94. self.element1.SetFocus()
  95. self.warning = _("Location or mapset is missing.")
  96. self._layout()
  97. self.SetMinSize(self.GetSize())
  98. def _layout(self):
  99. """!Do layout"""
  100. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  101. label = _("Name of GRASS location:")),
  102. proportion = 0, flag = wx.ALL, border = 1)
  103. self.dataSizer.Add(self.element1, proportion = 0,
  104. flag = wx.EXPAND | wx.ALL, border = 1)
  105. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  106. label = _("Name of mapset:")), proportion = 0,
  107. flag = wx.EXPAND | wx.ALL, border = 1)
  108. self.dataSizer.Add(self.element2, proportion = 0,
  109. flag = wx.EXPAND | wx.ALL, border = 1)
  110. self.panel.SetSizer(self.sizer)
  111. self.sizer.Fit(self)
  112. def OnLocation(self, event):
  113. """!Select mapset given location name"""
  114. location = event.GetString()
  115. if location:
  116. dbase = grass.gisenv()['GISDBASE']
  117. self.element2.UpdateItems(dbase = dbase, location = location)
  118. self.element2.SetSelection(0)
  119. mapset = self.element2.GetStringSelection()
  120. def GetValues(self):
  121. """!Get location, mapset"""
  122. return (self.element1.GetValue(), self.element2.GetValue())
  123. class MapsetDialog(SimpleDialog):
  124. """!Dialog used to select mapset"""
  125. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  126. location = None):
  127. SimpleDialog.__init__(self, parent, title)
  128. if location:
  129. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  130. else:
  131. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  132. self.element = MapsetSelect(parent = self.panel, id = wx.ID_ANY, skipCurrent = True,
  133. size = globalvar.DIALOG_GSELECT_SIZE,
  134. validator = SimpleValidator(callback = self.ValidatorCallback))
  135. self.element.SetFocus()
  136. self.warning = _("Name of mapset is missing.")
  137. self._layout()
  138. self.SetMinSize(self.GetSize())
  139. def _layout(self):
  140. """!Do layout"""
  141. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  142. label = _("Name of mapset:")),
  143. proportion = 0, flag = wx.ALL, border = 1)
  144. self.dataSizer.Add(self.element, proportion = 0,
  145. flag = wx.EXPAND | wx.ALL, border = 1)
  146. self.panel.SetSizer(self.sizer)
  147. self.sizer.Fit(self)
  148. def GetMapset(self):
  149. return self.element.GetValue()
  150. class NewVectorDialog(SimpleDialog):
  151. def __init__(self, parent, title = _("Create new vector map"),
  152. disableAdd = False, disableTable = False, showType = False):
  153. """!Dialog for creating new vector map
  154. @param parent parent window
  155. @param title window title
  156. @param disableAdd disable 'add layer' checkbox
  157. @param disableTable disable 'create table' checkbox
  158. @param showType True to show feature type selector (used for creating new empty OGR layers)
  159. @return dialog instance
  160. """
  161. SimpleDialog.__init__(self, parent, title)
  162. self.element = Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  163. type = 'vector', mapsets = [grass.gisenv()['MAPSET'],],
  164. validator = SimpleValidator(callback = self.ValidatorCallback))
  165. self.element.SetFocus()
  166. # determine output format
  167. if showType:
  168. self.ftype = OgrTypeSelect(parent = self, panel = self.panel)
  169. else:
  170. self.ftype = None
  171. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  172. label = _("Create attribute table"))
  173. self.table.SetValue(True)
  174. if disableTable:
  175. self.table.Enable(False)
  176. if showType:
  177. self.keycol = None
  178. else:
  179. self.keycol = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  180. size = globalvar.DIALOG_SPIN_SIZE)
  181. self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
  182. if disableTable:
  183. self.keycol.Enable(False)
  184. self.addbox = wx.CheckBox(parent = self.panel,
  185. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  186. if disableAdd:
  187. self.addbox.SetValue(True)
  188. self.addbox.Enable(False)
  189. else:
  190. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  191. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  192. self.warning = _("Name of new vector map is missing.")
  193. self._layout()
  194. self.SetMinSize(self.GetSize())
  195. def OnTable(self, event):
  196. if self.keycol:
  197. self.keycol.Enable(event.IsChecked())
  198. def _layout(self):
  199. """!Do layout"""
  200. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  201. label = _("Name for new vector map:")),
  202. proportion = 0, flag = wx.ALL, border = 1)
  203. self.dataSizer.Add(item = self.element, proportion = 0,
  204. flag = wx.EXPAND | wx.ALL, border = 1)
  205. if self.ftype:
  206. self.dataSizer.AddSpacer(1)
  207. self.dataSizer.Add(item = self.ftype, proportion = 0,
  208. flag = wx.EXPAND | wx.ALL, border = 1)
  209. self.dataSizer.Add(item = self.table, proportion = 0,
  210. flag = wx.EXPAND | wx.ALL, border = 1)
  211. if self.keycol:
  212. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  213. keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
  214. proportion = 0,
  215. flag = wx.ALIGN_CENTER_VERTICAL)
  216. keySizer.AddSpacer(10)
  217. keySizer.Add(item = self.keycol, proportion = 0,
  218. flag = wx.ALIGN_RIGHT)
  219. self.dataSizer.Add(item = keySizer, proportion = 1,
  220. flag = wx.EXPAND | wx.ALL, border = 1)
  221. self.dataSizer.AddSpacer(5)
  222. self.dataSizer.Add(item = self.addbox, proportion = 0,
  223. flag = wx.EXPAND | wx.ALL, border = 1)
  224. self.panel.SetSizer(self.sizer)
  225. self.sizer.Fit(self)
  226. def GetName(self, full = False):
  227. """!Get name of vector map to be created
  228. @param full True to get fully qualified name
  229. """
  230. name = self.element.GetValue()
  231. if full:
  232. if '@' in name:
  233. return name
  234. else:
  235. return name + '@' + grass.gisenv()['MAPSET']
  236. return name.split('@', 1)[0]
  237. def GetKey(self):
  238. """!Get key column name"""
  239. if self.keycol:
  240. return self.keycol.GetValue()
  241. return UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
  242. def IsChecked(self, key):
  243. """!Get dialog properties
  244. @param key window key ('add', 'table')
  245. @return True/False
  246. @return None on error
  247. """
  248. if key == 'add':
  249. return self.addbox.IsChecked()
  250. elif key == 'table':
  251. return self.table.IsChecked()
  252. return None
  253. def GetFeatureType(self):
  254. """!Get feature type for OGR
  255. @return feature type as string
  256. @return None for native format
  257. """
  258. if self.ftype:
  259. return self.ftype.GetType()
  260. return None
  261. def CreateNewVector(parent, cmd, title = _('Create new vector map'),
  262. exceptMap = None, log = None,
  263. disableAdd = False, disableTable = False):
  264. """!Create new vector map layer
  265. @param cmd (prog, **kwargs)
  266. @param title window title
  267. @param exceptMap list of maps to be excepted
  268. @param log
  269. @param disableAdd disable 'add layer' checkbox
  270. @param disableTable disable 'create table' checkbox
  271. @return dialog instance
  272. @return None on error
  273. """
  274. vExternalOut = grass.parse_command('v.external.out', flags = 'g')
  275. isNative = vExternalOut['format'] == 'native'
  276. if cmd[0] == 'v.edit' and not isNative:
  277. showType = True
  278. else:
  279. showType = False
  280. dlg = NewVectorDialog(parent, title = title,
  281. disableAdd = disableAdd, disableTable = disableTable,
  282. showType = showType)
  283. if dlg.ShowModal() != wx.ID_OK:
  284. dlg.Destroy()
  285. return None
  286. outmap = dlg.GetName()
  287. key = dlg.GetKey()
  288. if outmap == exceptMap:
  289. GError(parent = parent,
  290. message = _("Unable to create vector map <%s>.") % outmap)
  291. dlg.Destroy()
  292. return None
  293. if dlg.table.IsEnabled() and not key:
  294. GError(parent = parent,
  295. message = _("Invalid or empty key column.\n"
  296. "Unable to create vector map <%s>.") % outmap)
  297. dlg.Destroy()
  298. return
  299. if outmap == '': # should not happen
  300. dlg.Destroy()
  301. return None
  302. # update cmd -> output name defined
  303. cmd[1][cmd[2]] = outmap
  304. if showType:
  305. cmd[1]['type'] = dlg.GetFeatureType()
  306. if isNative:
  307. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  308. else:
  309. listOfVectors = RunCommand('v.external',
  310. quiet = True,
  311. parent = parent,
  312. read = True,
  313. flags = 'l',
  314. dsn = vExternalOut['dsn']).splitlines()
  315. overwrite = False
  316. if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  317. outmap in listOfVectors:
  318. dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
  319. "in the current mapset. "
  320. "Do you want to overwrite it?") % outmap,
  321. caption = _("Overwrite?"),
  322. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  323. if dlgOw.ShowModal() == wx.ID_YES:
  324. overwrite = True
  325. else:
  326. dlgOw.Destroy()
  327. dlg.Destroy()
  328. return None
  329. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  330. overwrite = True
  331. ret = RunCommand(prog = cmd[0],
  332. parent = parent,
  333. overwrite = overwrite,
  334. **cmd[1])
  335. if ret != 0:
  336. dlg.Destroy()
  337. return None
  338. if not isNative:
  339. # create link for OGR layers
  340. RunCommand('v.external',
  341. overwrite = overwrite,
  342. parent = parent,
  343. dsn = vExternalOut['dsn'],
  344. layer = outmap)
  345. # create attribute table
  346. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  347. if isNative:
  348. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  349. RunCommand('db.connect',
  350. flags = 'c')
  351. Debug.msg(1, "SQL: %s" % sql)
  352. RunCommand('db.execute',
  353. quiet = True,
  354. parent = parent,
  355. input = '-',
  356. stdin = sql)
  357. RunCommand('v.db.connect',
  358. quiet = True,
  359. parent = parent,
  360. map = outmap,
  361. table = outmap,
  362. key = key,
  363. layer = '1')
  364. # TODO: how to deal with attribute tables for OGR layers?
  365. # return fully qualified map name
  366. if '@' not in outmap:
  367. outmap += '@' + grass.gisenv()['MAPSET']
  368. if log:
  369. log.WriteLog(_("New vector map <%s> created") % outmap)
  370. return dlg
  371. class SavedRegion(wx.Dialog):
  372. def __init__(self, parent, title, id = wx.ID_ANY, loadsave = 'load',
  373. **kwargs):
  374. """!Loading or saving of display extents to saved region file
  375. @param loadsave load or save region?
  376. """
  377. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  378. self.loadsave = loadsave
  379. self.wind = ''
  380. sizer = wx.BoxSizer(wx.VERTICAL)
  381. box = wx.BoxSizer(wx.HORIZONTAL)
  382. label = wx.StaticText(parent = self, id = wx.ID_ANY)
  383. box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  384. if loadsave == 'load':
  385. label.SetLabel(_("Load region:"))
  386. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  387. type = 'windows')
  388. elif loadsave == 'save':
  389. label.SetLabel(_("Save region:"))
  390. selection = Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  391. type = 'windows', mapsets = [grass.gisenv()['MAPSET']], fullyQualified = False)
  392. box.Add(item = selection, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  393. selection.SetFocus()
  394. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  395. sizer.Add(item = box, proportion = 0, flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  396. border = 5)
  397. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
  398. sizer.Add(item = line, proportion = 0,
  399. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  400. btnsizer = wx.StdDialogButtonSizer()
  401. btn = wx.Button(parent = self, id = wx.ID_OK)
  402. btn.SetDefault()
  403. btnsizer.AddButton(btn)
  404. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  405. btnsizer.AddButton(btn)
  406. btnsizer.Realize()
  407. sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  408. self.SetSizer(sizer)
  409. sizer.Fit(self)
  410. self.Layout()
  411. def OnRegion(self, event):
  412. self.wind = event.GetString()
  413. def GetName(self):
  414. """!Return region name"""
  415. return self.wind
  416. DECOR_DIALOG_LEGEND = 0
  417. DECOR_DIALOG_BARSCALE = 1
  418. class DecorationDialog(wx.Dialog):
  419. """!Controls setting options and displaying/hiding map overlay
  420. decorations
  421. """
  422. def __init__(self, parent, title, giface, overlayController,
  423. ddstyle, **kwargs):
  424. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, **kwargs)
  425. self.parent = parent # MapFrame
  426. self._overlay = overlayController
  427. self._ddstyle = ddstyle
  428. self._giface = giface
  429. self._oldMouseUse = None
  430. self._oldCursor = None
  431. sizer = wx.BoxSizer(wx.VERTICAL)
  432. box = wx.BoxSizer(wx.HORIZONTAL)
  433. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY)
  434. self.chkbox.SetValue(True)
  435. if self._ddstyle == DECOR_DIALOG_LEGEND:
  436. self.chkbox.SetLabel("Show legend")
  437. else:
  438. self.chkbox.SetLabel("Show scale and North arrow")
  439. box.Add(item = self.chkbox, proportion = 0,
  440. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  441. sizer.Add(item = box, proportion = 0,
  442. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  443. box = wx.BoxSizer(wx.HORIZONTAL)
  444. optnbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set options"))
  445. box.Add(item = optnbtn, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  446. sizer.Add(item = box, proportion = 0,
  447. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  448. if self._ddstyle == DECOR_DIALOG_LEGEND:
  449. box = wx.BoxSizer(wx.HORIZONTAL)
  450. self.resizeBtn = wx.ToggleButton(parent = self, id = wx.ID_ANY, label = _("Set size and position"))
  451. self.resizeBtn.SetToolTipString(_("Click and drag on the map display to set legend "
  452. "size and position and then press OK"))
  453. self.resizeBtn.Disable()
  454. self.resizeBtn.Bind(wx.EVT_TOGGLEBUTTON, self.OnResize)
  455. box.Add(item = self.resizeBtn, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  456. sizer.Add(item = box, proportion = 0,
  457. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  458. box = wx.BoxSizer(wx.HORIZONTAL)
  459. if self._ddstyle == DECOR_DIALOG_LEGEND:
  460. labelText = _("Drag legend object with mouse in pointer mode to position.\n"
  461. "Double-click to change options.\n"
  462. "Define raster map name for legend in properties dialog.")
  463. else:
  464. labelText = _("Drag scale object with mouse in pointer mode to position.\n"
  465. "Double-click to change options.")
  466. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  467. label = labelText)
  468. box.Add(item = label, proportion = 0,
  469. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  470. sizer.Add(item = box, proportion = 0,
  471. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  472. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20,-1), style = wx.LI_HORIZONTAL)
  473. sizer.Add(item = line, proportion = 0,
  474. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  475. # buttons
  476. btnsizer = wx.StdDialogButtonSizer()
  477. self.btnOK = wx.Button(parent = self, id = wx.ID_OK)
  478. self.btnOK.SetDefault()
  479. self.btnOK.Enable(self._ddstyle != DECOR_DIALOG_LEGEND)
  480. btnsizer.AddButton(self.btnOK)
  481. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  482. btnsizer.AddButton(btnCancel)
  483. btnsizer.Realize()
  484. sizer.Add(item = btnsizer, proportion = 0,
  485. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  486. #
  487. # bindings
  488. #
  489. optnbtn.Bind(wx.EVT_BUTTON, self.OnOptions)
  490. btnCancel.Bind(wx.EVT_BUTTON, lambda evt: self.CloseDialog())
  491. self.btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
  492. self.SetSizer(sizer)
  493. sizer.Fit(self)
  494. mapName, found = GetLayerNameFromCmd(self._overlay.cmd)
  495. if found:
  496. # enable 'OK' and 'Resize' button
  497. self.btnOK.Enable()
  498. if not self.parent.IsPaneShown('3d'):
  499. self.resizeBtn.Enable()
  500. # set title
  501. self.SetTitle(_('Legend of raster map <%s>') % \
  502. mapName)
  503. def OnOptions(self, event):
  504. """!Sets option for decoration map overlays
  505. """
  506. if self._overlay.propwin is None:
  507. # build properties dialog
  508. GUI(parent = self.parent).ParseCommand(cmd = self._overlay.cmd,
  509. completed = (self.GetOptData, self._overlay.name, ''))
  510. else:
  511. if self._overlay.propwin.IsShown():
  512. self._overlay.propwin.SetFocus()
  513. else:
  514. self._overlay.propwin.Show()
  515. def OnResize(self, event):
  516. window = self._giface.GetMapWindow()
  517. if event.GetInt():
  518. self._oldMouseUse = window.mouse['use']
  519. self._oldCursor = window.GetCursor()
  520. window.SetCursor(self.parent.cursors["cross"])
  521. window.mouse['use'] = None
  522. window.mouse['box'] = 'box'
  523. window.pen = wx.Pen(colour = 'Black', width = 2, style = wx.SHORT_DASH)
  524. window.mouseLeftUp.connect(self._resizeLegend)
  525. else:
  526. self.Restore()
  527. self.DisconnectResizing()
  528. def Restore(self):
  529. """!Restore conditions before resizing"""
  530. window = self._giface.GetMapWindow()
  531. if self._oldCursor:
  532. window.SetCursor(self._oldCursor)
  533. if self._oldMouseUse:
  534. window.mouse['use'] = self._oldMouseUse
  535. def DisconnectResizing(self):
  536. self._giface.GetMapWindow().mouseLeftUp.disconnect(self._resizeLegend)
  537. def _resizeLegend(self, x, y):
  538. """!Update legend after drawing new legend size (moved from BufferedWindow)"""
  539. self.resizeBtn.SetValue(False)
  540. window = self._giface.GetMapWindow()
  541. self.DisconnectResizing()
  542. self.Restore()
  543. # resize legend
  544. screenSize = window.GetClientSizeTuple()
  545. self._overlay.ResizeLegend(window.mouse["begin"], window.mouse["end"], screenSize)
  546. # redraw
  547. self._giface.updateMap.emit()
  548. def CloseDialog(self):
  549. """!Hide dialog"""
  550. if self._ddstyle == DECOR_DIALOG_LEGEND and self.resizeBtn.GetValue():
  551. self.Restore()
  552. self.resizeBtn.SetValue(False)
  553. self.DisconnectResizing()
  554. self.Hide()
  555. def OnOK(self, event):
  556. """!Button 'OK' pressed"""
  557. # enable or disable overlay
  558. self._overlay.Show(self.chkbox.IsChecked())
  559. # update map
  560. if self.parent.IsPaneShown('3d'):
  561. self.parent.MapWindow.UpdateOverlays()
  562. self._giface.updateMap.emit()
  563. # hide dialog
  564. self.CloseDialog()
  565. def GetOptData(self, dcmd, layer, params, propwin):
  566. """!Process decoration layer data"""
  567. if dcmd:
  568. self._overlay.cmd = dcmd
  569. self._overlay.propwin = propwin
  570. if params:
  571. self.btnOK.Enable()
  572. if self._ddstyle == DECOR_DIALOG_LEGEND and not self.parent.IsPaneShown('3d'):
  573. self.resizeBtn.Enable()
  574. class TextLayerDialog(wx.Dialog):
  575. """
  576. Controls setting options and displaying/hiding map overlay decorations
  577. """
  578. def __init__(self, parent, ovlId, title, name = 'text',
  579. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE):
  580. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  581. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  582. self.ovlId = ovlId
  583. self.parent = parent
  584. if self.ovlId in self.parent.MapWindow.textdict.keys():
  585. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  586. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  587. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  588. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  589. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  590. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  591. else:
  592. self.currClr = wx.BLACK
  593. self.currText = ''
  594. self.currFont = self.GetFont()
  595. self.currRot = 0.0
  596. self.currCoords = [10, 10]
  597. self.currBB = wx.Rect()
  598. self.sizer = wx.BoxSizer(wx.VERTICAL)
  599. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  600. # show/hide
  601. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY,
  602. label = _('Show text object'))
  603. if self.parent.Map.GetOverlay(self.ovlId) is None:
  604. self.chkbox.SetValue(True)
  605. else:
  606. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  607. box.Add(item = self.chkbox, span = (1,2),
  608. flag = wx.ALIGN_LEFT|wx.ALL, border = 5,
  609. pos = (0, 0))
  610. # text entry
  611. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Enter text:"))
  612. box.Add(item = label,
  613. flag = wx.ALIGN_CENTER_VERTICAL,
  614. pos = (1, 0))
  615. self.textentry = ExpandoTextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (300,-1))
  616. self.textentry.SetFont(self.currFont)
  617. self.textentry.SetForegroundColour(self.currClr)
  618. self.textentry.SetValue(self.currText)
  619. # get rid of unneeded scrollbar when text box first opened
  620. self.textentry.SetClientSize((300,-1))
  621. box.Add(item = self.textentry,
  622. pos = (1, 1))
  623. # rotation
  624. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Rotation:"))
  625. box.Add(item = label,
  626. flag = wx.ALIGN_CENTER_VERTICAL,
  627. pos = (2, 0))
  628. self.rotation = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
  629. size = (75,-1), style = wx.SP_ARROW_KEYS)
  630. self.rotation.SetRange(-360, 360)
  631. self.rotation.SetValue(int(self.currRot))
  632. box.Add(item = self.rotation,
  633. flag = wx.ALIGN_RIGHT,
  634. pos = (2, 1))
  635. # font
  636. fontbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set font"))
  637. box.Add(item = fontbtn,
  638. flag = wx.ALIGN_RIGHT,
  639. pos = (3, 1))
  640. self.sizer.Add(item = box, proportion = 1,
  641. flag = wx.ALL, border = 10)
  642. # note
  643. box = wx.BoxSizer(wx.HORIZONTAL)
  644. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  645. label = _("Drag text with mouse in pointer mode "
  646. "to position.\nDouble-click to change options"))
  647. box.Add(item = label, proportion = 0,
  648. flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  649. self.sizer.Add(item = box, proportion = 0,
  650. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border = 5)
  651. line = wx.StaticLine(parent = self, id = wx.ID_ANY,
  652. size = (20,-1), style = wx.LI_HORIZONTAL)
  653. self.sizer.Add(item = line, proportion = 0,
  654. flag = wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border = 5)
  655. btnsizer = wx.StdDialogButtonSizer()
  656. btn = wx.Button(parent = self, id = wx.ID_OK)
  657. btn.SetDefault()
  658. btnsizer.AddButton(btn)
  659. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  660. btnsizer.AddButton(btn)
  661. btnsizer.Realize()
  662. self.sizer.Add(item = btnsizer, proportion = 0,
  663. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  664. self.SetSizer(self.sizer)
  665. self.sizer.Fit(self)
  666. # bindings
  667. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  668. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  669. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  670. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  671. def OnRefit(self, event):
  672. """!Resize text entry to match text"""
  673. self.sizer.Fit(self)
  674. def OnText(self, event):
  675. """!Change text string"""
  676. self.currText = event.GetString()
  677. def OnRotation(self, event):
  678. """!Change rotation"""
  679. self.currRot = event.GetInt()
  680. event.Skip()
  681. def OnSelectFont(self, event):
  682. """!Change font"""
  683. data = wx.FontData()
  684. data.EnableEffects(True)
  685. data.SetColour(self.currClr) # set colour
  686. data.SetInitialFont(self.currFont)
  687. dlg = wx.FontDialog(self, data)
  688. if dlg.ShowModal() == wx.ID_OK:
  689. data = dlg.GetFontData()
  690. self.currFont = data.GetChosenFont()
  691. self.currClr = data.GetColour()
  692. self.textentry.SetFont(self.currFont)
  693. self.textentry.SetForegroundColour(self.currClr)
  694. self.Layout()
  695. dlg.Destroy()
  696. def GetValues(self):
  697. """!Get text properties"""
  698. return { 'text' : self.currText,
  699. 'font' : self.currFont,
  700. 'color' : self.currClr,
  701. 'rotation' : self.currRot,
  702. 'coords' : self.currCoords,
  703. 'active' : self.chkbox.IsChecked() }
  704. class GroupDialog(wx.Dialog):
  705. """!Dialog for creating/editing groups"""
  706. def __init__(self, parent = None, defaultGroup = None,
  707. title = _("Create or edit imagery groups"),
  708. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  709. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  710. style = style, **kwargs)
  711. self.parent = parent
  712. self.defaultGroup = defaultGroup
  713. self.currentGroup = self.defaultGroup
  714. self.groupChanged = False
  715. self.bodySizer = self._createDialogBody()
  716. # buttons
  717. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  718. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  719. btnClose = wx.Button(parent = self, id = wx.ID_CANCEL)
  720. btnOk.SetToolTipString(_("Apply changes to selected group and close dialog"))
  721. btnApply.SetToolTipString(_("Apply changes to selected group"))
  722. btnClose.SetToolTipString(_("Close dialog, changes are not applied"))
  723. btnOk.SetDefault()
  724. # sizers & do layout
  725. # btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  726. # btnSizer.Add(item = btnClose, proportion = 0,
  727. # flag = wx.RIGHT | wx.ALIGN_RIGHT | wx.EXPAND, border = 5)
  728. # btnSizer.Add(item = btnApply, proportion = 0,
  729. # flag = wx.LEFT, border = 5)
  730. btnSizer = wx.StdDialogButtonSizer()
  731. btnSizer.AddButton(btnOk)
  732. btnSizer.AddButton(btnApply)
  733. btnSizer.AddButton(btnClose)
  734. btnSizer.Realize()
  735. mainSizer = wx.BoxSizer(wx.VERTICAL)
  736. mainSizer.Add(item = self.bodySizer, proportion = 1,
  737. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  738. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  739. style = wx.LI_HORIZONTAL), proportion = 0,
  740. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 10)
  741. mainSizer.Add(item = btnSizer, proportion = 0,
  742. flag = wx.ALL | wx.ALIGN_RIGHT, border = 10)
  743. self.SetSizer(mainSizer)
  744. mainSizer.Fit(self)
  745. btnOk.Bind(wx.EVT_BUTTON, self.OnOk)
  746. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  747. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  748. # set dialog min size
  749. self.SetMinSize(self.GetSize())
  750. def _createDialogBody(self):
  751. bodySizer = wx.BoxSizer(wx.VERTICAL)
  752. # group selection
  753. bodySizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  754. label = _("Select the group you want to edit or "
  755. "enter name of new group:")),
  756. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP, border = 10)
  757. self.groupSelect = Select(parent = self, type = 'group',
  758. mapsets = [grass.gisenv()['MAPSET']],
  759. size = globalvar.DIALOG_GSELECT_SIZE,
  760. fullyQualified = False) # searchpath?
  761. bodySizer.Add(item = self.groupSelect, flag = wx.TOP | wx.EXPAND, border = 5)
  762. bodySizer.AddSpacer(10)
  763. # layers in group
  764. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Raster maps in selected group:")),
  765. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, border = 5)
  766. buttonSizer = wx.BoxSizer(wx.VERTICAL)
  767. listSizer = wx.BoxSizer(wx.HORIZONTAL)
  768. self.layerBox = wx.ListBox(parent = self, id = wx.ID_ANY, size = (-1, 150),
  769. style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  770. listSizer.Add(item = self.layerBox, proportion = 1, flag = wx.EXPAND)
  771. self.addLayer = wx.Button(self, id = wx.ID_ADD)
  772. self.addLayer.SetToolTipString(_("Select map layers and add them to the list."))
  773. buttonSizer.Add(item = self.addLayer, flag = wx.BOTTOM, border = 10)
  774. self.removeLayer = wx.Button(self, id = wx.ID_REMOVE)
  775. self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
  776. buttonSizer.Add(item = self.removeLayer)
  777. listSizer.Add(item = buttonSizer, flag = wx.LEFT, border = 5)
  778. bodySizer.Add(item = listSizer, proportion = 1, flag = wx.EXPAND)
  779. self.infoLabel = wx.StaticText(parent = self, id = wx.ID_ANY)
  780. bodySizer.Add(item = self.infoLabel,
  781. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
  782. # TODO: subgroup can have a different name than the group
  783. # self.subGroup must be a text field, not a checkbox
  784. #self.subGroup = wx.CheckBox(parent = self, id = wx.ID_ANY,
  785. # label = _("Define also sub-group (same name as group)"))
  786. #self.subGroup.SetValue(True) # most of imagery modules requires also subgroup
  787. #bodySizer.Add(item = self.subGroup, flag = wx.BOTTOM | wx.EXPAND, border = 5)
  788. # bindings
  789. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  790. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  791. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  792. if self.defaultGroup:
  793. self.groupSelect.SetValue(self.defaultGroup)
  794. return bodySizer
  795. def OnAddLayer(self, event):
  796. """!Add new layer to listbox"""
  797. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  798. if dlg.ShowModal() != wx.ID_OK:
  799. dlg.Destroy()
  800. return
  801. layers = dlg.GetMapLayers()
  802. for layer in layers:
  803. if layer not in self.GetLayers():
  804. self.layerBox.Append(layer)
  805. self.groupChanged = True
  806. def OnRemoveLayer(self, event):
  807. """!Remove layer from listbox"""
  808. while self.layerBox.GetSelections():
  809. sel = self.layerBox.GetSelections()[0]
  810. self.layerBox.Delete(sel)
  811. self.groupChanged = True
  812. def GetLayers(self):
  813. """!Get layers"""
  814. return self.layerBox.GetItems()
  815. def OnGroupSelected(self, event):
  816. """!Text changed in group selector"""
  817. # callAfter must be called to close popup before other actions
  818. wx.CallAfter(self.GroupSelected)
  819. def GroupSelected(self):
  820. """!Group was selected, check if changes were apllied"""
  821. group = self.GetSelectedGroup()
  822. if self.currentGroup and self.groupChanged:
  823. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  824. "do you want to apply changes?") % self.currentGroup,
  825. caption = _("Unapplied changes"),
  826. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  827. if dlg.ShowModal() == wx.ID_YES:
  828. self.ApplyChanges()
  829. dlg.Destroy()
  830. maps = list()
  831. groups = self.GetExistGroups()
  832. if group in groups:
  833. maps = self.GetGroupLayers(group)
  834. self.ShowGroupLayers(maps)
  835. self.currentGroup = group
  836. self.groupChanged = False
  837. self.ClearNotification()
  838. def ShowGroupLayers(self, mapList):
  839. """!Show map layers in currently selected group"""
  840. self.layerBox.Set(mapList)
  841. def EditGroup(self, group):
  842. """!Edit selected group"""
  843. layersNew = self.GetLayers()
  844. layersOld = self.GetGroupLayers(group)
  845. add = []
  846. remove = []
  847. for layerNew in layersNew:
  848. if layerNew not in layersOld:
  849. add.append(layerNew)
  850. for layerOld in layersOld:
  851. if layerOld not in layersNew:
  852. remove.append(layerOld)
  853. kwargs = {}
  854. # TODO: self.subGroup must be a text field
  855. #if self.subGroup.IsChecked():
  856. # kwargs['subgroup'] = group
  857. ret = None
  858. if remove:
  859. ret = RunCommand('i.group',
  860. parent = self,
  861. group = group,
  862. flags = 'r',
  863. input = ','.join(remove),
  864. **kwargs)
  865. if add:
  866. ret = RunCommand('i.group',
  867. parent = self,
  868. group = group,
  869. input = ','.join(add),
  870. **kwargs)
  871. return ret
  872. def CreateNewGroup(self, group):
  873. """!Create new group"""
  874. layers = self.GetLayers()
  875. if not layers:
  876. GMessage(parent = self,
  877. message = _("No raster maps selected."))
  878. return 1
  879. kwargs = {}
  880. # TODO: self.subGroup must be a text field
  881. #if self.subGroup.IsChecked():
  882. # kwargs['subgroup'] = group
  883. return RunCommand('i.group',
  884. parent = self,
  885. group = group,
  886. input = layers,
  887. **kwargs)
  888. def GetExistGroups(self):
  889. """!Returns existing groups in current mapset"""
  890. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  891. def ShowResult(self, group, returnCode, create):
  892. """!Show if operation was successfull."""
  893. group += '@' + grass.gisenv()['MAPSET']
  894. if returnCode is None:
  895. label = _("No changes to apply in group <%s>.") % group
  896. elif returnCode == 0:
  897. if create:
  898. label = _("Group <%s> was successfully created.") % group
  899. else:
  900. label = _("Group <%s> was successfully changed.") % group
  901. else:
  902. if create:
  903. label = _("Creating of new group <%s> failed.") % group
  904. else:
  905. label = _("Changing of group <%s> failed.") % group
  906. self.infoLabel.SetLabel(label)
  907. wx.FutureCall(4000, self.ClearNotification)
  908. def GetSelectedGroup(self):
  909. """!Return currently selected group (without mapset)"""
  910. return self.groupSelect.GetValue().split('@')[0]
  911. def GetGroupLayers(self, group):
  912. """!Get layers in group"""
  913. kwargs = dict()
  914. kwargs['group'] = group
  915. # TODO: self.subGroup must be a text field
  916. #if self.subGroup.IsChecked():
  917. # kwargs['subgroup'] = group
  918. res = RunCommand('i.group',
  919. parent = self,
  920. flags = 'g',
  921. read = True, **kwargs)
  922. if not res:
  923. return []
  924. return res.splitlines()
  925. def ClearNotification(self):
  926. """!Clear notification string"""
  927. self.infoLabel.SetLabel("")
  928. def ApplyChanges(self):
  929. """!Create or edit group"""
  930. group = self.currentGroup
  931. if not group:
  932. GMessage(parent = self,
  933. message = _("No group selected."))
  934. return False
  935. groups = self.GetExistGroups()
  936. if group in groups:
  937. ret = self.EditGroup(group)
  938. self.ShowResult(group = group, returnCode = ret, create = False)
  939. else:
  940. ret = self.CreateNewGroup(group)
  941. self.ShowResult(group = group, returnCode = ret, create = True)
  942. self.groupChanged = False
  943. return True
  944. def OnApply(self, event):
  945. """!Apply changes"""
  946. self.ApplyChanges()
  947. def OnOk(self, event):
  948. """!Apply changes and close dialog"""
  949. if self.ApplyChanges():
  950. self.OnClose(event)
  951. def OnClose(self, event):
  952. """!Close dialog"""
  953. if not self.IsModal():
  954. self.Destroy()
  955. event.Skip()
  956. class MapLayersDialogBase(wx.Dialog):
  957. """!Base dialog for selecting map layers (raster, vector).
  958. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  959. MapLayersDialog. Base class contains core functionality.
  960. """
  961. def __init__(self, parent, title,
  962. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  963. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  964. style = style, **kwargs)
  965. self.parent = parent # GMFrame or ?
  966. self.applyAddingMapLayers = Signal('MapLayersDialogBase.applyAddingMapLayers')
  967. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  968. # dialog body
  969. self.bodySizer = self._createDialogBody()
  970. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  971. flag = wx.EXPAND | wx.ALL, border = 5)
  972. # update list of layer to be loaded
  973. self.map_layers = [] # list of map layers (full list type/mapset)
  974. self.LoadMapLayers(self.GetLayerType(cmd = True),
  975. self.mapset.GetStringSelection())
  976. self._fullyQualifiedNames()
  977. self._modelerDSeries()
  978. # buttons
  979. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  980. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  981. btnOk.SetDefault()
  982. # sizers & do layout
  983. self.btnSizer = wx.StdDialogButtonSizer()
  984. self.btnSizer.AddButton(btnCancel)
  985. self.btnSizer.AddButton(btnOk)
  986. self._addApplyButton()
  987. self.btnSizer.Realize()
  988. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  989. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  990. self.SetSizer(self.mainSizer)
  991. self.mainSizer.Fit(self)
  992. # set dialog min size
  993. self.SetMinSize(self.GetSize())
  994. def _modelerDSeries(self):
  995. """!Method used only by MapLayersDialogForModeler,
  996. for other subclasses does nothing.
  997. """
  998. pass
  999. def _addApplyButton(self):
  1000. """!Method used only by MapLayersDialog,
  1001. for other subclasses does nothing.
  1002. """
  1003. pass
  1004. def _fullyQualifiedNames(self):
  1005. """!Adds CheckBox which determines is fully qualified names are retuned.
  1006. """
  1007. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1008. label = _("Use fully-qualified map names"))
  1009. self.fullyQualified.SetValue(True)
  1010. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  1011. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1012. def _useFullyQualifiedNames(self):
  1013. return self.fullyQualified.IsChecked()
  1014. def _layerTypes(self):
  1015. """!Determines which layer types can be chosen.
  1016. Valid values:
  1017. - raster
  1018. - raster3d
  1019. - vector
  1020. """
  1021. return [_('raster'), _('3D raster'), _('vector')]
  1022. def _selectAll(self):
  1023. """!Check all layers by default"""
  1024. return True
  1025. def _createDialogBody(self):
  1026. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  1027. # layer type
  1028. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  1029. flag = wx.ALIGN_CENTER_VERTICAL,
  1030. pos = (0,0))
  1031. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  1032. choices = self._layerTypes(), size = (100,-1))
  1033. self.layerType.SetSelection(0)
  1034. bodySizer.Add(item = self.layerType,
  1035. pos = (0,1))
  1036. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1037. # select toggle
  1038. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1039. label = _("Select toggle"))
  1040. self.toggle.SetValue(self._selectAll())
  1041. bodySizer.Add(item = self.toggle,
  1042. flag = wx.ALIGN_CENTER_VERTICAL,
  1043. pos = (0,2))
  1044. # mapset filter
  1045. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  1046. flag = wx.ALIGN_CENTER_VERTICAL,
  1047. pos = (1,0))
  1048. self.mapset = MapsetSelect(parent = self, searchPath = True)
  1049. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1050. bodySizer.Add(item = self.mapset,
  1051. pos = (1,1), span = (1, 2))
  1052. # map name filter
  1053. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  1054. flag = wx.ALIGN_CENTER_VERTICAL,
  1055. pos = (2,0))
  1056. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1057. value = "",
  1058. size = (250,-1))
  1059. bodySizer.Add(item = self.filter,
  1060. flag = wx.EXPAND,
  1061. pos = (2,1), span = (1, 2))
  1062. self.filter.SetFocus()
  1063. self.filter.SetToolTipString(_("Put here a regular expression."
  1064. " Characters '.*' stand for anything,"
  1065. " character '^' stands for the beginning"
  1066. " and '$' for the end."))
  1067. # layer list
  1068. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  1069. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1070. pos = (3,0))
  1071. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1072. size = (250, 100),
  1073. choices = [])
  1074. bodySizer.Add(item = self.layers,
  1075. flag = wx.EXPAND,
  1076. pos = (3,1), span = (1, 2))
  1077. bodySizer.AddGrowableCol(1)
  1078. bodySizer.AddGrowableRow(3)
  1079. # bindings
  1080. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  1081. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1082. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1083. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1084. return bodySizer
  1085. def LoadMapLayers(self, type, mapset):
  1086. """!Load list of map layers
  1087. @param type layer type ('raster' or 'vector')
  1088. @param mapset mapset name
  1089. """
  1090. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  1091. self.layers.Set(self.map_layers)
  1092. # check all items by default
  1093. for item in range(self.layers.GetCount()):
  1094. self.layers.Check(item, check = self._selectAll())
  1095. def OnChangeParams(self, event):
  1096. """!Filter parameters changed by user"""
  1097. # update list of layer to be loaded
  1098. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1099. self.mapset.GetStringSelection())
  1100. event.Skip()
  1101. def OnMenu(self, event):
  1102. """!Table description area, context menu"""
  1103. if not hasattr(self, "popupID1"):
  1104. self.popupDataID1 = wx.NewId()
  1105. self.popupDataID2 = wx.NewId()
  1106. self.popupDataID3 = wx.NewId()
  1107. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1108. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  1109. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  1110. # generate popup-menu
  1111. menu = wx.Menu()
  1112. menu.Append(self.popupDataID1, _("Select all"))
  1113. menu.Append(self.popupDataID2, _("Invert selection"))
  1114. menu.Append(self.popupDataID3, _("Deselect all"))
  1115. self.PopupMenu(menu)
  1116. menu.Destroy()
  1117. def OnSelectAll(self, event):
  1118. """!Select all map layer from list"""
  1119. for item in range(self.layers.GetCount()):
  1120. self.layers.Check(item, True)
  1121. def OnSelectInvert(self, event):
  1122. """!Invert current selection"""
  1123. for item in range(self.layers.GetCount()):
  1124. if self.layers.IsChecked(item):
  1125. self.layers.Check(item, False)
  1126. else:
  1127. self.layers.Check(item, True)
  1128. def OnDeselectAll(self, event):
  1129. """!Select all map layer from list"""
  1130. for item in range(self.layers.GetCount()):
  1131. self.layers.Check(item, False)
  1132. def OnFilter(self, event):
  1133. """!Apply filter for map names"""
  1134. if len(event.GetString()) == 0:
  1135. self.layers.Set(self.map_layers)
  1136. return
  1137. list = []
  1138. for layer in self.map_layers:
  1139. try:
  1140. if re.compile(event.GetString()).search(layer):
  1141. list.append(layer)
  1142. except:
  1143. pass
  1144. self.layers.Set(list)
  1145. self.OnSelectAll(None)
  1146. event.Skip()
  1147. def OnToggle(self, event):
  1148. """!Select toggle (check or uncheck all layers)"""
  1149. check = event.Checked()
  1150. for item in range(self.layers.GetCount()):
  1151. self.layers.Check(item, check)
  1152. event.Skip()
  1153. def GetMapLayers(self):
  1154. """!Return list of checked map layers"""
  1155. layerNames = []
  1156. for indx in self.layers.GetSelections():
  1157. # layers.append(self.layers.GetStringSelec(indx))
  1158. pass
  1159. mapset = self.mapset.GetStringSelection()
  1160. for item in range(self.layers.GetCount()):
  1161. if not self.layers.IsChecked(item):
  1162. continue
  1163. if self._useFullyQualifiedNames():
  1164. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1165. else:
  1166. layerNames.append(self.layers.GetString(item))
  1167. return layerNames
  1168. def GetLayerType(self, cmd = False):
  1169. """!Get selected layer type
  1170. @param cmd True for g.mlist
  1171. """
  1172. if not cmd:
  1173. return self.layerType.GetStringSelection()
  1174. sel = self.layerType.GetSelection()
  1175. if sel == 0:
  1176. ltype = 'rast'
  1177. elif sel == 1:
  1178. ltype = 'rast3d'
  1179. else:
  1180. ltype = 'vect'
  1181. return ltype
  1182. class MapLayersDialog(MapLayersDialogBase):
  1183. """!Subclass of MapLayersDialogBase used in Layer Manager.
  1184. Contains apply button, which sends wxApplyMapLayers event.
  1185. """
  1186. def __init__(self, parent, title, **kwargs):
  1187. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1188. def _addApplyButton(self):
  1189. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  1190. self.btnSizer.AddButton(btnApply)
  1191. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1192. def OnApply(self, event):
  1193. self.applyAddingMapLayers.emit(mapLayers = self.GetMapLayers(),
  1194. ltype = self.GetLayerType(cmd = True))
  1195. class MapLayersDialogForGroups(MapLayersDialogBase):
  1196. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1197. Shows only raster maps.
  1198. """
  1199. def __init__(self, parent, title, **kwargs):
  1200. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1201. def _layerTypes(self):
  1202. return [_('raster'),]
  1203. def _selectAll(self):
  1204. """!Could be overriden"""
  1205. return False
  1206. def _fullyQualifiedNames(self):
  1207. pass
  1208. def _useFullyQualifiedNames(self):
  1209. return True
  1210. class MapLayersDialogForModeler(MapLayersDialogBase):
  1211. """!Subclass of MapLayersDialogBase used in Modeler.
  1212. """
  1213. def __init__(self, parent, title, **kwargs):
  1214. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1215. def _modelerDSeries(self):
  1216. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1217. label = _("Dynamic series (%s)") % 'g.mlist')
  1218. self.dseries.SetValue(False)
  1219. self.mainSizer.Add(item = self.dseries, proportion = 0,
  1220. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1221. def GetDSeries(self):
  1222. """!Used by modeler only
  1223. @return g.mlist command
  1224. """
  1225. if not self.dseries or not self.dseries.IsChecked():
  1226. return ''
  1227. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  1228. patt = self.filter.GetValue()
  1229. if patt:
  1230. cond += 'pattern=%s ' % patt
  1231. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1232. return cond
  1233. class ImportDialog(wx.Dialog):
  1234. """!Dialog for bulk import of various data (base class)"""
  1235. def __init__(self, parent, itype,
  1236. id = wx.ID_ANY, title = _("Multiple import"),
  1237. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1238. self.parent = parent # GMFrame
  1239. self.importType = itype
  1240. self.options = dict() # list of options
  1241. self.commandId = -1 # id of running command
  1242. wx.Dialog.__init__(self, parent, id, title, style = style,
  1243. name = "MultiImportDialog")
  1244. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1245. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  1246. if self.importType == 'gdal':
  1247. label = _("List of raster layers")
  1248. elif self.importType == 'ogr':
  1249. label = _("List of vector layers")
  1250. else:
  1251. label = _("List of %s layers") % self.importType.upper()
  1252. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  1253. # list of layers
  1254. columns = [_('Layer id'),
  1255. _('Layer name'),
  1256. _('Name for output GRASS map (editable)')]
  1257. if itype == 'ogr':
  1258. columns.insert(2, _('Feature type'))
  1259. columns.insert(3, _('Projection match'))
  1260. self.list = LayersList(parent = self.panel, columns = columns)
  1261. self.list.LoadData()
  1262. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1263. label = "%s" % _("Options"))
  1264. cmd = self._getCommand()
  1265. task = gtask.parse_interface(cmd)
  1266. for f in task.get_options()['flags']:
  1267. name = f.get('name', '')
  1268. desc = f.get('label', '')
  1269. if not desc:
  1270. desc = f.get('description', '')
  1271. if not name and not desc:
  1272. continue
  1273. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1274. continue
  1275. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1276. continue
  1277. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1278. continue
  1279. elif cmd == 'v.external' and name not in ('b'):
  1280. continue
  1281. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1282. continue
  1283. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1284. label = desc)
  1285. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1286. label = _("Allow output files to overwrite existing files"))
  1287. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1288. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1289. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1290. label = _("Close dialog on finish"))
  1291. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1292. #
  1293. # buttons
  1294. #
  1295. # cancel
  1296. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1297. self.btn_close.SetToolTipString(_("Close dialog"))
  1298. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1299. # run
  1300. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1301. self.btn_run.SetToolTipString(_("Import selected layers"))
  1302. self.btn_run.SetDefault()
  1303. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1304. def doLayout(self):
  1305. """!Do layout"""
  1306. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1307. # dsn input
  1308. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1309. flag = wx.EXPAND)
  1310. #
  1311. # list of DXF layers
  1312. #
  1313. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1314. layerSizer.Add(item = self.list, proportion = 1,
  1315. flag = wx.ALL | wx.EXPAND, border = 5)
  1316. dialogSizer.Add(item = layerSizer, proportion = 1,
  1317. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1318. # options
  1319. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1320. for key in self.options.keys():
  1321. optionSizer.Add(item = self.options[key], proportion = 0)
  1322. dialogSizer.Add(item = optionSizer, proportion = 0,
  1323. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1324. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1325. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1326. dialogSizer.Add(item = self.add, proportion = 0,
  1327. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1328. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1329. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1330. #
  1331. # buttons
  1332. #
  1333. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1334. btnsizer.Add(item = self.btn_close, proportion = 0,
  1335. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1336. border = 10)
  1337. btnsizer.Add(item = self.btn_run, proportion = 0,
  1338. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1339. border = 10)
  1340. dialogSizer.Add(item = btnsizer, proportion = 0,
  1341. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1342. border = 10)
  1343. # dialogSizer.SetSizeHints(self.panel)
  1344. self.panel.SetAutoLayout(True)
  1345. self.panel.SetSizer(dialogSizer)
  1346. dialogSizer.Fit(self.panel)
  1347. # auto-layout seems not work here - FIXME
  1348. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1349. self.SetMinSize(size)
  1350. self.SetSize((size.width, size.height + 100))
  1351. # width = self.GetSize()[0]
  1352. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1353. self.Layout()
  1354. def _getCommand(self):
  1355. """!Get command"""
  1356. return ''
  1357. def OnClose(self, event = None):
  1358. """!Close dialog"""
  1359. self.Close()
  1360. def OnRun(self, event):
  1361. """!Import/Link data (each layes as separate vector map)"""
  1362. pass
  1363. def AddLayers(self, returncode, cmd = None):
  1364. """!Add imported/linked layers into layer tree"""
  1365. if not self.add.IsChecked() or returncode != 0:
  1366. return
  1367. self.commandId += 1
  1368. maptree = self.parent.GetLayerTree()
  1369. layer, output = self.list.GetLayers()[self.commandId]
  1370. if '@' not in output:
  1371. name = output + '@' + grass.gisenv()['MAPSET']
  1372. else:
  1373. name = output
  1374. # add imported layers into layer tree
  1375. if self.importType == 'gdal':
  1376. cmd = ['d.rast',
  1377. 'map=%s' % name]
  1378. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1379. cmd.append('-n')
  1380. item = maptree.AddLayer(ltype = 'raster',
  1381. lname = name, lchecked = False,
  1382. lcmd = cmd, multiple = False)
  1383. else:
  1384. item = maptree.AddLayer(ltype = 'vector',
  1385. lname = name, lchecked = False,
  1386. lcmd = ['d.vect',
  1387. 'map=%s' % name] + GetDisplayVectSettings(),
  1388. multiple = False)
  1389. maptree.mapdisplay.MapWindow.ZoomToMap()
  1390. def OnAbort(self, event):
  1391. """!Abort running import
  1392. @todo not yet implemented
  1393. """
  1394. pass
  1395. class GdalImportDialog(ImportDialog):
  1396. def __init__(self, parent, giface, ogr = False, link = False):
  1397. """!Dialog for bulk import of various raster/vector data
  1398. @todo Split into GdalImportDialog and OgrImportDialog
  1399. @param parent parent window
  1400. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1401. @param link True for linking data otherwise importing data
  1402. """
  1403. self._giface = giface
  1404. self.link = link
  1405. self.ogr = ogr
  1406. if ogr:
  1407. ImportDialog.__init__(self, parent, itype = 'ogr')
  1408. if link:
  1409. self.SetTitle(_("Link external vector data"))
  1410. else:
  1411. self.SetTitle(_("Import vector data"))
  1412. else:
  1413. ImportDialog.__init__(self, parent, itype = 'gdal')
  1414. if link:
  1415. self.SetTitle(_("Link external raster data"))
  1416. else:
  1417. self.SetTitle(_("Import raster data"))
  1418. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1419. ogr = ogr, link = link)
  1420. self.dsnInput.reloadDataRequired.connect(lambda data: self.list.LoadData(data))
  1421. if link:
  1422. self.add.SetLabel(_("Add linked layers into layer tree"))
  1423. else:
  1424. self.add.SetLabel(_("Add imported layers into layer tree"))
  1425. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1426. if link:
  1427. self.btn_run.SetLabel(_("&Link"))
  1428. self.btn_run.SetToolTipString(_("Link selected layers"))
  1429. else:
  1430. self.btn_run.SetLabel(_("&Import"))
  1431. self.btn_run.SetToolTipString(_("Import selected layers"))
  1432. self.doLayout()
  1433. def OnRun(self, event):
  1434. """!Import/Link data (each layes as separate vector map)"""
  1435. self.commandId = -1
  1436. data = self.list.GetLayers()
  1437. if not data:
  1438. GMessage(_("No layers selected. Operation canceled."),
  1439. parent = self)
  1440. return
  1441. dsn = self.dsnInput.GetDsn()
  1442. ext = self.dsnInput.GetFormatExt()
  1443. # determine data driver for PostGIS links
  1444. popOGR = False
  1445. if self.importType == 'ogr' and \
  1446. self.dsnInput.GetType() == 'db' and \
  1447. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1448. 'GRASS_VECTOR_OGR' not in os.environ:
  1449. popOGR = True
  1450. os.environ['GRASS_VECTOR_OGR'] = '1'
  1451. for layer, output in data:
  1452. if self.importType == 'ogr':
  1453. if ext and layer.rfind(ext) > -1:
  1454. layer = layer.replace('.' + ext, '')
  1455. if self.link:
  1456. cmd = ['v.external',
  1457. 'dsn=%s' % dsn,
  1458. 'output=%s' % output,
  1459. 'layer=%s' % layer]
  1460. else:
  1461. cmd = ['v.in.ogr',
  1462. 'dsn=%s' % dsn,
  1463. 'layer=%s' % layer,
  1464. 'output=%s' % output]
  1465. else: # gdal
  1466. if self.dsnInput.GetType() == 'dir':
  1467. idsn = os.path.join(dsn, layer)
  1468. else:
  1469. idsn = dsn
  1470. if self.link:
  1471. cmd = ['r.external',
  1472. 'input=%s' % idsn,
  1473. 'output=%s' % output]
  1474. else:
  1475. cmd = ['r.in.gdal',
  1476. 'input=%s' % idsn,
  1477. 'output=%s' % output]
  1478. if self.overwrite.IsChecked():
  1479. cmd.append('--overwrite')
  1480. for key in self.options.keys():
  1481. if self.options[key].IsChecked():
  1482. cmd.append('-%s' % key)
  1483. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1484. '--overwrite' not in cmd:
  1485. cmd.append('--overwrite')
  1486. # run in Layer Manager
  1487. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1488. if popOGR:
  1489. os.environ.pop('GRASS_VECTOR_OGR')
  1490. if self.closeOnFinish.IsChecked():
  1491. self.Close()
  1492. def _getCommand(self):
  1493. """!Get command"""
  1494. if self.link:
  1495. if self.ogr:
  1496. return 'v.external'
  1497. else:
  1498. return 'r.external'
  1499. else:
  1500. if self.ogr:
  1501. return 'v.in.ogr'
  1502. else:
  1503. return 'r.in.gdal'
  1504. return ''
  1505. class GdalOutputDialog(wx.Dialog):
  1506. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1507. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1508. """!Dialog for setting output format for rasters/vectors
  1509. @todo Split into GdalOutputDialog and OgrOutputDialog
  1510. @param parent parent window
  1511. @param id window id
  1512. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1513. @param style window style
  1514. @param *kwargs other wx.Dialog's arguments
  1515. """
  1516. self.parent = parent # GMFrame
  1517. self.ogr = ogr
  1518. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1519. if self.ogr:
  1520. self.SetTitle(_("Define output format for vector data"))
  1521. else:
  1522. self.SetTitle(_("Define output format for raster data"))
  1523. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1524. # buttons
  1525. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1526. self.btnCancel.SetToolTipString(_("Close dialog"))
  1527. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1528. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1529. self.btnOk.SetDefault()
  1530. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1531. ogr = ogr,
  1532. exclude = ['file', 'protocol'], dest = True)
  1533. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1534. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1535. self._layout()
  1536. def _layout(self):
  1537. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1538. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1539. flag = wx.EXPAND)
  1540. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1541. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1542. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1543. border = 10)
  1544. btnSizer.Add(item = self.btnOk, proportion = 0,
  1545. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1546. border = 10)
  1547. dialogSizer.Add(item = btnSizer, proportion = 0,
  1548. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1549. border = 10)
  1550. self.panel.SetAutoLayout(True)
  1551. self.panel.SetSizer(dialogSizer)
  1552. dialogSizer.Fit(self.panel)
  1553. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1554. self.SetMinSize(size)
  1555. self.SetSize((size.width, size.height))
  1556. self.Layout()
  1557. def OnCancel(self, event):
  1558. self.Destroy()
  1559. def OnOK(self, event):
  1560. if self.dsnInput.GetType() == 'native':
  1561. RunCommand('v.external.out',
  1562. parent = self,
  1563. flags = 'r')
  1564. else:
  1565. dsn = self.dsnInput.GetDsn()
  1566. frmt = self.dsnInput.GetFormat()
  1567. options = self.dsnInput.GetOptions()
  1568. if not dsn:
  1569. GMessage(_("No data source selected."), parent=self)
  1570. return
  1571. RunCommand('v.external.out',
  1572. parent = self,
  1573. dsn = dsn, format = frmt,
  1574. options = options)
  1575. self.Close()
  1576. class DxfImportDialog(ImportDialog):
  1577. """!Dialog for bulk import of DXF layers"""
  1578. def __init__(self, parent, giface):
  1579. ImportDialog.__init__(self, parent, itype = 'dxf',
  1580. title = _("Import DXF layers"))
  1581. self._giface = giface
  1582. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1583. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1584. dialogTitle = _('Choose DXF file to import'),
  1585. buttonText = _('Browse'),
  1586. startDirectory = os.getcwd(), fileMode = 0,
  1587. changeCallback = self.OnSetDsn,
  1588. fileMask = "DXF File (*.dxf)|*.dxf")
  1589. self.add.SetLabel(_("Add imported layers into layer tree"))
  1590. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1591. self.doLayout()
  1592. def _getCommand(self):
  1593. """!Get command"""
  1594. return 'v.in.dxf'
  1595. def OnRun(self, event):
  1596. """!Import/Link data (each layes as separate vector map)"""
  1597. data = self.list.GetLayers()
  1598. if not data:
  1599. GMessage(_("No layers selected."), parent=self)
  1600. return
  1601. # hide dialog
  1602. self.Hide()
  1603. inputDxf = self.dsnInput.GetValue()
  1604. for layer, output in data:
  1605. cmd = ['v.in.dxf',
  1606. 'input=%s' % inputDxf,
  1607. 'layers=%s' % layer,
  1608. 'output=%s' % output]
  1609. for key in self.options.keys():
  1610. if self.options[key].IsChecked():
  1611. cmd.append('-%s' % key)
  1612. if self.overwrite.IsChecked() or \
  1613. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1614. cmd.append('--overwrite')
  1615. # run in Layer Manager
  1616. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1617. self.Close()
  1618. def OnSetDsn(self, event):
  1619. """!Input DXF file defined, update list of layer widget"""
  1620. path = event.GetString()
  1621. if not path:
  1622. return
  1623. data = list()
  1624. ret = RunCommand('v.in.dxf',
  1625. quiet = True,
  1626. parent = self,
  1627. read = True,
  1628. flags = 'l',
  1629. input = path)
  1630. if not ret:
  1631. self.list.LoadData()
  1632. return
  1633. for line in ret.splitlines():
  1634. layerId = line.split(':')[0].split(' ')[1]
  1635. layerName = line.split(':')[1].strip()
  1636. grassName = GetValidLayerName(layerName)
  1637. data.append((layerId, layerName.strip(), grassName.strip()))
  1638. self.list.LoadData(data)
  1639. class LayersList(GListCtrl, listmix.TextEditMixin):
  1640. """!List of layers to be imported (dxf, shp...)"""
  1641. def __init__(self, parent, columns, log = None):
  1642. GListCtrl.__init__(self, parent)
  1643. self.log = log
  1644. # setup mixins
  1645. listmix.TextEditMixin.__init__(self)
  1646. for i in range(len(columns)):
  1647. self.InsertColumn(i, columns[i])
  1648. if len(columns) == 3:
  1649. width = (65, 200)
  1650. else:
  1651. width = (65, 180, 90, 70)
  1652. for i in range(len(width)):
  1653. self.SetColumnWidth(col = i, width = width[i])
  1654. def LoadData(self, data = None):
  1655. """!Load data into list"""
  1656. self.DeleteAllItems()
  1657. if data is None:
  1658. return
  1659. for item in data:
  1660. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1661. for i in range(1, len(item)):
  1662. self.SetStringItem(index, i, "%s" % str(item[i]))
  1663. # check by default only on one item
  1664. if len(data) == 1:
  1665. self.CheckItem(index, True)
  1666. def OnLeftDown(self, event):
  1667. """!Allow editing only output name
  1668. Code taken from TextEditMixin class.
  1669. """
  1670. x, y = event.GetPosition()
  1671. colLocs = [0]
  1672. loc = 0
  1673. for n in range(self.GetColumnCount()):
  1674. loc = loc + self.GetColumnWidth(n)
  1675. colLocs.append(loc)
  1676. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1677. if col == self.GetColumnCount() - 1:
  1678. listmix.TextEditMixin.OnLeftDown(self, event)
  1679. else:
  1680. event.Skip()
  1681. def GetLayers(self):
  1682. """!Get list of layers (layer name, output name)"""
  1683. data = []
  1684. item = -1
  1685. while True:
  1686. item = self.GetNextItem(item)
  1687. if item == -1:
  1688. break
  1689. if not self.IsChecked(item):
  1690. continue
  1691. # layer / output name
  1692. data.append((self.GetItem(item, 1).GetText(),
  1693. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1694. return data
  1695. class SetOpacityDialog(wx.Dialog):
  1696. """!Set opacity of map layers"""
  1697. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1698. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1699. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1700. self.parent = parent # GMFrame
  1701. self.opacity = opacity # current opacity
  1702. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1703. size = size, style = style, title = title)
  1704. self.applyOpacity = Signal('SetOpacityDialog.applyOpacity')
  1705. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1706. sizer = wx.BoxSizer(wx.VERTICAL)
  1707. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1708. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1709. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1710. wx.SL_TOP | wx.SL_LABELS,
  1711. minValue = 0, maxValue = 100,
  1712. size = (350, -1))
  1713. box.Add(item = self.value,
  1714. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1715. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1716. label = _("transparent")),
  1717. pos = (1, 0))
  1718. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1719. label = _("opaque")),
  1720. flag = wx.ALIGN_RIGHT,
  1721. pos = (1, 1))
  1722. sizer.Add(item = box, proportion = 0,
  1723. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1724. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1725. style = wx.LI_HORIZONTAL)
  1726. sizer.Add(item = line, proportion = 0,
  1727. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1728. # buttons
  1729. btnsizer = wx.StdDialogButtonSizer()
  1730. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1731. btnOK.SetDefault()
  1732. btnsizer.AddButton(btnOK)
  1733. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1734. btnsizer.AddButton(btnCancel)
  1735. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1736. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1737. btnsizer.AddButton(btnApply)
  1738. btnsizer.Realize()
  1739. sizer.Add(item = btnsizer, proportion = 0,
  1740. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1741. panel.SetSizer(sizer)
  1742. sizer.Fit(panel)
  1743. self.SetSize(self.GetBestSize())
  1744. self.Layout()
  1745. def GetOpacity(self):
  1746. """!Button 'OK' pressed"""
  1747. # return opacity value
  1748. opacity = float(self.value.GetValue()) / 100
  1749. return opacity
  1750. def OnApply(self, event):
  1751. self.applyOpacity.emit(value = self.GetOpacity())
  1752. def GetImageHandlers(image):
  1753. """!Get list of supported image handlers"""
  1754. lext = list()
  1755. ltype = list()
  1756. for h in image.GetHandlers():
  1757. lext.append(h.GetExtension())
  1758. filetype = ''
  1759. if 'png' in lext:
  1760. filetype += "PNG file (*.png)|*.png|"
  1761. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1762. 'ext' : 'png' })
  1763. filetype += "BMP file (*.bmp)|*.bmp|"
  1764. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1765. 'ext' : 'bmp' })
  1766. if 'gif' in lext:
  1767. filetype += "GIF file (*.gif)|*.gif|"
  1768. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1769. 'ext' : 'gif' })
  1770. if 'jpg' in lext:
  1771. filetype += "JPG file (*.jpg)|*.jpg|"
  1772. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1773. 'ext' : 'jpg' })
  1774. if 'pcx' in lext:
  1775. filetype += "PCX file (*.pcx)|*.pcx|"
  1776. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1777. 'ext' : 'pcx' })
  1778. if 'pnm' in lext:
  1779. filetype += "PNM file (*.pnm)|*.pnm|"
  1780. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1781. 'ext' : 'pnm' })
  1782. if 'tif' in lext:
  1783. filetype += "TIF file (*.tif)|*.tif|"
  1784. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1785. 'ext' : 'tif' })
  1786. if 'xpm' in lext:
  1787. filetype += "XPM file (*.xpm)|*.xpm"
  1788. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1789. 'ext' : 'xpm' })
  1790. return filetype, ltype
  1791. class ImageSizeDialog(wx.Dialog):
  1792. """!Set size for saved graphic file"""
  1793. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1794. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1795. self.parent = parent
  1796. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1797. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1798. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1799. label = ' % s' % _("Image size"))
  1800. size = self.parent.GetWindow().GetClientSize()
  1801. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1802. style = wx.SP_ARROW_KEYS)
  1803. self.width.SetRange(20, 1e6)
  1804. self.width.SetValue(size.width)
  1805. wx.CallAfter(self.width.SetFocus)
  1806. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1807. style = wx.SP_ARROW_KEYS)
  1808. self.height.SetRange(20, 1e6)
  1809. self.height.SetValue(size.height)
  1810. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1811. size = (125, -1),
  1812. choices = [ "",
  1813. "640x480",
  1814. "800x600",
  1815. "1024x768",
  1816. "1280x960",
  1817. "1600x1200",
  1818. "1920x1440" ])
  1819. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1820. self.btnOK.SetDefault()
  1821. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1822. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1823. self._layout()
  1824. self.SetSize(self.GetBestSize())
  1825. def _layout(self):
  1826. """!Do layout"""
  1827. sizer = wx.BoxSizer(wx.VERTICAL)
  1828. # body
  1829. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1830. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1831. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1832. label = _("Width:")),
  1833. flag = wx.ALIGN_CENTER_VERTICAL)
  1834. fbox.Add(item = self.width)
  1835. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1836. label = _("Height:")),
  1837. flag = wx.ALIGN_CENTER_VERTICAL)
  1838. fbox.Add(item = self.height)
  1839. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1840. label = _("Template:")),
  1841. flag = wx.ALIGN_CENTER_VERTICAL)
  1842. fbox.Add(item = self.template)
  1843. box.Add(item = fbox, proportion = 1,
  1844. flag = wx.EXPAND | wx.ALL, border = 5)
  1845. sizer.Add(item = box, proportion = 1,
  1846. flag=wx.EXPAND | wx.ALL, border = 3)
  1847. # buttons
  1848. btnsizer = wx.StdDialogButtonSizer()
  1849. btnsizer.AddButton(self.btnOK)
  1850. btnsizer.AddButton(self.btnCancel)
  1851. btnsizer.Realize()
  1852. sizer.Add(item = btnsizer, proportion = 0,
  1853. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1854. self.panel.SetSizer(sizer)
  1855. sizer.Fit(self.panel)
  1856. self.Layout()
  1857. def GetValues(self):
  1858. """!Get width/height values"""
  1859. return self.width.GetValue(), self.height.GetValue()
  1860. def OnTemplate(self, event):
  1861. """!Template selected"""
  1862. sel = event.GetString()
  1863. if not sel:
  1864. width, height = self.parent.GetWindow().GetClientSize()
  1865. else:
  1866. width, height = map(int, sel.split('x'))
  1867. self.width.SetValue(width)
  1868. self.height.SetValue(height)
  1869. class SqlQueryFrame(wx.Frame):
  1870. def __init__(self, parent, id = wx.ID_ANY,
  1871. title = _("GRASS GIS SQL Query Utility"),
  1872. *kwargs):
  1873. """!SQL Query Utility window
  1874. """
  1875. self.parent = parent
  1876. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1877. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1878. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1879. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1880. label = _(" SQL statement "))
  1881. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1882. style = wx.TE_MULTILINE)
  1883. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1884. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1885. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1886. self._layout()
  1887. self.SetMinSize(wx.Size(300, 150))
  1888. self.SetSize(wx.Size(500, 200))
  1889. def _layout(self):
  1890. """!Do layout"""
  1891. sizer = wx.BoxSizer(wx.VERTICAL)
  1892. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1893. sqlSizer.Add(item = self.sql, proportion = 1,
  1894. flag = wx.EXPAND)
  1895. btnSizer = wx.StdDialogButtonSizer()
  1896. btnSizer.AddButton(self.btnApply)
  1897. btnSizer.AddButton(self.btnCancel)
  1898. btnSizer.Realize()
  1899. sizer.Add(item = sqlSizer, proportion = 1,
  1900. flag = wx.EXPAND | wx.ALL, border = 5)
  1901. sizer.Add(item = btnSizer, proportion = 0,
  1902. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1903. self.panel.SetSizer(sizer)
  1904. self.Layout()
  1905. def OnCloseWindow(self, event):
  1906. """!Close window
  1907. """
  1908. self.Close()
  1909. class SymbolDialog(wx.Dialog):
  1910. """!Dialog for GRASS symbols selection.
  1911. Dialog is called in gui_core::forms module.
  1912. """
  1913. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1914. """!Dialog constructor.
  1915. It is assumed that symbolPath contains folders with symbols.
  1916. @param parent dialog parent
  1917. @param symbolPath absolute path to symbols
  1918. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1919. @param title dialog title
  1920. """
  1921. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  1922. self.symbolPath = symbolPath
  1923. self.currentSymbol = currentSymbol # default basic/x
  1924. self.selected = None
  1925. self.selectedDir = None
  1926. self._layout()
  1927. def _layout(self):
  1928. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  1929. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1930. vSizer = wx.BoxSizer( wx.VERTICAL)
  1931. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  1932. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  1933. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1934. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  1935. proportion = 0,
  1936. flag = wx.ALIGN_CENTER_VERTICAL)
  1937. fgSizer.Add(item = self.folderChoice, proportion = 0,
  1938. flag = wx.ALIGN_CENTER, border = 0)
  1939. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  1940. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  1941. flag = wx.ALIGN_CENTRE_VERTICAL)
  1942. fgSizer.Add(self.infoLabel, proportion = 0,
  1943. flag = wx.ALIGN_CENTRE_VERTICAL)
  1944. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  1945. self.panels = self._createSymbolPanels(mainPanel)
  1946. for panel in self.panels:
  1947. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  1948. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  1949. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  1950. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  1951. self.btnOK.SetDefault()
  1952. self.btnOK.Enable(False)
  1953. # buttons
  1954. btnSizer = wx.StdDialogButtonSizer()
  1955. btnSizer.AddButton(self.btnCancel)
  1956. btnSizer.AddButton(self.btnOK)
  1957. btnSizer.Realize()
  1958. mainSizer.Add(item = btnSizer, proportion = 0,
  1959. flag = wx.EXPAND | wx.ALL, border = 5)
  1960. # show panel with the largest number of images and fit size
  1961. count = []
  1962. for folder in os.listdir(self.symbolPath):
  1963. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  1964. index = count.index(max(count))
  1965. self.folderChoice.SetSelection(index)
  1966. self.OnFolderSelect(None)
  1967. self.infoLabel.Show()
  1968. mainPanel.SetSizerAndFit(mainSizer)
  1969. self.SetSize(self.GetBestSize())
  1970. # show currently selected symbol
  1971. if self.currentSymbol:
  1972. # set directory
  1973. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  1974. self.folderChoice.SetStringSelection(self.selectedDir)
  1975. # select symbol
  1976. panelIdx = self.folderChoice.GetSelection()
  1977. for panel in self.symbolPanels[panelIdx]:
  1978. if panel.GetName() == self.selected:
  1979. panel.Select()
  1980. else:
  1981. self.folderChoice.SetSelection(0)
  1982. self.OnFolderSelect(None)
  1983. def _createSymbolPanels(self, parent):
  1984. """!Creates multiple panels with symbols.
  1985. Panels are shown/hidden according to selected folder."""
  1986. folders = os.listdir(self.symbolPath)
  1987. panels = []
  1988. self.symbolPanels = []
  1989. for folder in folders:
  1990. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  1991. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  1992. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  1993. symbolPanels = []
  1994. for img in images:
  1995. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  1996. iP.symbolSelectionChanged.connect(self.SelectionChanged)
  1997. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  1998. symbolPanels.append(iP)
  1999. panel.SetSizerAndFit(sizer)
  2000. panel.Hide()
  2001. panels.append(panel)
  2002. self.symbolPanels.append(symbolPanels)
  2003. return panels
  2004. def _getSymbols(self, path):
  2005. # we assume that images are in subfolders (1 level only)
  2006. imageList = []
  2007. for image in os.listdir(path):
  2008. imageList.append(os.path.join(path, image))
  2009. return sorted(imageList)
  2010. def OnFolderSelect(self, event):
  2011. """!Selected folder with symbols changed."""
  2012. idx = self.folderChoice.GetSelection()
  2013. for i in range(len(self.panels)):
  2014. sizer = self.panels[i].GetContainingSizer()
  2015. sizer.Show(self.panels[i], i == idx, recursive = True)
  2016. sizer.Layout()
  2017. if self.selectedDir == self.folderChoice.GetStringSelection():
  2018. self.btnOK.Enable()
  2019. self.infoLabel.SetLabel(self.selected)
  2020. else:
  2021. self.btnOK.Disable()
  2022. self.infoLabel.SetLabel('')
  2023. def SelectionChanged(self, name, doubleClick):
  2024. """!Selected symbol changed."""
  2025. if doubleClick:
  2026. self.EndModal(wx.ID_OK)
  2027. # deselect all
  2028. for i in range(len(self.panels)):
  2029. for panel in self.symbolPanels[i]:
  2030. if panel.GetName() != name:
  2031. panel.Deselect()
  2032. self.btnOK.Enable()
  2033. self.selected = name
  2034. self.selectedDir = self.folderChoice.GetStringSelection()
  2035. self.infoLabel.SetLabel(name)
  2036. def GetSelectedSymbolName(self):
  2037. """!Returns currently selected symbol name (e.g. 'basic/x').
  2038. """
  2039. # separator must be '/' and not dependent on OS
  2040. return self.selectedDir + '/' + self.selected
  2041. def GetSelectedSymbolPath(self):
  2042. """!Returns currently selected symbol full path.
  2043. """
  2044. return os.path.join(self.symbolPath, self.selectedDir, self.selected)
  2045. class TextEntryDialog(wx.Dialog):
  2046. """!Simple dialog with text field.
  2047. It differs from wx.TextEntryDialog because it allows adding validator.
  2048. """
  2049. def __init__(self, parent, message, caption='',
  2050. defaultValue='', pos=wx.DefaultPosition, validator=wx.DefaultValidator,
  2051. style=wx.OK | wx.CANCEL):
  2052. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=caption, pos=pos)
  2053. vbox = wx.BoxSizer(wx.VERTICAL)
  2054. stline = wx.StaticText(self, id=wx.ID_ANY, label=message)
  2055. vbox.Add(item=stline, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  2056. self._textCtrl = wx.TextCtrl(self, id=wx.ID_ANY, size = (300, -1),
  2057. value=defaultValue, validator=validator)
  2058. vbox.Add(item=self._textCtrl, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
  2059. self._textCtrl.SetFocus()
  2060. sizer = self.CreateSeparatedButtonSizer(style)
  2061. vbox.Add(item=sizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2062. self.SetSizerAndFit(vbox)
  2063. def GetValue(self):
  2064. return self._textCtrl.GetValue()
  2065. def SetValue(self, value):
  2066. self._textCtrl.SetValue(value)
  2067. class HyperlinkDialog(wx.Dialog):
  2068. """!Dialog for displaying message with hyperlink."""
  2069. def __init__(self, parent, title, message, hyperlink,
  2070. hyperlinkLabel=None, style=wx.OK):
  2071. """!Constructor
  2072. @param parent gui parent
  2073. @param title dialog title
  2074. @param message message
  2075. @param hyperlink url
  2076. @param hyperlinkLabel label shown instead of url
  2077. @param style button style
  2078. """
  2079. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
  2080. style=wx.DEFAULT_DIALOG_STYLE)
  2081. sizer = wx.BoxSizer(wx.VERTICAL)
  2082. label = wx.StaticText(self, label=message)
  2083. sizer.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=10)
  2084. hyperlinkLabel = hyperlinkLabel if hyperlinkLabel else hyperlink
  2085. hyperlinkCtrl = wx.HyperlinkCtrl(self, id=wx.ID_ANY,
  2086. label=hyperlinkLabel, url=hyperlink,
  2087. style=wx.HL_ALIGN_LEFT|wx.HL_CONTEXTMENU)
  2088. sizer.Add(item=hyperlinkCtrl, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
  2089. btnsizer = self.CreateSeparatedButtonSizer(style)
  2090. sizer.Add(item=btnsizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
  2091. self.SetSizer(sizer)
  2092. sizer.Fit(self)