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. gridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
  807. gridSizer.AddGrowableCol(0)
  808. self.layerBox = wx.ListBox(parent = self, id = wx.ID_ANY, size = (-1, 150),
  809. style = wx.LB_MULTIPLE | wx.LB_NEEDED_SB)
  810. gridSizer.Add(item = self.layerBox, pos = (0, 0), span = (2, 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. gridSizer.Add(item = self.addLayer, pos = (0, 1), flag = wx.EXPAND)
  814. self.removeLayer = wx.Button(self, id = wx.ID_REMOVE)
  815. self.removeLayer.SetToolTipString(_("Remove selected layer(s) from list."))
  816. gridSizer.Add(item = self.removeLayer, pos = (1, 1))
  817. bodySizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND)
  818. self.infoLabel = wx.StaticText(parent = self, id = wx.ID_ANY)
  819. bodySizer.Add(item = self.infoLabel,
  820. flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, border = 5)
  821. self.subGroup = wx.CheckBox(parent = self, id = wx.ID_ANY,
  822. label = _("Define also sub-group (same name as group)"))
  823. self.subGroup.SetValue(True) # most of imagery modules requires also subgroup
  824. bodySizer.Add(item = self.subGroup, flag = wx.BOTTOM | wx.EXPAND, border = 5)
  825. # bindings
  826. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnGroupSelected)
  827. self.addLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  828. self.removeLayer.Bind(wx.EVT_BUTTON, self.OnRemoveLayer)
  829. if self.defaultGroup:
  830. self.groupSelect.SetValue(self.defaultGroup)
  831. return bodySizer
  832. def OnAddLayer(self, event):
  833. """!Add new layer to listbox"""
  834. dlg = MapLayersDialogForGroups(parent = self, title = _("Add selected map layers into group"))
  835. if dlg.ShowModal() != wx.ID_OK:
  836. dlg.Destroy()
  837. return
  838. layers = dlg.GetMapLayers()
  839. for layer in layers:
  840. if layer not in self.GetLayers():
  841. self.layerBox.Append(layer)
  842. self.groupChanged = True
  843. def OnRemoveLayer(self, event):
  844. """!Remove layer from listbox"""
  845. while self.layerBox.GetSelections():
  846. sel = self.layerBox.GetSelections()[0]
  847. self.layerBox.Delete(sel)
  848. self.groupChanged = True
  849. def GetLayers(self):
  850. """!Get layers"""
  851. return self.layerBox.GetItems()
  852. def OnGroupSelected(self, event):
  853. """!Text changed in group selector"""
  854. # callAfter must be called to close popup before other actions
  855. wx.CallAfter(self.GroupSelected)
  856. def GroupSelected(self):
  857. """!Group was selected, check if changes were apllied"""
  858. group = self.GetSelectedGroup()
  859. if self.groupChanged:
  860. dlg = wx.MessageDialog(self, message = _("Group <%s> was changed, "
  861. "do you want to apply changes?") % self.currentGroup,
  862. caption = _("Unapplied changes"),
  863. style = wx.YES_NO | wx.ICON_QUESTION | wx.YES_DEFAULT)
  864. if dlg.ShowModal() == wx.ID_YES:
  865. self.ApplyChanges()
  866. dlg.Destroy()
  867. maps = list()
  868. groups = self.GetExistGroups()
  869. if group in groups:
  870. maps = self.GetGroupLayers(group)
  871. self.ShowGroupLayers(maps)
  872. self.currentGroup = group
  873. self.groupChanged = False
  874. self.ClearNotification()
  875. def ShowGroupLayers(self, mapList):
  876. """!Show map layers in currently selected group"""
  877. self.layerBox.Set(mapList)
  878. def EditGroup(self, group):
  879. """!Edit selected group"""
  880. layersNew = self.GetLayers()
  881. layersOld = self.GetGroupLayers(group)
  882. add = []
  883. remove = []
  884. for layerNew in layersNew:
  885. if layerNew not in layersOld:
  886. add.append(layerNew)
  887. for layerOld in layersOld:
  888. if layerOld not in layersNew:
  889. remove.append(layerOld)
  890. kwargs = {}
  891. if self.subGroup.IsChecked():
  892. kwargs['subgroup'] = group
  893. ret = None
  894. if remove:
  895. ret = RunCommand('i.group',
  896. parent = self,
  897. group = group,
  898. flags = 'r',
  899. input = ','.join(remove),
  900. **kwargs)
  901. if add:
  902. ret = RunCommand('i.group',
  903. parent = self,
  904. group = group,
  905. input = ','.join(add),
  906. **kwargs)
  907. return ret
  908. def CreateNewGroup(self, group):
  909. """!Create new group"""
  910. layers = self.GetLayers()
  911. kwargs = {}
  912. if self.subGroup.IsChecked():
  913. kwargs['subgroup'] = group
  914. return RunCommand('i.group',
  915. parent = self,
  916. group = group,
  917. input = layers,
  918. **kwargs)
  919. def GetExistGroups(self):
  920. """!Returns existing groups in current mapset"""
  921. return grass.list_grouped('group')[grass.gisenv()['MAPSET']]
  922. def ShowResult(self, group, returnCode, create):
  923. """!Show if operation was successfull."""
  924. group += '@' + grass.gisenv()['MAPSET']
  925. if returnCode is None:
  926. label = _("No changes to apply in group <%s>.") % group
  927. elif returnCode == 0:
  928. if create:
  929. label = _("Group <%s> was successfully created.") % group
  930. else:
  931. label = _("Group <%s> was successfully changed.") % group
  932. else:
  933. if create:
  934. label = _("Creating of new group <%s> failed.") % group
  935. else:
  936. label = _("Changing of group <%s> failed.") % group
  937. self.infoLabel.SetLabel(label)
  938. wx.FutureCall(4000, self.ClearNotification)
  939. def GetSelectedGroup(self):
  940. """!Return currently selected group (without mapset)"""
  941. return self.groupSelect.GetValue().split('@')[0]
  942. def GetGroupLayers(self, group):
  943. """!Get layers in group"""
  944. res = RunCommand('i.group',
  945. parent = self,
  946. flags = 'g',
  947. group = group,
  948. read = True).strip()
  949. if res.split('\n')[0]:
  950. return res.split('\n')
  951. return []
  952. def ClearNotification(self):
  953. """!Clear notification string"""
  954. self.infoLabel.SetLabel("")
  955. def ApplyChanges(self):
  956. """!Create or edit group"""
  957. group = self.currentGroup
  958. if not group:
  959. GMessage(parent = self,
  960. message = _("No group selected."))
  961. return False
  962. groups = self.GetExistGroups()
  963. if group in groups:
  964. ret = self.EditGroup(group)
  965. self.ShowResult(group = group, returnCode = ret, create = False)
  966. else:
  967. ret = self.CreateNewGroup(group)
  968. self.ShowResult(group = group, returnCode = ret, create = True)
  969. self.groupChanged = False
  970. return True
  971. def OnApply(self, event):
  972. """!Apply changes"""
  973. self.ApplyChanges()
  974. def OnOk(self, event):
  975. """!Apply changes and close dialog"""
  976. if self.ApplyChanges():
  977. self.OnClose(event)
  978. def OnClose(self, event):
  979. """!Close dialog"""
  980. if not self.IsModal():
  981. self.Destroy()
  982. event.Skip()
  983. class MapLayersDialogBase(wx.Dialog):
  984. """!Base dialog for selecting map layers (raster, vector).
  985. There are 3 subclasses: MapLayersDialogForGroups, MapLayersDialogForModeler,
  986. MapLayersDialog. Base class contains core functionality.
  987. """
  988. def __init__(self, parent, title,
  989. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  990. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  991. style = style, **kwargs)
  992. self.parent = parent # GMFrame or ?
  993. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  994. # dialog body
  995. self.bodySizer = self._createDialogBody()
  996. self.mainSizer.Add(item = self.bodySizer, proportion = 1,
  997. flag = wx.EXPAND | wx.ALL, border = 5)
  998. # update list of layer to be loaded
  999. self.map_layers = [] # list of map layers (full list type/mapset)
  1000. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1001. self.mapset.GetStringSelection())
  1002. self._fullyQualifiedNames()
  1003. self._modelerDSeries()
  1004. # buttons
  1005. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  1006. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  1007. btnOk.SetDefault()
  1008. # sizers & do layout
  1009. self.btnSizer = wx.StdDialogButtonSizer()
  1010. self.btnSizer.AddButton(btnCancel)
  1011. self.btnSizer.AddButton(btnOk)
  1012. self._addApplyButton()
  1013. self.btnSizer.Realize()
  1014. self.mainSizer.Add(item = self.btnSizer, proportion = 0,
  1015. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  1016. self.SetSizer(self.mainSizer)
  1017. self.mainSizer.Fit(self)
  1018. # set dialog min size
  1019. self.SetMinSize(self.GetSize())
  1020. def _modelerDSeries(self):
  1021. """!Method used only by MapLayersDialogForModeler,
  1022. for other subclasses does nothing.
  1023. """
  1024. pass
  1025. def _addApplyButton(self):
  1026. """!Method used only by MapLayersDialog,
  1027. for other subclasses does nothing.
  1028. """
  1029. pass
  1030. def _fullyQualifiedNames(self):
  1031. """!Adds CheckBox which determines is fully qualified names are retuned.
  1032. """
  1033. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1034. label = _("Use fully-qualified map names"))
  1035. self.fullyQualified.SetValue(True)
  1036. self.mainSizer.Add(item = self.fullyQualified, proportion = 0,
  1037. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1038. def _useFullyQualifiedNames(self):
  1039. return self.fullyQualified.IsChecked()
  1040. def _layerTypes(self):
  1041. """!Determines which layer types can be chosen.
  1042. Valid values:
  1043. - raster
  1044. - raster3d
  1045. - vector
  1046. """
  1047. return [_('raster'), _('3D raster'), _('vector')]
  1048. def _selectAll(self):
  1049. """!Check all layers by default"""
  1050. return True
  1051. def _createDialogBody(self):
  1052. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  1053. bodySizer.AddGrowableCol(1)
  1054. bodySizer.AddGrowableRow(3)
  1055. # layer type
  1056. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map type:")),
  1057. flag = wx.ALIGN_CENTER_VERTICAL,
  1058. pos = (0,0))
  1059. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  1060. choices = self._layerTypes(), size = (100,-1))
  1061. self.layerType.SetSelection(0)
  1062. bodySizer.Add(item = self.layerType,
  1063. pos = (0,1))
  1064. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  1065. # select toggle
  1066. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1067. label = _("Select toggle"))
  1068. self.toggle.SetValue(self._selectAll())
  1069. bodySizer.Add(item = self.toggle,
  1070. flag = wx.ALIGN_CENTER_VERTICAL,
  1071. pos = (0,2))
  1072. # mapset filter
  1073. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  1074. flag = wx.ALIGN_CENTER_VERTICAL,
  1075. pos = (1,0))
  1076. self.mapset = MapsetSelect(parent = self, searchPath = True)
  1077. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  1078. bodySizer.Add(item = self.mapset,
  1079. pos = (1,1), span = (1, 2))
  1080. # map name filter
  1081. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Pattern:")),
  1082. flag = wx.ALIGN_CENTER_VERTICAL,
  1083. pos = (2,0))
  1084. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  1085. value = "",
  1086. size = (250,-1))
  1087. bodySizer.Add(item = self.filter,
  1088. flag = wx.EXPAND,
  1089. pos = (2,1), span = (1, 2))
  1090. self.filter.SetFocus()
  1091. self.filter.SetToolTipString(_("Put here a regular expression."
  1092. " Characters '.*' stand for anything,"
  1093. " character '^' stands for the beginning"
  1094. " and '$' for the end."))
  1095. # layer list
  1096. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  1097. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  1098. pos = (3,0))
  1099. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1100. size = (250, 100),
  1101. choices = [])
  1102. bodySizer.Add(item = self.layers,
  1103. flag = wx.EXPAND,
  1104. pos = (3,1), span = (1, 2))
  1105. # bindings
  1106. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  1107. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  1108. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  1109. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  1110. return bodySizer
  1111. def LoadMapLayers(self, type, mapset):
  1112. """!Load list of map layers
  1113. @param type layer type ('raster' or 'vector')
  1114. @param mapset mapset name
  1115. """
  1116. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  1117. self.layers.Set(self.map_layers)
  1118. # check all items by default
  1119. for item in range(self.layers.GetCount()):
  1120. self.layers.Check(item, check = self._selectAll())
  1121. def OnChangeParams(self, event):
  1122. """!Filter parameters changed by user"""
  1123. # update list of layer to be loaded
  1124. self.LoadMapLayers(self.GetLayerType(cmd = True),
  1125. self.mapset.GetStringSelection())
  1126. event.Skip()
  1127. def OnMenu(self, event):
  1128. """!Table description area, context menu"""
  1129. if not hasattr(self, "popupID1"):
  1130. self.popupDataID1 = wx.NewId()
  1131. self.popupDataID2 = wx.NewId()
  1132. self.popupDataID3 = wx.NewId()
  1133. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1134. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  1135. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  1136. # generate popup-menu
  1137. menu = wx.Menu()
  1138. menu.Append(self.popupDataID1, _("Select all"))
  1139. menu.Append(self.popupDataID2, _("Invert selection"))
  1140. menu.Append(self.popupDataID3, _("Deselect all"))
  1141. self.PopupMenu(menu)
  1142. menu.Destroy()
  1143. def OnSelectAll(self, event):
  1144. """!Select all map layer from list"""
  1145. for item in range(self.layers.GetCount()):
  1146. self.layers.Check(item, True)
  1147. def OnSelectInvert(self, event):
  1148. """!Invert current selection"""
  1149. for item in range(self.layers.GetCount()):
  1150. if self.layers.IsChecked(item):
  1151. self.layers.Check(item, False)
  1152. else:
  1153. self.layers.Check(item, True)
  1154. def OnDeselectAll(self, event):
  1155. """!Select all map layer from list"""
  1156. for item in range(self.layers.GetCount()):
  1157. self.layers.Check(item, False)
  1158. def OnFilter(self, event):
  1159. """!Apply filter for map names"""
  1160. if len(event.GetString()) == 0:
  1161. self.layers.Set(self.map_layers)
  1162. return
  1163. list = []
  1164. for layer in self.map_layers:
  1165. try:
  1166. if re.compile(event.GetString()).search(layer):
  1167. list.append(layer)
  1168. except:
  1169. pass
  1170. self.layers.Set(list)
  1171. self.OnSelectAll(None)
  1172. event.Skip()
  1173. def OnToggle(self, event):
  1174. """!Select toggle (check or uncheck all layers)"""
  1175. check = event.Checked()
  1176. for item in range(self.layers.GetCount()):
  1177. self.layers.Check(item, check)
  1178. event.Skip()
  1179. def GetMapLayers(self):
  1180. """!Return list of checked map layers"""
  1181. layerNames = []
  1182. for indx in self.layers.GetSelections():
  1183. # layers.append(self.layers.GetStringSelec(indx))
  1184. pass
  1185. mapset = self.mapset.GetStringSelection()
  1186. for item in range(self.layers.GetCount()):
  1187. if not self.layers.IsChecked(item):
  1188. continue
  1189. if self._useFullyQualifiedNames():
  1190. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  1191. else:
  1192. layerNames.append(self.layers.GetString(item))
  1193. return layerNames
  1194. def GetLayerType(self, cmd = False):
  1195. """!Get selected layer type
  1196. @param cmd True for g.mlist
  1197. """
  1198. if not cmd:
  1199. return self.layerType.GetStringSelection()
  1200. sel = self.layerType.GetSelection()
  1201. if sel == 0:
  1202. ltype = 'rast'
  1203. elif sel == 1:
  1204. ltype = 'rast3d'
  1205. else:
  1206. ltype = 'vect'
  1207. return ltype
  1208. class MapLayersDialog(MapLayersDialogBase):
  1209. """!Subclass of MapLayersDialogBase used in Layer Manager.
  1210. Contains apply button, which sends wxApplyMapLayers event.
  1211. """
  1212. def __init__(self, parent, title, **kwargs):
  1213. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1214. def _addApplyButton(self):
  1215. btnApply = wx.Button(parent = self, id = wx.ID_APPLY)
  1216. self.btnSizer.AddButton(btnApply)
  1217. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1218. def OnApply(self, event):
  1219. event = wxApplyMapLayers(mapLayers = self.GetMapLayers(), ltype = self.GetLayerType(cmd = True))
  1220. wx.PostEvent(self, event)
  1221. class MapLayersDialogForGroups(MapLayersDialogBase):
  1222. """!Subclass of MapLayersDialogBase used for specyfying maps in an imagery group.
  1223. Shows only raster maps.
  1224. """
  1225. def __init__(self, parent, title, **kwargs):
  1226. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1227. def _layerTypes(self):
  1228. return [_('raster'),]
  1229. def _selectAll(self):
  1230. """!Could be overriden"""
  1231. return False
  1232. def _fullyQualifiedNames(self):
  1233. pass
  1234. def _useFullyQualifiedNames(self):
  1235. return True
  1236. class MapLayersDialogForModeler(MapLayersDialogBase):
  1237. """!Subclass of MapLayersDialogBase used in Modeler.
  1238. """
  1239. def __init__(self, parent, title, **kwargs):
  1240. MapLayersDialogBase.__init__(self, parent = parent, title = title, **kwargs)
  1241. def _modelerDSeries(self):
  1242. self.dseries = wx.CheckBox(parent = self, id = wx.ID_ANY,
  1243. label = _("Dynamic series (%s)") % 'g.mlist')
  1244. self.dseries.SetValue(False)
  1245. self.mainSizer.Add(item = self.dseries, proportion = 0,
  1246. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  1247. def GetDSeries(self):
  1248. """!Used by modeler only
  1249. @return g.mlist command
  1250. """
  1251. if not self.dseries or not self.dseries.IsChecked():
  1252. return ''
  1253. cond = 'map in `g.mlist type=%s ' % self.GetLayerType(cmd = True)
  1254. patt = self.filter.GetValue()
  1255. if patt:
  1256. cond += 'pattern=%s ' % patt
  1257. cond += 'mapset=%s`' % self.mapset.GetStringSelection()
  1258. return cond
  1259. class ImportDialog(wx.Dialog):
  1260. """!Dialog for bulk import of various data (base class)"""
  1261. def __init__(self, parent, itype,
  1262. id = wx.ID_ANY, title = _("Multiple import"),
  1263. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  1264. self.parent = parent # GMFrame
  1265. self.importType = itype
  1266. self.options = dict() # list of options
  1267. self.commandId = -1 # id of running command
  1268. wx.Dialog.__init__(self, parent, id, title, style = style,
  1269. name = "MultiImportDialog")
  1270. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1271. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY)
  1272. if self.importType == 'gdal':
  1273. label = _("List of raster layers")
  1274. elif self.importType == 'ogr':
  1275. label = _("List of vector layers")
  1276. else:
  1277. label = _("List of %s layers") % self.importType.upper()
  1278. self.layerBox.SetLabel(" %s - %s " % (label, _("right click to (un)select all")))
  1279. # list of layers
  1280. columns = [_('Layer id'),
  1281. _('Layer name'),
  1282. _('Name for output GRASS map (editable)')]
  1283. if itype == 'ogr':
  1284. columns.insert(2, _('Feature type'))
  1285. self.list = LayersList(parent = self.panel, columns = columns)
  1286. self.list.LoadData()
  1287. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1288. label = "%s" % _("Options"))
  1289. cmd = self._getCommand()
  1290. task = gtask.parse_interface(cmd)
  1291. for f in task.get_options()['flags']:
  1292. name = f.get('name', '')
  1293. desc = f.get('label', '')
  1294. if not desc:
  1295. desc = f.get('description', '')
  1296. if not name and not desc:
  1297. continue
  1298. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  1299. continue
  1300. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  1301. continue
  1302. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  1303. continue
  1304. elif cmd == 'v.external' and name not in ('b'):
  1305. continue
  1306. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  1307. continue
  1308. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1309. label = desc)
  1310. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1311. label = _("Allow output files to overwrite existing files"))
  1312. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  1313. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  1314. self.closeOnFinish = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  1315. label = _("Close dialog on finish"))
  1316. self.closeOnFinish.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  1317. #
  1318. # buttons
  1319. #
  1320. # cancel
  1321. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  1322. self.btn_close.SetToolTipString(_("Close dialog"))
  1323. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  1324. # run
  1325. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  1326. self.btn_run.SetToolTipString(_("Import selected layers"))
  1327. self.btn_run.SetDefault()
  1328. self.btn_run.Enable(False)
  1329. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  1330. # run command dialog
  1331. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  1332. label = _("Command dialog"))
  1333. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  1334. def doLayout(self):
  1335. """!Do layout"""
  1336. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1337. # dsn input
  1338. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1339. flag = wx.EXPAND)
  1340. #
  1341. # list of DXF layers
  1342. #
  1343. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  1344. layerSizer.Add(item = self.list, proportion = 1,
  1345. flag = wx.ALL | wx.EXPAND, border = 5)
  1346. dialogSizer.Add(item = layerSizer, proportion = 1,
  1347. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1348. # options
  1349. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  1350. for key in self.options.keys():
  1351. optionSizer.Add(item = self.options[key], proportion = 0)
  1352. dialogSizer.Add(item = optionSizer, proportion = 0,
  1353. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  1354. dialogSizer.Add(item = self.overwrite, proportion = 0,
  1355. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1356. dialogSizer.Add(item = self.add, proportion = 0,
  1357. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1358. dialogSizer.Add(item = self.closeOnFinish, proportion = 0,
  1359. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1360. #
  1361. # buttons
  1362. #
  1363. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1364. btnsizer.Add(item = self.btn_cmd, proportion = 0,
  1365. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1366. border = 10)
  1367. btnsizer.Add(item = self.btn_close, proportion = 0,
  1368. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1369. border = 10)
  1370. btnsizer.Add(item = self.btn_run, proportion = 0,
  1371. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1372. border = 10)
  1373. dialogSizer.Add(item = btnsizer, proportion = 0,
  1374. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.ALIGN_RIGHT,
  1375. border = 10)
  1376. # dialogSizer.SetSizeHints(self.panel)
  1377. self.panel.SetAutoLayout(True)
  1378. self.panel.SetSizer(dialogSizer)
  1379. dialogSizer.Fit(self.panel)
  1380. # auto-layout seems not work here - FIXME
  1381. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1382. self.SetMinSize(size)
  1383. self.SetSize((size.width, size.height + 100))
  1384. # width = self.GetSize()[0]
  1385. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1386. self.Layout()
  1387. def _getCommand(self):
  1388. """!Get command"""
  1389. return ''
  1390. def OnClose(self, event = None):
  1391. """!Close dialog"""
  1392. self.Close()
  1393. def OnRun(self, event):
  1394. """!Import/Link data (each layes as separate vector map)"""
  1395. pass
  1396. def OnCmdDialog(self, event):
  1397. """!Show command dialog"""
  1398. pass
  1399. def AddLayers(self, returncode, cmd = None):
  1400. """!Add imported/linked layers into layer tree"""
  1401. if not self.add.IsChecked() or returncode != 0:
  1402. return
  1403. self.commandId += 1
  1404. maptree = self.parent.GetLayerTree()
  1405. layer, output = self.list.GetLayers()[self.commandId]
  1406. if '@' not in output:
  1407. name = output + '@' + grass.gisenv()['MAPSET']
  1408. else:
  1409. name = output
  1410. # add imported layers into layer tree
  1411. if self.importType == 'gdal':
  1412. cmd = ['d.rast',
  1413. 'map=%s' % name]
  1414. if UserSettings.Get(group = 'rasterLayer', key = 'opaque', subkey = 'enabled'):
  1415. cmd.append('-n')
  1416. item = maptree.AddLayer(ltype = 'raster',
  1417. lname = name, lchecked = False,
  1418. lcmd = cmd, multiple = False)
  1419. else:
  1420. item = maptree.AddLayer(ltype = 'vector',
  1421. lname = name, lchecked = False,
  1422. lcmd = ['d.vect',
  1423. 'map=%s' % name] + GetDisplayVectSettings(),
  1424. multiple = False)
  1425. maptree.mapdisplay.MapWindow.ZoomToMap()
  1426. def OnAbort(self, event):
  1427. """!Abort running import
  1428. @todo not yet implemented
  1429. """
  1430. pass
  1431. class GdalImportDialog(ImportDialog):
  1432. def __init__(self, parent, giface, ogr = False, link = False):
  1433. """!Dialog for bulk import of various raster/vector data
  1434. @todo Split into GdalImportDialog and OgrImportDialog
  1435. @param parent parent window
  1436. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1437. @param link True for linking data otherwise importing data
  1438. """
  1439. self._giface = giface
  1440. self.link = link
  1441. self.ogr = ogr
  1442. if ogr:
  1443. ImportDialog.__init__(self, parent, itype = 'ogr')
  1444. if link:
  1445. self.SetTitle(_("Link external vector data"))
  1446. else:
  1447. self.SetTitle(_("Import vector data"))
  1448. else:
  1449. ImportDialog.__init__(self, parent, itype = 'gdal')
  1450. if link:
  1451. self.SetTitle(_("Link external raster data"))
  1452. else:
  1453. self.SetTitle(_("Import raster data"))
  1454. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1455. ogr = ogr, link = link)
  1456. if link:
  1457. self.add.SetLabel(_("Add linked layers into layer tree"))
  1458. else:
  1459. self.add.SetLabel(_("Add imported layers into layer tree"))
  1460. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1461. if link:
  1462. self.btn_run.SetLabel(_("&Link"))
  1463. self.btn_run.SetToolTipString(_("Link selected layers"))
  1464. if ogr:
  1465. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.external')
  1466. else:
  1467. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.external')
  1468. else:
  1469. self.btn_run.SetLabel(_("&Import"))
  1470. self.btn_run.SetToolTipString(_("Import selected layers"))
  1471. if ogr:
  1472. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.in.ogr')
  1473. else:
  1474. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.in.gdal')
  1475. self.doLayout()
  1476. def OnRun(self, event):
  1477. """!Import/Link data (each layes as separate vector map)"""
  1478. self.commandId = -1
  1479. data = self.list.GetLayers()
  1480. if not data:
  1481. GMessage(_("No layers selected. Operation canceled."),
  1482. parent = self)
  1483. return
  1484. dsn = self.dsnInput.GetDsn()
  1485. ext = self.dsnInput.GetFormatExt()
  1486. # determine data driver for PostGIS links
  1487. popOGR = False
  1488. if self.importType == 'ogr' and \
  1489. self.dsnInput.GetType() == 'db' and \
  1490. self.dsnInput.GetFormat() == 'PostgreSQL' and \
  1491. 'GRASS_VECTOR_OGR' not in os.environ:
  1492. popOGR = True
  1493. os.environ['GRASS_VECTOR_OGR'] = '1'
  1494. for layer, output in data:
  1495. if self.importType == 'ogr':
  1496. if ext and layer.rfind(ext) > -1:
  1497. layer = layer.replace('.' + ext, '')
  1498. if self.link:
  1499. cmd = ['v.external',
  1500. 'dsn=%s' % dsn,
  1501. 'output=%s' % output,
  1502. 'layer=%s' % layer]
  1503. else:
  1504. cmd = ['v.in.ogr',
  1505. 'dsn=%s' % dsn,
  1506. 'layer=%s' % layer,
  1507. 'output=%s' % output]
  1508. else: # gdal
  1509. if self.dsnInput.GetType() == 'dir':
  1510. idsn = os.path.join(dsn, layer)
  1511. else:
  1512. idsn = dsn
  1513. if self.link:
  1514. cmd = ['r.external',
  1515. 'input=%s' % idsn,
  1516. 'output=%s' % output]
  1517. else:
  1518. cmd = ['r.in.gdal',
  1519. 'input=%s' % idsn,
  1520. 'output=%s' % output]
  1521. if self.overwrite.IsChecked():
  1522. cmd.append('--overwrite')
  1523. for key in self.options.keys():
  1524. if self.options[key].IsChecked():
  1525. cmd.append('-%s' % key)
  1526. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  1527. '--overwrite' not in cmd:
  1528. cmd.append('--overwrite')
  1529. # run in Layer Manager
  1530. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1531. if popOGR:
  1532. os.environ.pop('GRASS_VECTOR_OGR')
  1533. if self.closeOnFinish.IsChecked():
  1534. self.Close()
  1535. def _getCommand(self):
  1536. """!Get command"""
  1537. if self.link:
  1538. if self.ogr:
  1539. return 'v.external'
  1540. else:
  1541. return 'r.external'
  1542. else:
  1543. if self.ogr:
  1544. return 'v.in.ogr'
  1545. else:
  1546. return 'r.in.gdal'
  1547. return ''
  1548. def OnCmdDialog(self, event):
  1549. """!Show command dialog"""
  1550. name = self._getCommand()
  1551. GUI(parent = self, modal = False).ParseCommand(cmd = [name])
  1552. class GdalOutputDialog(wx.Dialog):
  1553. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1554. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1555. """!Dialog for setting output format for rasters/vectors
  1556. @todo Split into GdalOutputDialog and OgrOutputDialog
  1557. @param parent parent window
  1558. @param id window id
  1559. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1560. @param style window style
  1561. @param *kwargs other wx.Dialog's arguments
  1562. """
  1563. self.parent = parent # GMFrame
  1564. self.ogr = ogr
  1565. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1566. if self.ogr:
  1567. self.SetTitle(_("Define output format for vector data"))
  1568. else:
  1569. self.SetTitle(_("Define output format for raster data"))
  1570. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1571. # buttons
  1572. self.btnCmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  1573. label = _("Command dialog"))
  1574. self.btnCmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  1575. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1576. self.btnCancel.SetToolTipString(_("Close dialog"))
  1577. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1578. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1579. self.btnOk.SetDefault()
  1580. self.btnOk.Enable(False)
  1581. self.dsnInput = GdalSelect(parent = self, panel = self.panel,
  1582. ogr = ogr,
  1583. exclude = ['file', 'protocol'], dest = True)
  1584. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1585. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1586. self._layout()
  1587. def _layout(self):
  1588. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1589. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1590. flag = wx.EXPAND)
  1591. btnSizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1592. btnSizer.Add(item = self.btnCmd, proportion = 0,
  1593. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1594. border = 10)
  1595. btnSizer.Add(item = self.btnCancel, proportion = 0,
  1596. flag = wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
  1597. border = 10)
  1598. btnSizer.Add(item = self.btnOk, proportion = 0,
  1599. flag = wx.RIGHT | wx.ALIGN_CENTER,
  1600. border = 10)
  1601. dialogSizer.Add(item = btnSizer, proportion = 0,
  1602. flag = wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT,
  1603. border = 10)
  1604. self.panel.SetAutoLayout(True)
  1605. self.panel.SetSizer(dialogSizer)
  1606. dialogSizer.Fit(self.panel)
  1607. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1608. self.SetMinSize(size)
  1609. self.SetSize((size.width, size.height))
  1610. self.Layout()
  1611. def OnCmdDialog(self, event):
  1612. GUI(parent = self, modal = True).ParseCommand(cmd = ['v.external.out'])
  1613. def OnCancel(self, event):
  1614. self.Destroy()
  1615. def OnOK(self, event):
  1616. if self.dsnInput.GetType() == 'native':
  1617. RunCommand('v.external.out',
  1618. parent = self,
  1619. flags = 'r')
  1620. else:
  1621. dsn = self.dsnInput.GetDsn()
  1622. frmt = self.dsnInput.GetFormat()
  1623. options = self.dsnInput.GetOptions()
  1624. RunCommand('v.external.out',
  1625. parent = self,
  1626. dsn = dsn, format = frmt,
  1627. options = options)
  1628. self.Close()
  1629. class DxfImportDialog(ImportDialog):
  1630. """!Dialog for bulk import of DXF layers"""
  1631. def __init__(self, parent, giface):
  1632. ImportDialog.__init__(self, parent, itype = 'dxf',
  1633. title = _("Import DXF layers"))
  1634. self._giface = giface
  1635. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1636. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1637. dialogTitle = _('Choose DXF file to import'),
  1638. buttonText = _('Browse'),
  1639. startDirectory = os.getcwd(), fileMode = 0,
  1640. changeCallback = self.OnSetDsn,
  1641. fileMask = "DXF File (*.dxf)|*.dxf")
  1642. self.add.SetLabel(_("Add imported layers into layer tree"))
  1643. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1644. self.doLayout()
  1645. def _getCommand(self):
  1646. """!Get command"""
  1647. return 'v.in.dxf'
  1648. def OnRun(self, event):
  1649. """!Import/Link data (each layes as separate vector map)"""
  1650. data = self.list.GetLayers()
  1651. # hide dialog
  1652. self.Hide()
  1653. inputDxf = self.dsnInput.GetValue()
  1654. for layer, output in data:
  1655. cmd = ['v.in.dxf',
  1656. 'input=%s' % inputDxf,
  1657. 'layers=%s' % layer,
  1658. 'output=%s' % output]
  1659. for key in self.options.keys():
  1660. if self.options[key].IsChecked():
  1661. cmd.append('-%s' % key)
  1662. if self.overwrite.IsChecked() or \
  1663. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1664. cmd.append('--overwrite')
  1665. # run in Layer Manager
  1666. self._giface.RunCmd(cmd, switchPage = True, onDone = self.AddLayers)
  1667. self.OnCancel()
  1668. def OnSetDsn(self, event):
  1669. """!Input DXF file defined, update list of layer widget"""
  1670. path = event.GetString()
  1671. if not path:
  1672. return
  1673. data = list()
  1674. ret = RunCommand('v.in.dxf',
  1675. quiet = True,
  1676. parent = self,
  1677. read = True,
  1678. flags = 'l',
  1679. input = path)
  1680. if not ret:
  1681. self.list.LoadData()
  1682. self.btn_run.Enable(False)
  1683. return
  1684. for line in ret.splitlines():
  1685. layerId = line.split(':')[0].split(' ')[1]
  1686. layerName = line.split(':')[1].strip()
  1687. grassName = GetValidLayerName(layerName)
  1688. data.append((layerId, layerName.strip(), grassName.strip()))
  1689. self.list.LoadData(data)
  1690. if len(data) > 0:
  1691. self.btn_run.Enable(True)
  1692. else:
  1693. self.btn_run.Enable(False)
  1694. def OnCmdDialog(self, event):
  1695. """!Show command dialog"""
  1696. GUI(parent = self, modal = True).ParseCommand(cmd = ['v.in.dxf'])
  1697. class LayersList(GListCtrl, listmix.TextEditMixin):
  1698. """!List of layers to be imported (dxf, shp...)"""
  1699. def __init__(self, parent, columns, log = None):
  1700. GListCtrl.__init__(self, parent)
  1701. self.log = log
  1702. # setup mixins
  1703. listmix.TextEditMixin.__init__(self)
  1704. for i in range(len(columns)):
  1705. self.InsertColumn(i, columns[i])
  1706. if len(columns) == 3:
  1707. width = (65, 200)
  1708. else:
  1709. width = (65, 180, 110)
  1710. for i in range(len(width)):
  1711. self.SetColumnWidth(col = i, width = width[i])
  1712. def LoadData(self, data = None):
  1713. """!Load data into list"""
  1714. self.DeleteAllItems()
  1715. if data is None:
  1716. return
  1717. for item in data:
  1718. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1719. for i in range(1, len(item)):
  1720. self.SetStringItem(index, i, "%s" % str(item[i]))
  1721. # check by default only on one item
  1722. if len(data) == 1:
  1723. self.CheckItem(index, True)
  1724. def OnLeftDown(self, event):
  1725. """!Allow editing only output name
  1726. Code taken from TextEditMixin class.
  1727. """
  1728. x, y = event.GetPosition()
  1729. colLocs = [0]
  1730. loc = 0
  1731. for n in range(self.GetColumnCount()):
  1732. loc = loc + self.GetColumnWidth(n)
  1733. colLocs.append(loc)
  1734. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1735. if col == self.GetColumnCount() - 1:
  1736. listmix.TextEditMixin.OnLeftDown(self, event)
  1737. else:
  1738. event.Skip()
  1739. def GetLayers(self):
  1740. """!Get list of layers (layer name, output name)"""
  1741. data = []
  1742. item = -1
  1743. while True:
  1744. item = self.GetNextItem(item)
  1745. if item == -1:
  1746. break
  1747. if not self.IsChecked(item):
  1748. continue
  1749. # layer / output name
  1750. data.append((self.GetItem(item, 1).GetText(),
  1751. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1752. return data
  1753. class SetOpacityDialog(wx.Dialog):
  1754. """!Set opacity of map layers"""
  1755. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1756. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1757. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1758. self.parent = parent # GMFrame
  1759. self.opacity = opacity # current opacity
  1760. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1761. size = size, style = style, title = title)
  1762. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1763. sizer = wx.BoxSizer(wx.VERTICAL)
  1764. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1765. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1766. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1767. wx.SL_TOP | wx.SL_LABELS,
  1768. minValue = 0, maxValue = 100,
  1769. size = (350, -1))
  1770. box.Add(item = self.value,
  1771. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1772. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1773. label = _("transparent")),
  1774. pos = (1, 0))
  1775. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1776. label = _("opaque")),
  1777. flag = wx.ALIGN_RIGHT,
  1778. pos = (1, 1))
  1779. sizer.Add(item = box, proportion = 0,
  1780. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1781. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1782. style = wx.LI_HORIZONTAL)
  1783. sizer.Add(item = line, proportion = 0,
  1784. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1785. # buttons
  1786. btnsizer = wx.StdDialogButtonSizer()
  1787. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1788. btnOK.SetDefault()
  1789. btnsizer.AddButton(btnOK)
  1790. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1791. btnsizer.AddButton(btnCancel)
  1792. btnApply = wx.Button(parent = panel, id = wx.ID_APPLY)
  1793. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1794. btnsizer.AddButton(btnApply)
  1795. btnsizer.Realize()
  1796. sizer.Add(item = btnsizer, proportion = 0,
  1797. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1798. panel.SetSizer(sizer)
  1799. sizer.Fit(panel)
  1800. self.SetSize(self.GetBestSize())
  1801. self.Layout()
  1802. def GetOpacity(self):
  1803. """!Button 'OK' pressed"""
  1804. # return opacity value
  1805. opacity = float(self.value.GetValue()) / 100
  1806. return opacity
  1807. def OnApply(self, event):
  1808. event = wxApplyOpacity(value = self.GetOpacity())
  1809. wx.PostEvent(self, event)
  1810. def GetImageHandlers(image):
  1811. """!Get list of supported image handlers"""
  1812. lext = list()
  1813. ltype = list()
  1814. for h in image.GetHandlers():
  1815. lext.append(h.GetExtension())
  1816. filetype = ''
  1817. if 'png' in lext:
  1818. filetype += "PNG file (*.png)|*.png|"
  1819. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1820. 'ext' : 'png' })
  1821. filetype += "BMP file (*.bmp)|*.bmp|"
  1822. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1823. 'ext' : 'bmp' })
  1824. if 'gif' in lext:
  1825. filetype += "GIF file (*.gif)|*.gif|"
  1826. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1827. 'ext' : 'gif' })
  1828. if 'jpg' in lext:
  1829. filetype += "JPG file (*.jpg)|*.jpg|"
  1830. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1831. 'ext' : 'jpg' })
  1832. if 'pcx' in lext:
  1833. filetype += "PCX file (*.pcx)|*.pcx|"
  1834. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1835. 'ext' : 'pcx' })
  1836. if 'pnm' in lext:
  1837. filetype += "PNM file (*.pnm)|*.pnm|"
  1838. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1839. 'ext' : 'pnm' })
  1840. if 'tif' in lext:
  1841. filetype += "TIF file (*.tif)|*.tif|"
  1842. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1843. 'ext' : 'tif' })
  1844. if 'xpm' in lext:
  1845. filetype += "XPM file (*.xpm)|*.xpm"
  1846. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1847. 'ext' : 'xpm' })
  1848. return filetype, ltype
  1849. class ImageSizeDialog(wx.Dialog):
  1850. """!Set size for saved graphic file"""
  1851. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1852. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1853. self.parent = parent
  1854. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1855. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1856. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1857. label = ' % s' % _("Image size"))
  1858. size = self.parent.GetWindow().GetClientSize()
  1859. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1860. style = wx.SP_ARROW_KEYS)
  1861. self.width.SetRange(20, 1e6)
  1862. self.width.SetValue(size.width)
  1863. wx.CallAfter(self.width.SetFocus)
  1864. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1865. style = wx.SP_ARROW_KEYS)
  1866. self.height.SetRange(20, 1e6)
  1867. self.height.SetValue(size.height)
  1868. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1869. size = (125, -1),
  1870. choices = [ "",
  1871. "640x480",
  1872. "800x600",
  1873. "1024x768",
  1874. "1280x960",
  1875. "1600x1200",
  1876. "1920x1440" ])
  1877. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1878. self.btnOK.SetDefault()
  1879. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1880. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1881. self._layout()
  1882. self.SetSize(self.GetBestSize())
  1883. def _layout(self):
  1884. """!Do layout"""
  1885. sizer = wx.BoxSizer(wx.VERTICAL)
  1886. # body
  1887. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1888. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1889. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1890. label = _("Width:")),
  1891. flag = wx.ALIGN_CENTER_VERTICAL)
  1892. fbox.Add(item = self.width)
  1893. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1894. label = _("Height:")),
  1895. flag = wx.ALIGN_CENTER_VERTICAL)
  1896. fbox.Add(item = self.height)
  1897. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1898. label = _("Template:")),
  1899. flag = wx.ALIGN_CENTER_VERTICAL)
  1900. fbox.Add(item = self.template)
  1901. box.Add(item = fbox, proportion = 1,
  1902. flag = wx.EXPAND | wx.ALL, border = 5)
  1903. sizer.Add(item = box, proportion = 1,
  1904. flag=wx.EXPAND | wx.ALL, border = 3)
  1905. # buttons
  1906. btnsizer = wx.StdDialogButtonSizer()
  1907. btnsizer.AddButton(self.btnOK)
  1908. btnsizer.AddButton(self.btnCancel)
  1909. btnsizer.Realize()
  1910. sizer.Add(item = btnsizer, proportion = 0,
  1911. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1912. self.panel.SetSizer(sizer)
  1913. sizer.Fit(self.panel)
  1914. self.Layout()
  1915. def GetValues(self):
  1916. """!Get width/height values"""
  1917. return self.width.GetValue(), self.height.GetValue()
  1918. def OnTemplate(self, event):
  1919. """!Template selected"""
  1920. sel = event.GetString()
  1921. if not sel:
  1922. width, height = self.parent.GetWindow().GetClientSize()
  1923. else:
  1924. width, height = map(int, sel.split('x'))
  1925. self.width.SetValue(width)
  1926. self.height.SetValue(height)
  1927. class SqlQueryFrame(wx.Frame):
  1928. def __init__(self, parent, id = wx.ID_ANY,
  1929. title = _("GRASS GIS SQL Query Utility"),
  1930. *kwargs):
  1931. """!SQL Query Utility window
  1932. """
  1933. self.parent = parent
  1934. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1935. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1936. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1937. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1938. label = _(" SQL statement "))
  1939. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1940. style = wx.TE_MULTILINE)
  1941. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1942. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1943. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1944. self._layout()
  1945. self.SetMinSize(wx.Size(300, 150))
  1946. self.SetSize(wx.Size(500, 200))
  1947. def _layout(self):
  1948. """!Do layout"""
  1949. sizer = wx.BoxSizer(wx.VERTICAL)
  1950. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1951. sqlSizer.Add(item = self.sql, proportion = 1,
  1952. flag = wx.EXPAND)
  1953. btnSizer = wx.StdDialogButtonSizer()
  1954. btnSizer.AddButton(self.btnApply)
  1955. btnSizer.AddButton(self.btnCancel)
  1956. btnSizer.Realize()
  1957. sizer.Add(item = sqlSizer, proportion = 1,
  1958. flag = wx.EXPAND | wx.ALL, border = 5)
  1959. sizer.Add(item = btnSizer, proportion = 0,
  1960. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1961. self.panel.SetSizer(sizer)
  1962. self.Layout()
  1963. def OnCloseWindow(self, event):
  1964. """!Close window
  1965. """
  1966. self.Close()
  1967. class SymbolDialog(wx.Dialog):
  1968. """!Dialog for GRASS symbols selection.
  1969. Dialog is called in gui_core::forms module.
  1970. """
  1971. def __init__(self, parent, symbolPath, currentSymbol = None, title = _("Symbols")):
  1972. """!Dialog constructor.
  1973. It is assumed that symbolPath contains folders with symbols.
  1974. @param parent dialog parent
  1975. @param symbolPath absolute path to symbols
  1976. @param currentSymbol currently selected symbol (e.g. 'basic/x')
  1977. @param title dialog title
  1978. """
  1979. wx.Dialog.__init__(self, parent = parent, title = title, id = wx.ID_ANY)
  1980. self.symbolPath = symbolPath
  1981. self.currentSymbol = currentSymbol # default basic/x
  1982. self.selected = None
  1983. self.selectedDir = None
  1984. self._layout()
  1985. def _layout(self):
  1986. mainPanel = wx.Panel(self, id = wx.ID_ANY)
  1987. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1988. vSizer = wx.BoxSizer( wx.VERTICAL)
  1989. fgSizer = wx.FlexGridSizer(rows = 2, vgap = 5, hgap = 5)
  1990. self.folderChoice = wx.Choice(mainPanel, id = wx.ID_ANY, choices = os.listdir(self.symbolPath))
  1991. self.folderChoice.Bind(wx.EVT_CHOICE, self.OnFolderSelect)
  1992. fgSizer.Add(item = wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol directory:")),
  1993. proportion = 0,
  1994. flag = wx.ALIGN_CENTER_VERTICAL)
  1995. fgSizer.Add(item = self.folderChoice, proportion = 0,
  1996. flag = wx.ALIGN_CENTER, border = 0)
  1997. self.infoLabel = wx.StaticText(mainPanel, id = wx.ID_ANY)
  1998. fgSizer.Add(wx.StaticText(mainPanel, id = wx.ID_ANY, label = _("Symbol name:")),
  1999. flag = wx.ALIGN_CENTRE_VERTICAL)
  2000. fgSizer.Add(self.infoLabel, proportion = 0,
  2001. flag = wx.ALIGN_CENTRE_VERTICAL)
  2002. vSizer.Add(fgSizer, proportion = 0, flag = wx.ALL, border = 5)
  2003. self.panels = self._createSymbolPanels(mainPanel)
  2004. for panel in self.panels:
  2005. vSizer.Add(panel, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5)
  2006. panel.Bind(EVT_SYMBOL_SELECTION_CHANGED, self.SelectionChanged)
  2007. mainSizer.Add(vSizer, proportion = 1, flag = wx.ALL| wx.EXPAND, border = 5)
  2008. self.btnCancel = wx.Button(parent = mainPanel, id = wx.ID_CANCEL)
  2009. self.btnOK = wx.Button(parent = mainPanel, id = wx.ID_OK)
  2010. self.btnOK.SetDefault()
  2011. self.btnOK.Enable(False)
  2012. # buttons
  2013. btnSizer = wx.StdDialogButtonSizer()
  2014. btnSizer.AddButton(self.btnCancel)
  2015. btnSizer.AddButton(self.btnOK)
  2016. btnSizer.Realize()
  2017. mainSizer.Add(item = btnSizer, proportion = 0,
  2018. flag = wx.EXPAND | wx.ALL, border = 5)
  2019. # show panel with the largest number of images and fit size
  2020. count = []
  2021. for folder in os.listdir(self.symbolPath):
  2022. count.append(len(os.listdir(os.path.join(self.symbolPath, folder))))
  2023. index = count.index(max(count))
  2024. self.folderChoice.SetSelection(index)
  2025. self.OnFolderSelect(None)
  2026. self.infoLabel.Show()
  2027. mainPanel.SetSizerAndFit(mainSizer)
  2028. self.SetSize(self.GetBestSize())
  2029. # show currently selected symbol
  2030. if self.currentSymbol:
  2031. # set directory
  2032. self.selectedDir, self.selected = os.path.split(self.currentSymbol)
  2033. self.folderChoice.SetStringSelection(self.selectedDir)
  2034. # select symbol
  2035. panelIdx = self.folderChoice.GetSelection()
  2036. for panel in self.symbolPanels[panelIdx]:
  2037. if panel.GetName() == self.selected:
  2038. panel.Select()
  2039. else:
  2040. self.folderChoice.SetSelection(0)
  2041. self.OnFolderSelect(None)
  2042. def _createSymbolPanels(self, parent):
  2043. """!Creates multiple panels with symbols.
  2044. Panels are shown/hidden according to selected folder."""
  2045. folders = os.listdir(self.symbolPath)
  2046. panels = []
  2047. self.symbolPanels = []
  2048. for folder in folders:
  2049. panel = wx.Panel(parent, style = wx.BORDER_RAISED)
  2050. sizer = wx.GridSizer(cols = 6, vgap = 3, hgap = 3)
  2051. images = self._getSymbols(path = os.path.join(self.symbolPath, folder))
  2052. symbolPanels = []
  2053. for img in images:
  2054. iP = SingleSymbolPanel(parent = panel, symbolPath = img)
  2055. sizer.Add(item = iP, proportion = 0, flag = wx.ALIGN_CENTER)
  2056. symbolPanels.append(iP)
  2057. panel.SetSizerAndFit(sizer)
  2058. panel.Hide()
  2059. panels.append(panel)
  2060. self.symbolPanels.append(symbolPanels)
  2061. return panels
  2062. def _getSymbols(self, path):
  2063. # we assume that images are in subfolders (1 level only)
  2064. imageList = []
  2065. for image in os.listdir(path):
  2066. imageList.append(os.path.join(path, image))
  2067. return sorted(imageList)
  2068. def OnFolderSelect(self, event):
  2069. """!Selected folder with symbols changed."""
  2070. idx = self.folderChoice.GetSelection()
  2071. for i in range(len(self.panels)):
  2072. sizer = self.panels[i].GetContainingSizer()
  2073. sizer.Show(self.panels[i], i == idx, recursive = True)
  2074. sizer.Layout()
  2075. if self.selectedDir == self.folderChoice.GetStringSelection():
  2076. self.btnOK.Enable()
  2077. self.infoLabel.SetLabel(self.selected)
  2078. else:
  2079. self.btnOK.Disable()
  2080. self.infoLabel.SetLabel('')
  2081. def SelectionChanged(self, event):
  2082. """!Selected symbol changed."""
  2083. if event.doubleClick:
  2084. self.EndModal(wx.ID_OK)
  2085. # deselect all
  2086. for i in range(len(self.panels)):
  2087. for panel in self.symbolPanels[i]:
  2088. if panel.GetName() != event.name:
  2089. panel.Deselect()
  2090. self.btnOK.Enable()
  2091. self.selected = event.name
  2092. self.selectedDir = self.folderChoice.GetStringSelection()
  2093. self.infoLabel.SetLabel(event.name)
  2094. def GetSelectedSymbolName(self):
  2095. """!Returns currently selected symbol name (e.g. 'basic/x').
  2096. """
  2097. # separator must be '/' and not dependent on OS
  2098. return self.selectedDir + '/' + self.selected
  2099. def GetSelectedSymbolPath(self):
  2100. """!Returns currently selected symbol full path.
  2101. """
  2102. return os.path.join(self.symbolPath, self.selectedDir, self.selected)