dialogs.py 98 KB

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