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