dialogs.py 98 KB

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