gdialogs.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  1. """!
  2. @package gdialogs.py
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - ElementDialog
  6. - LocationDialog
  7. - MapsetDialog
  8. - NewVectorDialog
  9. - SavedRegion
  10. - DecorationDialog
  11. - TextLayerDialog
  12. - MapLayersDialog
  13. - ImportDialog
  14. - GdalImportDialog
  15. - GdalOutputDialog
  16. - DxfImportDialog
  17. - LayersList (used by MultiImport)
  18. - SetOpacityDialog
  19. - StaticWrapText
  20. - ImageSizeDialog
  21. - SqlQueryFrame
  22. (C) 2008-2011 by the GRASS Development Team
  23. This program is free software under the GNU General Public
  24. License (>=v2). Read the file COPYING that comes with GRASS
  25. for details.
  26. @author Martin Landa <landa.martin gmail.com>
  27. """
  28. import os
  29. import sys
  30. import re
  31. from bisect import bisect
  32. import wx
  33. import wx.lib.filebrowsebutton as filebrowse
  34. import wx.lib.mixins.listctrl as listmix
  35. from grass.script import core as grass
  36. from grass.script import task as gtask
  37. import gcmd
  38. import globalvar
  39. import gselect
  40. import menuform
  41. import utils
  42. from preferences import globalSettings as UserSettings
  43. from debug import Debug
  44. class ElementDialog(wx.Dialog):
  45. def __init__(self, parent, title, label, id = wx.ID_ANY,
  46. etype = False, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  47. **kwargs):
  48. """!General dialog to choose given element (location, mapset, vector map, etc.)
  49. @param parent window
  50. @param title window title
  51. @param label element label
  52. @param etype show also ElementSelect
  53. """
  54. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  55. self.etype = etype
  56. self.label = label
  57. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  58. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  59. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  60. self.btnOK.SetDefault()
  61. self.btnOK.Enable(False)
  62. if self.etype:
  63. self.typeSelect = gselect.ElementSelect(parent = self.panel,
  64. size = globalvar.DIALOG_GSELECT_SIZE)
  65. self.typeSelect.Bind(wx.EVT_CHOICE, self.OnType)
  66. self.element = None # must be defined
  67. self.__layout()
  68. def PostInit(self):
  69. self.element.SetFocus()
  70. self.element.Bind(wx.EVT_TEXT, self.OnElement)
  71. def OnType(self, event):
  72. """!Select element type"""
  73. if not self.etype:
  74. return
  75. evalue = self.typeSelect.GetValue(event.GetString())
  76. self.element.SetType(evalue)
  77. def OnElement(self, event):
  78. """!Name for vector map layer given"""
  79. if len(event.GetString()) > 0:
  80. self.btnOK.Enable(True)
  81. else:
  82. self.btnOK.Enable(False)
  83. def __layout(self):
  84. """!Do layout"""
  85. self.sizer = wx.BoxSizer(wx.VERTICAL)
  86. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  87. if self.etype:
  88. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  89. label = _("Type of element:")),
  90. proportion = 0, flag = wx.ALL, border = 1)
  91. self.dataSizer.Add(item = self.typeSelect,
  92. proportion = 0, flag = wx.ALL, border = 1)
  93. self.dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  94. label = self.label),
  95. proportion = 0, flag = wx.ALL, border = 1)
  96. # buttons
  97. btnSizer = wx.StdDialogButtonSizer()
  98. btnSizer.AddButton(self.btnCancel)
  99. btnSizer.AddButton(self.btnOK)
  100. btnSizer.Realize()
  101. self.sizer.Add(item = self.dataSizer, proportion = 1,
  102. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  103. self.sizer.Add(item = btnSizer, proportion = 0,
  104. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  105. def GetElement(self):
  106. """!Return (mapName, overwrite)"""
  107. return self.element.GetValue()
  108. def GetType(self):
  109. """!Get element type"""
  110. return self.element.tcp.GetType()
  111. class LocationDialog(ElementDialog):
  112. """!Dialog used to select location"""
  113. def __init__(self, parent, title = _("Select GRASS location and mapset"), id = wx.ID_ANY):
  114. ElementDialog.__init__(self, parent, title, label = _("Name of GRASS location:"))
  115. self.element = gselect.LocationSelect(parent = self.panel, id = wx.ID_ANY,
  116. size = globalvar.DIALOG_GSELECT_SIZE)
  117. self.element1 = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  118. size = globalvar.DIALOG_GSELECT_SIZE,
  119. setItems = False)
  120. self.PostInit()
  121. self.__Layout()
  122. self.SetMinSize(self.GetSize())
  123. def __Layout(self):
  124. """!Do layout"""
  125. self.dataSizer.Add(self.element, proportion = 0,
  126. flag = wx.EXPAND | wx.ALL, border = 1)
  127. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  128. label = _("Name of mapset:")), proportion = 0,
  129. flag = wx.EXPAND | wx.ALL, border = 1)
  130. self.dataSizer.Add(self.element1, proportion = 0,
  131. flag = wx.EXPAND | wx.ALL, border = 1)
  132. self.panel.SetSizer(self.sizer)
  133. self.sizer.Fit(self)
  134. def OnElement(self, event):
  135. """!Select mapset given location name"""
  136. location = event.GetString()
  137. if location:
  138. dbase = grass.gisenv()['GISDBASE']
  139. self.element1.SetItems(utils.GetListOfMapsets(dbase, location, selectable = True))
  140. self.element1.SetSelection(0)
  141. mapset = self.element1.GetStringSelection()
  142. if location and mapset:
  143. self.btnOK.Enable(True)
  144. else:
  145. self.btnOK.Enable(False)
  146. def GetValues(self):
  147. """!Get location, mapset"""
  148. return (self.GetElement(), self.element1.GetStringSelection())
  149. class MapsetDialog(ElementDialog):
  150. """!Dialog used to select mapset"""
  151. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  152. location = None, id = wx.ID_ANY):
  153. ElementDialog.__init__(self, parent, title, label = _("Name of mapset:"))
  154. if location:
  155. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  156. else:
  157. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  158. self.element = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  159. size = globalvar.DIALOG_GSELECT_SIZE)
  160. self.PostInit()
  161. self.__Layout()
  162. self.SetMinSize(self.GetSize())
  163. def __Layout(self):
  164. """!Do layout"""
  165. self.dataSizer.Add(self.element, proportion = 0,
  166. flag = wx.EXPAND | wx.ALL, border = 1)
  167. self.panel.SetSizer(self.sizer)
  168. self.sizer.Fit(self)
  169. def GetMapset(self):
  170. return self.GetElement()
  171. class NewVectorDialog(ElementDialog):
  172. def __init__(self, parent, id = wx.ID_ANY, title = _('Create new vector map'),
  173. disableAdd = False, disableTable = False, showType = False,
  174. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  175. """!Dialog for creating new vector map
  176. @param parent parent window
  177. @param id window id
  178. @param title window title
  179. @param disableAdd disable 'add layer' checkbox
  180. @param disableTable disable 'create table' checkbox
  181. @param showType True to show feature type selector (used for creating new empty OGR layers)
  182. @param style window style
  183. @param kwargs other argumentes for ElementDialog
  184. @return dialog instance
  185. """
  186. ElementDialog.__init__(self, parent, title, label = _("Name for new vector map:"))
  187. self.element = gselect.Select(parent = self.panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  188. type = 'vector', mapsets = [grass.gisenv()['MAPSET'],])
  189. # determine output format
  190. if showType:
  191. self.ftype = gselect.OgrTypeSelect(parent = self, panel = self.panel)
  192. else:
  193. self.ftype = None
  194. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  195. label = _("Create attribute table"))
  196. self.table.SetValue(True)
  197. if disableTable:
  198. self.table.Enable(False)
  199. self.keycol = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  200. size = globalvar.DIALOG_SPIN_SIZE)
  201. self.keycol.SetValue(UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value'))
  202. if disableTable:
  203. self.keycol.Enable(False)
  204. self.addbox = wx.CheckBox(parent = self.panel,
  205. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  206. if disableAdd:
  207. self.addbox.SetValue(True)
  208. self.addbox.Enable(False)
  209. else:
  210. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  211. self.table.Bind(wx.EVT_CHECKBOX, self.OnTable)
  212. self.PostInit()
  213. self._layout()
  214. self.SetMinSize(self.GetSize())
  215. def OnMapName(self, event):
  216. """!Name for vector map layer given"""
  217. self.OnElement(event)
  218. def OnTable(self, event):
  219. self.keycol.Enable(event.IsChecked())
  220. def _layout(self):
  221. """!Do layout"""
  222. self.dataSizer.Add(item = self.element, proportion = 0,
  223. flag = wx.EXPAND | wx.ALL, border = 1)
  224. if self.ftype:
  225. self.dataSizer.AddSpacer(1)
  226. self.dataSizer.Add(item = self.ftype, proportion = 0,
  227. flag = wx.EXPAND | wx.ALL, border = 1)
  228. self.dataSizer.Add(item = self.table, proportion = 0,
  229. flag = wx.EXPAND | wx.ALL, border = 1)
  230. keySizer = wx.BoxSizer(wx.HORIZONTAL)
  231. keySizer.Add(item = wx.StaticText(parent = self.panel, label = _("Key column:")),
  232. proportion = 0,
  233. flag = wx.ALIGN_CENTER_VERTICAL)
  234. keySizer.AddSpacer(10)
  235. keySizer.Add(item = self.keycol, proportion = 0,
  236. flag = wx.ALIGN_RIGHT)
  237. self.dataSizer.Add(item = keySizer, proportion = 1,
  238. flag = wx.EXPAND | wx.ALL, border = 1)
  239. self.dataSizer.AddSpacer(5)
  240. self.dataSizer.Add(item = self.addbox, proportion = 0,
  241. flag = wx.EXPAND | wx.ALL, border = 1)
  242. self.panel.SetSizer(self.sizer)
  243. self.sizer.Fit(self)
  244. def GetName(self, full = False):
  245. """!Get name of vector map to be created
  246. @param full True to get fully qualified name
  247. """
  248. name = self.GetElement()
  249. if full:
  250. if '@' in name:
  251. return name
  252. else:
  253. return name + '@' + grass.gisenv()['MAPSET']
  254. return name.split('@', 1)[0]
  255. def GetKey(self):
  256. """!Get key column name"""
  257. return self.keycol.GetValue()
  258. def IsChecked(self, key):
  259. """!Get dialog properties
  260. @param key window key ('add', 'table')
  261. @return True/False
  262. @return None on error
  263. """
  264. if key == 'add':
  265. return self.addbox.IsChecked()
  266. elif key == 'table':
  267. return self.table.IsChecked()
  268. return None
  269. def GetFeatureType(self):
  270. """!Get feature type for OGR
  271. @return feature type as string
  272. @return None for native format
  273. """
  274. if self.ftype:
  275. return self.ftype.GetType()
  276. return None
  277. def CreateNewVector(parent, cmd, title = _('Create new vector map'),
  278. exceptMap = None, log = None,
  279. disableAdd = False, disableTable = False):
  280. """!Create new vector map layer
  281. @param cmd (prog, **kwargs)
  282. @param title window title
  283. @param exceptMap list of maps to be excepted
  284. @param log
  285. @param disableAdd disable 'add layer' checkbox
  286. @param disableTable disable 'create table' checkbox
  287. @return dialog instance
  288. @return None on error
  289. """
  290. vExternalOut = grass.parse_command('v.external.out', flags = 'g')
  291. isNative = vExternalOut['format'] == 'native'
  292. if cmd[0] == 'v.edit' and not isNative:
  293. showType = True
  294. else:
  295. showType = False
  296. dlg = NewVectorDialog(parent, title = title,
  297. disableAdd = disableAdd, disableTable = disableTable,
  298. showType = showType)
  299. if dlg.ShowModal() != wx.ID_OK:
  300. dlg.Destroy()
  301. return None
  302. outmap = dlg.GetName()
  303. key = dlg.GetKey()
  304. if outmap == exceptMap:
  305. gcmd.GError(parent = parent,
  306. message = _("Unable to create vector map <%s>.") % outmap)
  307. dlg.Destroy()
  308. return None
  309. if dlg.table.IsEnabled() and not key:
  310. gcmd.GError(parent = parent,
  311. message = _("Invalid or empty key column.\n"
  312. "Unable to create vector map <%s>.") % outmap)
  313. dlg.Destroy()
  314. return
  315. if outmap == '': # should not happen
  316. dlg.Destroy()
  317. return None
  318. # update cmd -> output name defined
  319. cmd[1][cmd[2]] = outmap
  320. if showType:
  321. cmd[1]['type'] = dlg.GetFeatureType()
  322. if isNative:
  323. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  324. else:
  325. listOfVectors = gcmd.RunCommand('v.external',
  326. quiet = True,
  327. parent = parent,
  328. read = True,
  329. flags = 'l',
  330. dsn = vExternalOut['dsn'])
  331. overwrite = False
  332. if not UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled') and \
  333. outmap in listOfVectors:
  334. dlgOw = wx.MessageDialog(parent, message = _("Vector map <%s> already exists "
  335. "in the current mapset. "
  336. "Do you want to overwrite it?") % outmap,
  337. caption = _("Overwrite?"),
  338. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  339. if dlgOw.ShowModal() == wx.ID_YES:
  340. overwrite = True
  341. else:
  342. dlgOw.Destroy()
  343. dlg.Destroy()
  344. return None
  345. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  346. overwrite = True
  347. ret = gcmd.RunCommand(prog = cmd[0],
  348. parent = parent,
  349. overwrite = overwrite,
  350. **cmd[1])
  351. if ret != 0:
  352. dlg.Destroy()
  353. return None
  354. if not isNative:
  355. # create link for OGR layers
  356. gcmd.RunCommand('v.external',
  357. overwrite = overwrite,
  358. parent = parent,
  359. dsn = vExternalOut['dsn'],
  360. layer = outmap)
  361. # create attribute table
  362. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  363. if isNative:
  364. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  365. gcmd.RunCommand('db.connect',
  366. flags = 'c')
  367. Debug.msg(1, "SQL: %s" % sql)
  368. gcmd.RunCommand('db.execute',
  369. quiet = True,
  370. parent = parent,
  371. input = '-',
  372. stdin = sql)
  373. gcmd.RunCommand('v.db.connect',
  374. quiet = True,
  375. parent = parent,
  376. map = outmap,
  377. table = outmap,
  378. key = key,
  379. layer = '1')
  380. # TODO: how to deal with attribute tables for OGR layers?
  381. # return fully qualified map name
  382. if '@' not in outmap:
  383. outmap += '@' + grass.gisenv()['MAPSET']
  384. if log:
  385. log.WriteLog(_("New vector map <%s> created") % outmap)
  386. return dlg
  387. class SavedRegion(wx.Dialog):
  388. def __init__(self, parent, id = wx.ID_ANY, title = "", loadsave = 'load',
  389. **kwargs):
  390. """!Loading and saving of display extents to saved region file
  391. @param loadsave load or save region?
  392. """
  393. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  394. self.loadsave = loadsave
  395. self.wind = ''
  396. sizer = wx.BoxSizer(wx.VERTICAL)
  397. box = wx.BoxSizer(wx.HORIZONTAL)
  398. label = wx.StaticText(parent = self, id = wx.ID_ANY)
  399. box.Add(item = label, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  400. if loadsave == 'load':
  401. label.SetLabel(_("Load region:"))
  402. selection = gselect.Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  403. type = 'windows')
  404. elif loadsave == 'save':
  405. label.SetLabel(_("Save region:"))
  406. selection = gselect.Select(parent = self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  407. type = 'windows', mapsets = [grass.gisenv()['MAPSET']])
  408. box.Add(item = selection, proportion = 0, flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  409. selection.SetFocus()
  410. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  411. sizer.Add(item = box, proportion = 0, flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,
  412. border = 5)
  413. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20, -1), style = wx.LI_HORIZONTAL)
  414. sizer.Add(item = line, proportion = 0,
  415. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 5)
  416. btnsizer = wx.StdDialogButtonSizer()
  417. btn = wx.Button(parent = self, id = wx.ID_OK)
  418. btn.SetDefault()
  419. btnsizer.AddButton(btn)
  420. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  421. btnsizer.AddButton(btn)
  422. btnsizer.Realize()
  423. sizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  424. self.SetSizer(sizer)
  425. sizer.Fit(self)
  426. self.Layout()
  427. def OnRegion(self, event):
  428. self.wind = event.GetString()
  429. class DecorationDialog(wx.Dialog):
  430. """
  431. Controls setting options and displaying/hiding map overlay decorations
  432. """
  433. def __init__(self, parent, ovlId, title, cmd, name = None,
  434. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE,
  435. checktxt = '', ctrltxt = ''):
  436. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  437. self.ovlId = ovlId # PseudoDC id
  438. self.cmd = cmd
  439. self.name = name # overlay name
  440. self.parent = parent # MapFrame
  441. sizer = wx.BoxSizer(wx.VERTICAL)
  442. box = wx.BoxSizer(wx.HORIZONTAL)
  443. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY, label = checktxt)
  444. if self.parent.Map.GetOverlay(self.ovlId) is None:
  445. self.chkbox.SetValue(True)
  446. else:
  447. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  448. box.Add(item = self.chkbox, proportion = 0,
  449. flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  450. sizer.Add(item = box, proportion = 0,
  451. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  452. box = wx.BoxSizer(wx.HORIZONTAL)
  453. optnbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set options"))
  454. box.Add(item = optnbtn, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 5)
  455. sizer.Add(item = box, proportion = 0,
  456. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  457. if self.name == 'legend':
  458. box = wx.BoxSizer(wx.HORIZONTAL)
  459. resize = wx.ToggleButton(parent = self, id = wx.ID_ANY, label = _("Set size and position"))
  460. resize.SetToolTipString(_("Click and drag on the map display to set legend"
  461. " size and position and then press OK"))
  462. resize.SetName('resize')
  463. if self.parent.IsPaneShown('3d'):
  464. resize.Disable()
  465. box.Add(item = resize, 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. box = wx.BoxSizer(wx.HORIZONTAL)
  469. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  470. label = _("Drag %s with mouse in pointer mode to position.\n"
  471. "Double-click to change options." % ctrltxt))
  472. if self.name == 'legend':
  473. label.SetLabel(label.GetLabel() + _('\nDefine raster map name for legend in '
  474. 'properties dialog.'))
  475. box.Add(item = label, proportion = 0,
  476. 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. line = wx.StaticLine(parent = self, id = wx.ID_ANY, size = (20,-1), style = wx.LI_HORIZONTAL)
  480. sizer.Add(item = line, proportion = 0,
  481. flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
  482. # buttons
  483. btnsizer = wx.StdDialogButtonSizer()
  484. self.btnOK = wx.Button(parent = self, id = wx.ID_OK)
  485. self.btnOK.SetDefault()
  486. if self.name == 'legend':
  487. self.btnOK.Enable(False)
  488. btnsizer.AddButton(self.btnOK)
  489. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  490. btnsizer.AddButton(btnCancel)
  491. btnsizer.Realize()
  492. sizer.Add(item = btnsizer, proportion = 0,
  493. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  494. #
  495. # bindings
  496. #
  497. self.Bind(wx.EVT_BUTTON, self.OnOptions, optnbtn)
  498. if self.name == 'legend':
  499. self.Bind(wx.EVT_TOGGLEBUTTON, self.OnResize, resize)
  500. self.Bind(wx.EVT_BUTTON, self.OnCancel, btnCancel)
  501. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  502. self.SetSizer(sizer)
  503. sizer.Fit(self)
  504. # create overlay if doesn't exist
  505. self._CreateOverlay()
  506. if len(self.parent.MapWindow.overlays[self.ovlId]['cmd']) > 1:
  507. if name == 'legend':
  508. mapName, found = utils.GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd'])
  509. if found:
  510. # enable 'OK' button
  511. self.btnOK.Enable()
  512. # set title
  513. self.SetTitle(_('Legend of raster map <%s>') % \
  514. mapName)
  515. def _CreateOverlay(self):
  516. if not self.parent.Map.GetOverlay(self.ovlId):
  517. self.newOverlay = self.parent.Map.AddOverlay(id = self.ovlId, type = self.name,
  518. command = self.cmd,
  519. l_active = False, l_render = False, l_hidden = True)
  520. prop = { 'layer' : self.newOverlay,
  521. 'params' : None,
  522. 'propwin' : None,
  523. 'cmd' : self.cmd,
  524. 'coords': (0, 0),
  525. 'pdcType': 'image' }
  526. self.parent.MapWindow2D.overlays[self.ovlId] = prop
  527. if self.parent.MapWindow3D:
  528. self.parent.MapWindow3D.overlays[self.ovlId] = prop
  529. else:
  530. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] == None:
  531. return
  532. self.parent.MapWindow.overlays[self.ovlId]['propwin'].get_dcmd = self.GetOptData
  533. def OnOptions(self, event):
  534. """ self.SetSizer(sizer)
  535. sizer.Fit(self)
  536. Sets option for decoration map overlays
  537. """
  538. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None:
  539. # build properties dialog
  540. menuform.GUI(parent = self.parent).ParseCommand(cmd = self.cmd,
  541. completed = (self.GetOptData, self.name, ''))
  542. else:
  543. if self.parent.MapWindow.overlays[self.ovlId]['propwin'].IsShown():
  544. self.parent.MapWindow.overlays[self.ovlId]['propwin'].SetFocus()
  545. else:
  546. self.parent.MapWindow.overlays[self.ovlId]['propwin'].Show()
  547. def OnResize(self, event):
  548. if self.FindWindowByName('resize').GetValue():
  549. self.parent.MapWindow.SetCursor(self.parent.cursors["cross"])
  550. self.parent.MapWindow.mouse['use'] = 'legend'
  551. self.parent.MapWindow.mouse['box'] = 'box'
  552. self.parent.MapWindow.pen = wx.Pen(colour = 'Black', width = 2, style = wx.SHORT_DASH)
  553. else:
  554. self.parent.MapWindow.SetCursor(self.parent.cursors["default"])
  555. self.parent.MapWindow.mouse['use'] = 'pointer'
  556. def OnCancel(self, event):
  557. """!Cancel dialog"""
  558. if self.name == 'legend' and self.FindWindowByName('resize').GetValue():
  559. self.FindWindowByName('resize').SetValue(False)
  560. self.OnResize(None)
  561. self.parent.dialogs['barscale'] = None
  562. if event and hasattr(self, 'newOverlay'):
  563. self.parent.Map.DeleteOverlay(self.newOverlay)
  564. self.Destroy()
  565. def OnOK(self, event):
  566. """!Button 'OK' pressed"""
  567. # enable or disable overlay
  568. self.parent.Map.GetOverlay(self.ovlId).SetActive(self.chkbox.IsChecked())
  569. # update map
  570. if self.parent.IsPaneShown('3d'):
  571. self.parent.MapWindow.UpdateOverlays()
  572. self.parent.MapWindow.UpdateMap()
  573. # close dialog
  574. self.OnCancel(None)
  575. def GetOptData(self, dcmd, layer, params, propwin):
  576. """!Process decoration layer data"""
  577. # update layer data
  578. if params:
  579. self.parent.MapWindow.overlays[self.ovlId]['params'] = params
  580. if dcmd:
  581. self.parent.MapWindow.overlays[self.ovlId]['cmd'] = dcmd
  582. self.parent.MapWindow.overlays[self.ovlId]['propwin'] = propwin
  583. # change parameters for item in layers list in render.Map
  584. # "Use mouse..." (-m) flag causes GUI freeze and is pointless here, trac #119
  585. try:
  586. self.parent.MapWindow.overlays[self.ovlId]['cmd'].remove('-m')
  587. except ValueError:
  588. pass
  589. self.parent.Map.ChangeOverlay(id = self.ovlId, type = self.name,
  590. command = self.parent.MapWindow.overlays[self.ovlId]['cmd'],
  591. l_active = self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive(),
  592. l_render = False, l_hidden = True)
  593. if self.name == 'legend':
  594. if params and not self.btnOK.IsEnabled():
  595. self.btnOK.Enable()
  596. class TextLayerDialog(wx.Dialog):
  597. """
  598. Controls setting options and displaying/hiding map overlay decorations
  599. """
  600. def __init__(self, parent, ovlId, title, name = 'text',
  601. pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE):
  602. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  603. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  604. self.ovlId = ovlId
  605. self.parent = parent
  606. if self.ovlId in self.parent.MapWindow.textdict.keys():
  607. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  608. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  609. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  610. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  611. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  612. self.currBB = self.parent.MapWindow.textdict[self.ovlId]['bbox']
  613. else:
  614. self.currClr = wx.BLACK
  615. self.currText = ''
  616. self.currFont = self.GetFont()
  617. self.currRot = 0.0
  618. self.currCoords = [10, 10]
  619. self.currBB = wx.Rect()
  620. self.sizer = wx.BoxSizer(wx.VERTICAL)
  621. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  622. # show/hide
  623. self.chkbox = wx.CheckBox(parent = self, id = wx.ID_ANY,
  624. label = _('Show text object'))
  625. if self.parent.Map.GetOverlay(self.ovlId) is None:
  626. self.chkbox.SetValue(True)
  627. else:
  628. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  629. box.Add(item = self.chkbox, span = (1,2),
  630. flag = wx.ALIGN_LEFT|wx.ALL, border = 5,
  631. pos = (0, 0))
  632. # text entry
  633. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Enter text:"))
  634. box.Add(item = label,
  635. flag = wx.ALIGN_CENTER_VERTICAL,
  636. pos = (1, 0))
  637. self.textentry = ExpandoTextCtrl(parent = self, id = wx.ID_ANY, value = "", size = (300,-1))
  638. self.textentry.SetFont(self.currFont)
  639. self.textentry.SetForegroundColour(self.currClr)
  640. self.textentry.SetValue(self.currText)
  641. # get rid of unneeded scrollbar when text box first opened
  642. self.textentry.SetClientSize((300,-1))
  643. box.Add(item = self.textentry,
  644. pos = (1, 1))
  645. # rotation
  646. label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Rotation:"))
  647. box.Add(item = label,
  648. flag = wx.ALIGN_CENTER_VERTICAL,
  649. pos = (2, 0))
  650. self.rotation = wx.SpinCtrl(parent = self, id = wx.ID_ANY, value = "", pos = (30, 50),
  651. size = (75,-1), style = wx.SP_ARROW_KEYS)
  652. self.rotation.SetRange(-360, 360)
  653. self.rotation.SetValue(int(self.currRot))
  654. box.Add(item = self.rotation,
  655. flag = wx.ALIGN_RIGHT,
  656. pos = (2, 1))
  657. # font
  658. fontbtn = wx.Button(parent = self, id = wx.ID_ANY, label = _("Set font"))
  659. box.Add(item = fontbtn,
  660. flag = wx.ALIGN_RIGHT,
  661. pos = (3, 1))
  662. self.sizer.Add(item = box, proportion = 1,
  663. flag = wx.ALL, border = 10)
  664. # note
  665. box = wx.BoxSizer(wx.HORIZONTAL)
  666. label = wx.StaticText(parent = self, id = wx.ID_ANY,
  667. label = _("Drag text with mouse in pointer mode "
  668. "to position.\nDouble-click to change options"))
  669. box.Add(item = label, proportion = 0,
  670. flag = wx.ALIGN_CENTRE | wx.ALL, border = 5)
  671. self.sizer.Add(item = box, proportion = 0,
  672. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border = 5)
  673. line = wx.StaticLine(parent = self, id = wx.ID_ANY,
  674. size = (20,-1), style = wx.LI_HORIZONTAL)
  675. self.sizer.Add(item = line, proportion = 0,
  676. flag = wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border = 5)
  677. btnsizer = wx.StdDialogButtonSizer()
  678. btn = wx.Button(parent = self, id = wx.ID_OK)
  679. btn.SetDefault()
  680. btnsizer.AddButton(btn)
  681. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  682. btnsizer.AddButton(btn)
  683. btnsizer.Realize()
  684. self.sizer.Add(item = btnsizer, proportion = 0,
  685. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  686. self.SetSizer(self.sizer)
  687. self.sizer.Fit(self)
  688. # bindings
  689. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  690. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  691. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  692. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  693. def OnRefit(self, event):
  694. """!Resize text entry to match text"""
  695. self.sizer.Fit(self)
  696. def OnText(self, event):
  697. """!Change text string"""
  698. self.currText = event.GetString()
  699. def OnRotation(self, event):
  700. """!Change rotation"""
  701. self.currRot = event.GetInt()
  702. event.Skip()
  703. def OnSelectFont(self, event):
  704. """!Change font"""
  705. data = wx.FontData()
  706. data.EnableEffects(True)
  707. data.SetColour(self.currClr) # set colour
  708. data.SetInitialFont(self.currFont)
  709. dlg = wx.FontDialog(self, data)
  710. if dlg.ShowModal() == wx.ID_OK:
  711. data = dlg.GetFontData()
  712. self.currFont = data.GetChosenFont()
  713. self.currClr = data.GetColour()
  714. self.textentry.SetFont(self.currFont)
  715. self.textentry.SetForegroundColour(self.currClr)
  716. self.Layout()
  717. dlg.Destroy()
  718. def GetValues(self):
  719. """!Get text properties"""
  720. return { 'text' : self.currText,
  721. 'font' : self.currFont,
  722. 'color' : self.currClr,
  723. 'rotation' : self.currRot,
  724. 'coords' : self.currCoords,
  725. 'active' : self.chkbox.IsChecked() }
  726. class MapLayersDialog(wx.Dialog):
  727. def __init__(self, parent, title,
  728. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  729. """!Dialog for selecting map layers (raster, vector)"""
  730. wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title,
  731. style = style, **kwargs)
  732. self.parent = parent # GMFrame or ?
  733. # dialog body
  734. self.bodySizer = self._createDialogBody()
  735. # update list of layer to be loaded
  736. self.map_layers = [] # list of map layers (full list type/mapset)
  737. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  738. self.mapset.GetStringSelection())
  739. self.fullyQualified = wx.CheckBox(parent = self, id = wx.ID_ANY,
  740. label = _("Use fully-qualified map names"))
  741. self.fullyQualified.SetValue(True)
  742. # buttons
  743. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  744. btnOk = wx.Button(parent = self, id = wx.ID_OK)
  745. btnOk.SetDefault()
  746. # sizers & do layout
  747. btnSizer = wx.StdDialogButtonSizer()
  748. btnSizer.AddButton(btnCancel)
  749. btnSizer.AddButton(btnOk)
  750. btnSizer.Realize()
  751. mainSizer = wx.BoxSizer(wx.VERTICAL)
  752. mainSizer.Add(item = self.bodySizer, proportion = 1,
  753. flag = wx.EXPAND | wx.ALL, border = 5)
  754. mainSizer.Add(item = self.fullyQualified, proportion = 0,
  755. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  756. mainSizer.Add(item = btnSizer, proportion = 0,
  757. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  758. self.SetSizer(mainSizer)
  759. mainSizer.Fit(self)
  760. # set dialog min size
  761. self.SetMinSize(self.GetSize())
  762. def _createDialogBody(self):
  763. bodySizer = wx.GridBagSizer(vgap = 3, hgap = 3)
  764. bodySizer.AddGrowableCol(1)
  765. bodySizer.AddGrowableRow(3)
  766. # layer type
  767. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Map layer type:")),
  768. flag = wx.ALIGN_CENTER_VERTICAL,
  769. pos = (0,0))
  770. self.layerType = wx.Choice(parent = self, id = wx.ID_ANY,
  771. choices = ['raster', 'vector'], size = (100,-1))
  772. self.layerType.SetSelection(0)
  773. bodySizer.Add(item = self.layerType,
  774. pos = (0,1))
  775. # select toggle
  776. self.toggle = wx.CheckBox(parent = self, id = wx.ID_ANY,
  777. label = _("Select toggle"))
  778. self.toggle.SetValue(True)
  779. bodySizer.Add(item = self.toggle,
  780. flag = wx.ALIGN_CENTER_VERTICAL,
  781. pos = (0,2))
  782. # mapset filter
  783. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Mapset:")),
  784. flag = wx.ALIGN_CENTER_VERTICAL,
  785. pos = (1,0))
  786. self.mapset = gselect.MapsetSelect(parent = self, searchPath = True)
  787. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  788. bodySizer.Add(item = self.mapset,
  789. pos = (1,1), span = (1, 2))
  790. # map name filter
  791. bodySizer.Add(item = wx.StaticText(parent = self, label = _("Filter:")),
  792. flag = wx.ALIGN_CENTER_VERTICAL,
  793. pos = (2,0))
  794. self.filter = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  795. value = "",
  796. size = (250,-1))
  797. bodySizer.Add(item = self.filter,
  798. flag = wx.EXPAND,
  799. pos = (2,1), span = (1, 2))
  800. # layer list
  801. bodySizer.Add(item = wx.StaticText(parent = self, label = _("List of maps:")),
  802. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  803. pos = (3,0))
  804. self.layers = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  805. size = (250, 100),
  806. choices = [])
  807. bodySizer.Add(item = self.layers,
  808. flag = wx.EXPAND,
  809. pos = (3,1), span = (1, 2))
  810. # bindings
  811. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  812. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  813. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  814. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  815. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  816. return bodySizer
  817. def LoadMapLayers(self, type, mapset):
  818. """!Load list of map layers
  819. @param type layer type ('raster' or 'vector')
  820. @param mapset mapset name
  821. """
  822. self.map_layers = grass.mlist_grouped(type = type)[mapset]
  823. self.layers.Set(self.map_layers)
  824. # check all items by default
  825. for item in range(self.layers.GetCount()):
  826. self.layers.Check(item)
  827. def OnChangeParams(self, event):
  828. """!Filter parameters changed by user"""
  829. # update list of layer to be loaded
  830. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  831. self.mapset.GetStringSelection())
  832. event.Skip()
  833. def OnMenu(self, event):
  834. """!Table description area, context menu"""
  835. if not hasattr(self, "popupID1"):
  836. self.popupDataID1 = wx.NewId()
  837. self.popupDataID2 = wx.NewId()
  838. self.popupDataID3 = wx.NewId()
  839. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  840. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id = self.popupDataID2)
  841. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id = self.popupDataID3)
  842. # generate popup-menu
  843. menu = wx.Menu()
  844. menu.Append(self.popupDataID1, _("Select all"))
  845. menu.Append(self.popupDataID2, _("Invert selection"))
  846. menu.Append(self.popupDataID3, _("Deselect all"))
  847. self.PopupMenu(menu)
  848. menu.Destroy()
  849. def OnSelectAll(self, event):
  850. """!Select all map layer from list"""
  851. for item in range(self.layers.GetCount()):
  852. self.layers.Check(item, True)
  853. def OnSelectInvert(self, event):
  854. """!Invert current selection"""
  855. for item in range(self.layers.GetCount()):
  856. if self.layers.IsChecked(item):
  857. self.layers.Check(item, False)
  858. else:
  859. self.layers.Check(item, True)
  860. def OnDeselectAll(self, event):
  861. """!Select all map layer from list"""
  862. for item in range(self.layers.GetCount()):
  863. self.layers.Check(item, False)
  864. def OnFilter(self, event):
  865. """!Apply filter for map names"""
  866. if len(event.GetString()) == 0:
  867. self.layers.Set(self.map_layers)
  868. return
  869. list = []
  870. for layer in self.map_layers:
  871. try:
  872. if re.compile('^' + event.GetString()).search(layer):
  873. list.append(layer)
  874. except:
  875. pass
  876. self.layers.Set(list)
  877. self.OnSelectAll(None)
  878. event.Skip()
  879. def OnToggle(self, event):
  880. """!Select toggle (check or uncheck all layers)"""
  881. check = event.Checked()
  882. for item in range(self.layers.GetCount()):
  883. self.layers.Check(item, check)
  884. event.Skip()
  885. def GetMapLayers(self):
  886. """!Return list of checked map layers"""
  887. layerNames = []
  888. for indx in self.layers.GetSelections():
  889. # layers.append(self.layers.GetStringSelec(indx))
  890. pass
  891. fullyQualified = self.fullyQualified.IsChecked()
  892. mapset = self.mapset.GetStringSelection()
  893. for item in range(self.layers.GetCount()):
  894. if not self.layers.IsChecked(item):
  895. continue
  896. if fullyQualified:
  897. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  898. else:
  899. layerNames.append(self.layers.GetString(item))
  900. return layerNames
  901. def GetLayerType(self):
  902. """!Get selected layer type"""
  903. return self.layerType.GetStringSelection()
  904. class ImportDialog(wx.Dialog):
  905. """!Dialog for bulk import of various data (base class)"""
  906. def __init__(self, parent, itype,
  907. id = wx.ID_ANY, title = _("Multiple import"),
  908. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  909. self.parent = parent # GMFrame
  910. self.importType = itype
  911. self.options = dict() # list of options
  912. self.commandId = -1 # id of running command
  913. wx.Dialog.__init__(self, parent, id, title, style = style,
  914. name = "MultiImportDialog")
  915. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  916. self.layerBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  917. label = _(" List of %s layers ") % self.importType.upper())
  918. #
  919. # list of layers
  920. #
  921. columns = [_('Layer id'),
  922. _('Layer name'),
  923. _('Name for GRASS map (editable)')]
  924. if itype == 'ogr':
  925. columns.insert(2, _('Feature type'))
  926. self.list = LayersList(parent = self.panel, columns = columns)
  927. self.list.LoadData()
  928. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  929. label = "%s" % _("Options"))
  930. cmd = self._getCommand()
  931. task = gtask.parse_interface(cmd)
  932. for f in task.get_options()['flags']:
  933. name = f.get('name', '')
  934. desc = f.get('label', '')
  935. if not desc:
  936. desc = f.get('description', '')
  937. if not name and not desc:
  938. continue
  939. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  940. continue
  941. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  942. continue
  943. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  944. continue
  945. elif cmd == 'v.external' and name not in ('b'):
  946. continue
  947. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  948. continue
  949. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  950. label = desc)
  951. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  952. label = _("Allow output files to overwrite existing files"))
  953. self.overwrite.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  954. self.add = wx.CheckBox(parent = self.panel, id = wx.ID_ANY)
  955. #
  956. # buttons
  957. #
  958. # cancel
  959. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  960. self.btn_cancel.SetToolTipString(_("Close dialog"))
  961. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  962. # run
  963. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Import"))
  964. self.btn_run.SetToolTipString(_("Import selected layers"))
  965. self.btn_run.SetDefault()
  966. self.btn_run.Enable(False)
  967. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  968. # run command dialog
  969. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  970. label = _("Command dialog"))
  971. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  972. def doLayout(self):
  973. """!Do layout"""
  974. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  975. # dsn input
  976. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  977. flag = wx.EXPAND)
  978. #
  979. # list of DXF layers
  980. #
  981. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  982. layerSizer.Add(item = self.list, proportion = 1,
  983. flag = wx.ALL | wx.EXPAND, border = 5)
  984. dialogSizer.Add(item = layerSizer, proportion = 1,
  985. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  986. # options
  987. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  988. for key in self.options.keys():
  989. optionSizer.Add(item = self.options[key], proportion = 0)
  990. dialogSizer.Add(item = optionSizer, proportion = 0,
  991. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
  992. dialogSizer.Add(item = self.overwrite, proportion = 0,
  993. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  994. dialogSizer.Add(item = self.add, proportion = 0,
  995. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  996. #
  997. # buttons
  998. #
  999. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1000. btnsizer.Add(item = self.btn_cmd, proportion = 0,
  1001. flag = wx.ALL | wx.ALIGN_CENTER,
  1002. border = 10)
  1003. btnsizer.Add(item = self.btn_run, proportion = 0,
  1004. flag = wx.ALL | wx.ALIGN_CENTER,
  1005. border = 10)
  1006. btnsizer.Add(item = self.btn_cancel, proportion = 0,
  1007. flag = wx.ALL | wx.ALIGN_CENTER,
  1008. border = 10)
  1009. dialogSizer.Add(item = btnsizer, proportion = 0,
  1010. flag = wx.ALIGN_CENTER)
  1011. # dialogSizer.SetSizeHints(self.panel)
  1012. self.panel.SetAutoLayout(True)
  1013. self.panel.SetSizer(dialogSizer)
  1014. dialogSizer.Fit(self.panel)
  1015. # auto-layout seems not work here - FIXME
  1016. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  1017. self.SetMinSize(size)
  1018. self.SetSize((size.width, size.height + 100))
  1019. # width = self.GetSize()[0]
  1020. # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
  1021. self.Layout()
  1022. def _getCommand(self):
  1023. """!Get command"""
  1024. return ''
  1025. def OnCancel(self, event = None):
  1026. """!Close dialog"""
  1027. self.Close()
  1028. def OnRun(self, event):
  1029. """!Import/Link data (each layes as separate vector map)"""
  1030. pass
  1031. def OnCmdDialog(self, event):
  1032. """!Show command dialog"""
  1033. pass
  1034. def AddLayers(self, returncode, cmd = None):
  1035. """!Add imported/linked layers into layer tree"""
  1036. self.commandId += 1
  1037. if not self.add.IsChecked() or returncode != 0:
  1038. return
  1039. maptree = self.parent.curr_page.maptree
  1040. layer, output = self.list.GetLayers()[self.commandId]
  1041. if '@' not in output:
  1042. name = output + '@' + grass.gisenv()['MAPSET']
  1043. else:
  1044. name = output
  1045. # add imported layers into layer tree
  1046. if self.importType == 'gdal':
  1047. cmd = ['d.rast',
  1048. 'map=%s' % name]
  1049. if UserSettings.Get(group = 'cmd', key = 'rasterOverlay', subkey = 'enabled'):
  1050. cmd.append('-o')
  1051. item = maptree.AddLayer(ltype = 'raster',
  1052. lname = name, lchecked = False,
  1053. lcmd = cmd)
  1054. else:
  1055. item = maptree.AddLayer(ltype = 'vector',
  1056. lname = name, lchecked = False,
  1057. lcmd = ['d.vect',
  1058. 'map=%s' % name])
  1059. maptree.mapdisplay.MapWindow.ZoomToMap()
  1060. def OnAbort(self, event):
  1061. """!Abort running import
  1062. @todo not yet implemented
  1063. """
  1064. pass
  1065. class GdalImportDialog(ImportDialog):
  1066. def __init__(self, parent, ogr = False, link = False):
  1067. """!Dialog for bulk import of various raster/vector data
  1068. @param parent parent window
  1069. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1070. @param link True for linking data otherwise importing data
  1071. """
  1072. self.link = link
  1073. self.ogr = ogr
  1074. if ogr:
  1075. ImportDialog.__init__(self, parent, itype = 'ogr')
  1076. if link:
  1077. self.SetTitle(_("Link external vector data"))
  1078. else:
  1079. self.SetTitle(_("Import vector data"))
  1080. else:
  1081. ImportDialog.__init__(self, parent, itype = 'gdal')
  1082. if link:
  1083. self.SetTitle(_("Link external raster data"))
  1084. else:
  1085. self.SetTitle(_("Import raster data"))
  1086. self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel, ogr = ogr)
  1087. if link:
  1088. self.add.SetLabel(_("Add linked layers into layer tree"))
  1089. else:
  1090. self.add.SetLabel(_("Add imported layers into layer tree"))
  1091. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1092. if link:
  1093. self.btn_run.SetLabel(_("&Link"))
  1094. self.btn_run.SetToolTipString(_("Link selected layers"))
  1095. if ogr:
  1096. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.external')
  1097. else:
  1098. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.external')
  1099. else:
  1100. self.btn_run.SetLabel(_("&Import"))
  1101. self.btn_run.SetToolTipString(_("Import selected layers"))
  1102. if ogr:
  1103. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.in.ogr')
  1104. else:
  1105. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.in.gdal')
  1106. self.doLayout()
  1107. def OnRun(self, event):
  1108. """!Import/Link data (each layes as separate vector map)"""
  1109. data = self.list.GetLayers()
  1110. # hide dialog
  1111. self.Hide()
  1112. dsn = self.dsnInput.GetDsn()
  1113. ext = self.dsnInput.GetFormatExt()
  1114. for layer, output in data:
  1115. if self.importType == 'ogr':
  1116. if ext and layer.rfind(ext) > -1:
  1117. layer = layer.replace('.' + ext, '')
  1118. if self.link:
  1119. cmd = ['v.external',
  1120. 'dsn=%s' % dsn,
  1121. 'output=%s' % output,
  1122. 'layer=%s' % layer]
  1123. else:
  1124. cmd = ['v.in.ogr',
  1125. 'dsn=%s' % dsn,
  1126. 'layer=%s' % layer,
  1127. 'output=%s' % output]
  1128. else: # gdal
  1129. if self.dsnInput.GetType() == 'dir':
  1130. idsn = os.path.join(dsn, layer)
  1131. else:
  1132. idsn = dsn
  1133. if self.link:
  1134. cmd = ['r.external',
  1135. 'input=%s' % idsn,
  1136. 'output=%s' % output]
  1137. else:
  1138. cmd = ['r.in.gdal',
  1139. 'input=%s' % idsn,
  1140. 'output=%s' % output]
  1141. if self.overwrite.IsChecked():
  1142. cmd.append('--overwrite')
  1143. for key in self.options.keys():
  1144. if self.options[key].IsChecked():
  1145. cmd.append('-%s' % key)
  1146. if UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1147. cmd.append('--overwrite')
  1148. # run in Layer Manager
  1149. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1150. onDone = self.AddLayers)
  1151. self.OnCancel()
  1152. def _getCommand(self):
  1153. """!Get command"""
  1154. if self.link:
  1155. if self.ogr:
  1156. return 'v.external'
  1157. else:
  1158. return 'r.external'
  1159. else:
  1160. if self.ogr:
  1161. return 'v.in.ogr'
  1162. else:
  1163. return 'r.in.gdal'
  1164. return ''
  1165. def OnCmdDialog(self, event):
  1166. """!Show command dialog"""
  1167. name = self._getCommand()
  1168. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = [name])
  1169. class GdalOutputDialog(wx.Dialog):
  1170. def __init__(self, parent, id = wx.ID_ANY, ogr = False,
  1171. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, *kwargs):
  1172. """!Dialog for setting output format for rasters/vectors
  1173. @param parent parent window
  1174. @param id window id
  1175. @param ogr True for OGR (vector) otherwise GDAL (raster)
  1176. @param style window style
  1177. @param *kwargs other wx.Dialog's arguments
  1178. """
  1179. self.parent = parent # GMFrame
  1180. self.ogr = ogr
  1181. wx.Dialog.__init__(self, parent, id = id, style = style, *kwargs)
  1182. if self.ogr:
  1183. self.SetTitle(_("Define output format for vector data"))
  1184. else:
  1185. self.SetTitle(_("Define output format for raster data"))
  1186. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1187. # buttons
  1188. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1189. self.btnCancel.SetToolTipString(_("Close dialog"))
  1190. self.btnOk = wx.Button(parent = self.panel, id = wx.ID_OK)
  1191. self.btnOk.SetToolTipString(_("Set external format and close dialog"))
  1192. self.btnOk.SetDefault()
  1193. self.btnOk.Enable(False)
  1194. self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel,
  1195. ogr = ogr,
  1196. exclude = ['file', 'protocol'], dest = True)
  1197. self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel)
  1198. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOk)
  1199. self._layout()
  1200. def _layout(self):
  1201. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  1202. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  1203. flag = wx.EXPAND)
  1204. btnSizer = wx.StdDialogButtonSizer()
  1205. btnSizer.AddButton(self.btnOk)
  1206. btnSizer.AddButton(self.btnCancel)
  1207. btnSizer.Realize()
  1208. dialogSizer.Add(item = btnSizer, proportion = 0,
  1209. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  1210. border = 5)
  1211. self.panel.SetAutoLayout(True)
  1212. self.panel.SetSizer(dialogSizer)
  1213. dialogSizer.Fit(self.panel)
  1214. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, self.GetBestSize()[1])
  1215. self.SetMinSize(size)
  1216. self.SetSize((size.width, size.height))
  1217. self.Layout()
  1218. def OnCancel(self, event):
  1219. self.Destroy()
  1220. def OnOK(self, event):
  1221. if self.dsnInput.GetType() == 'native':
  1222. gcmd.RunCommand('v.external.out',
  1223. parent = self,
  1224. flags = 'r')
  1225. else:
  1226. dsn = self.dsnInput.GetDsn()
  1227. frmt = self.dsnInput.GetFormat()
  1228. options = self.dsnInput.GetOptions()
  1229. gcmd.RunCommand('v.external.out',
  1230. parent = self,
  1231. dsn = dsn, format = frmt,
  1232. options = options)
  1233. self.Close()
  1234. class DxfImportDialog(ImportDialog):
  1235. """!Dialog for bulk import of DXF layers"""
  1236. def __init__(self, parent):
  1237. ImportDialog.__init__(self, parent, itype = 'dxf',
  1238. title = _("Import DXF layers"))
  1239. self.dsnInput = filebrowse.FileBrowseButton(parent = self.panel, id = wx.ID_ANY,
  1240. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1241. dialogTitle = _('Choose DXF file to import'),
  1242. buttonText = _('Browse'),
  1243. startDirectory = os.getcwd(), fileMode = 0,
  1244. changeCallback = self.OnSetDsn,
  1245. fileMask = "DXF File (*.dxf)|*.dxf")
  1246. self.add.SetLabel(_("Add imported layers into layer tree"))
  1247. self.add.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  1248. self.doLayout()
  1249. def _getCommand(self):
  1250. """!Get command"""
  1251. return 'v.in.dxf'
  1252. def OnRun(self, event):
  1253. """!Import/Link data (each layes as separate vector map)"""
  1254. data = self.list.GetLayers()
  1255. # hide dialog
  1256. self.Hide()
  1257. inputDxf = self.dsnInput.GetValue()
  1258. for layer, output in data:
  1259. cmd = ['v.in.dxf',
  1260. 'input=%s' % inputDxf,
  1261. 'layers=%s' % layer,
  1262. 'output=%s' % output]
  1263. for key in self.options.keys():
  1264. if self.options[key].IsChecked():
  1265. cmd.append('-%s' % key)
  1266. if self.overwrite.IsChecked() or \
  1267. UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'):
  1268. cmd.append('--overwrite')
  1269. # run in Layer Manager
  1270. self.parent.goutput.RunCmd(cmd, switchPage = True,
  1271. onDone = self.AddLayers)
  1272. self.OnCancel()
  1273. def OnSetDsn(self, event):
  1274. """!Input DXF file defined, update list of layer widget"""
  1275. path = event.GetString()
  1276. if not path:
  1277. return
  1278. data = list()
  1279. ret = gcmd.RunCommand('v.in.dxf',
  1280. quiet = True,
  1281. parent = self,
  1282. read = True,
  1283. flags = 'l',
  1284. input = path)
  1285. if not ret:
  1286. self.list.LoadData()
  1287. self.btn_run.Enable(False)
  1288. return
  1289. for line in ret.splitlines():
  1290. layerId = line.split(':')[0].split(' ')[1]
  1291. layerName = line.split(':')[1].strip()
  1292. grassName = utils.GetValidLayerName(layerName)
  1293. data.append((layerId, layerName.strip(), grassName.strip()))
  1294. self.list.LoadData(data)
  1295. if len(data) > 0:
  1296. self.btn_run.Enable(True)
  1297. else:
  1298. self.btn_run.Enable(False)
  1299. def OnCmdDialog(self, event):
  1300. """!Show command dialog"""
  1301. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = ['v.in.dxf'])
  1302. class LayersList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin,
  1303. listmix.CheckListCtrlMixin, listmix.TextEditMixin):
  1304. """!List of layers to be imported (dxf, shp...)"""
  1305. def __init__(self, parent, columns, log = None):
  1306. self.parent = parent
  1307. wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
  1308. style = wx.LC_REPORT)
  1309. listmix.CheckListCtrlMixin.__init__(self)
  1310. self.log = log
  1311. # setup mixins
  1312. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1313. listmix.TextEditMixin.__init__(self)
  1314. for i in range(len(columns)):
  1315. self.InsertColumn(i, columns[i])
  1316. if len(columns) == 3:
  1317. width = (65, 200)
  1318. else:
  1319. width = (65, 200, 90)
  1320. for i in range(len(width)):
  1321. self.SetColumnWidth(col = i, width = width[i])
  1322. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
  1323. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
  1324. def LoadData(self, data = None):
  1325. """!Load data into list"""
  1326. if data is None:
  1327. return
  1328. self.DeleteAllItems()
  1329. for item in data:
  1330. index = self.InsertStringItem(sys.maxint, str(item[0]))
  1331. for i in range(1, len(item)):
  1332. self.SetStringItem(index, i, "%s" % str(item[i]))
  1333. # check by default
  1334. ### self.CheckItem(index, True)
  1335. def OnPopupMenu(self, event):
  1336. """!Show popup menu"""
  1337. if self.GetItemCount() < 1:
  1338. return
  1339. if not hasattr(self, "popupDataID1"):
  1340. self.popupDataID1 = wx.NewId()
  1341. self.popupDataID2 = wx.NewId()
  1342. self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
  1343. self.Bind(wx.EVT_MENU, self.OnSelectNone, id = self.popupDataID2)
  1344. # generate popup-menu
  1345. menu = wx.Menu()
  1346. menu.Append(self.popupDataID1, _("Select all"))
  1347. menu.Append(self.popupDataID2, _("Deselect all"))
  1348. self.PopupMenu(menu)
  1349. menu.Destroy()
  1350. def OnSelectAll(self, event):
  1351. """!Select all items"""
  1352. item = -1
  1353. while True:
  1354. item = self.GetNextItem(item)
  1355. if item == -1:
  1356. break
  1357. self.CheckItem(item, True)
  1358. event.Skip()
  1359. def OnSelectNone(self, event):
  1360. """!Deselect items"""
  1361. item = -1
  1362. while True:
  1363. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  1364. if item == -1:
  1365. break
  1366. self.CheckItem(item, False)
  1367. event.Skip()
  1368. def OnLeftDown(self, event):
  1369. """!Allow editing only output name
  1370. Code taken from TextEditMixin class.
  1371. """
  1372. x, y = event.GetPosition()
  1373. colLocs = [0]
  1374. loc = 0
  1375. for n in range(self.GetColumnCount()):
  1376. loc = loc + self.GetColumnWidth(n)
  1377. colLocs.append(loc)
  1378. col = bisect(colLocs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
  1379. if col == self.GetColumnCount() - 1:
  1380. listmix.TextEditMixin.OnLeftDown(self, event)
  1381. else:
  1382. event.Skip()
  1383. def GetLayers(self):
  1384. """!Get list of layers (layer name, output name)"""
  1385. data = []
  1386. item = -1
  1387. while True:
  1388. item = self.GetNextItem(item)
  1389. if item == -1:
  1390. break
  1391. if not self.IsChecked(item):
  1392. continue
  1393. # layer / output name
  1394. data.append((self.GetItem(item, 1).GetText(),
  1395. self.GetItem(item, self.GetColumnCount() - 1).GetText()))
  1396. return data
  1397. class SetOpacityDialog(wx.Dialog):
  1398. """!Set opacity of map layers"""
  1399. def __init__(self, parent, id = wx.ID_ANY, title = _("Set Map Layer Opacity"),
  1400. size = wx.DefaultSize, pos = wx.DefaultPosition,
  1401. style = wx.DEFAULT_DIALOG_STYLE, opacity = 100):
  1402. self.parent = parent # GMFrame
  1403. self.opacity = opacity # current opacity
  1404. super(SetOpacityDialog, self).__init__(parent, id = id, pos = pos,
  1405. size = size, style = style, title = title)
  1406. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1407. sizer = wx.BoxSizer(wx.VERTICAL)
  1408. box = wx.GridBagSizer(vgap = 5, hgap = 5)
  1409. self.value = wx.Slider(panel, id = wx.ID_ANY, value = self.opacity,
  1410. style = wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1411. wx.SL_TOP | wx.SL_LABELS,
  1412. minValue = 0, maxValue = 100,
  1413. size = (350, -1))
  1414. box.Add(item = self.value,
  1415. flag = wx.ALIGN_CENTRE, pos = (0, 0), span = (1, 2))
  1416. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1417. label = _("transparent")),
  1418. pos = (1, 0))
  1419. box.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
  1420. label = _("opaque")),
  1421. flag = wx.ALIGN_RIGHT,
  1422. pos = (1, 1))
  1423. sizer.Add(item = box, proportion = 0,
  1424. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1425. line = wx.StaticLine(parent = panel, id = wx.ID_ANY,
  1426. style = wx.LI_HORIZONTAL)
  1427. sizer.Add(item = line, proportion = 0,
  1428. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1429. # buttons
  1430. btnsizer = wx.StdDialogButtonSizer()
  1431. btnOK = wx.Button(parent = panel, id = wx.ID_OK)
  1432. btnOK.SetDefault()
  1433. btnsizer.AddButton(btnOK)
  1434. btnCancel = wx.Button(parent = panel, id = wx.ID_CANCEL)
  1435. btnsizer.AddButton(btnCancel)
  1436. btnsizer.Realize()
  1437. sizer.Add(item = btnsizer, proportion = 0,
  1438. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
  1439. panel.SetSizer(sizer)
  1440. sizer.Fit(panel)
  1441. self.SetSize(self.GetBestSize())
  1442. self.Layout()
  1443. def GetOpacity(self):
  1444. """!Button 'OK' pressed"""
  1445. # return opacity value
  1446. opacity = float(self.value.GetValue()) / 100
  1447. return opacity
  1448. def GetImageHandlers(image):
  1449. """!Get list of supported image handlers"""
  1450. lext = list()
  1451. ltype = list()
  1452. for h in image.GetHandlers():
  1453. lext.append(h.GetExtension())
  1454. filetype = ''
  1455. if 'png' in lext:
  1456. filetype += "PNG file (*.png)|*.png|"
  1457. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1458. 'ext' : 'png' })
  1459. filetype += "BMP file (*.bmp)|*.bmp|"
  1460. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1461. 'ext' : 'bmp' })
  1462. if 'gif' in lext:
  1463. filetype += "GIF file (*.gif)|*.gif|"
  1464. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1465. 'ext' : 'gif' })
  1466. if 'jpg' in lext:
  1467. filetype += "JPG file (*.jpg)|*.jpg|"
  1468. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1469. 'ext' : 'jpg' })
  1470. if 'pcx' in lext:
  1471. filetype += "PCX file (*.pcx)|*.pcx|"
  1472. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1473. 'ext' : 'pcx' })
  1474. if 'pnm' in lext:
  1475. filetype += "PNM file (*.pnm)|*.pnm|"
  1476. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1477. 'ext' : 'pnm' })
  1478. if 'tif' in lext:
  1479. filetype += "TIF file (*.tif)|*.tif|"
  1480. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1481. 'ext' : 'tif' })
  1482. if 'xpm' in lext:
  1483. filetype += "XPM file (*.xpm)|*.xpm"
  1484. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1485. 'ext' : 'xpm' })
  1486. return filetype, ltype
  1487. class StaticWrapText(wx.StaticText):
  1488. """!A Static Text field that wraps its text to fit its width,
  1489. enlarging its height if necessary.
  1490. """
  1491. def __init__(self, parent, id = wx.ID_ANY, label = '', *args, **kwds):
  1492. self.parent = parent
  1493. self.originalLabel = label
  1494. wx.StaticText.__init__(self, parent, id, label = '', *args, **kwds)
  1495. self.SetLabel(label)
  1496. self.Bind(wx.EVT_SIZE, self.OnResize)
  1497. def SetLabel(self, label):
  1498. self.originalLabel = label
  1499. self.wrappedSize = None
  1500. self.OnResize(None)
  1501. def OnResize(self, event):
  1502. if not getattr(self, "resizing", False):
  1503. self.resizing = True
  1504. newSize = wx.Size(self.parent.GetSize().width - 50,
  1505. self.GetSize().height)
  1506. if self.wrappedSize != newSize:
  1507. wx.StaticText.SetLabel(self, self.originalLabel)
  1508. self.Wrap(newSize.width)
  1509. self.wrappedSize = newSize
  1510. self.SetSize(self.wrappedSize)
  1511. del self.resizing
  1512. class ImageSizeDialog(wx.Dialog):
  1513. """!Set size for saved graphic file"""
  1514. def __init__(self, parent, id = wx.ID_ANY, title = _("Set image size"),
  1515. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1516. self.parent = parent
  1517. wx.Dialog.__init__(self, parent, id = id, style = style, title = title, **kwargs)
  1518. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1519. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1520. label = ' % s' % _("Image size"))
  1521. size = self.parent.GetWindow().GetClientSize()
  1522. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1523. style = wx.SP_ARROW_KEYS)
  1524. self.width.SetRange(20, 1e6)
  1525. self.width.SetValue(size.width)
  1526. wx.CallAfter(self.width.SetFocus)
  1527. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1528. style = wx.SP_ARROW_KEYS)
  1529. self.height.SetRange(20, 1e6)
  1530. self.height.SetValue(size.height)
  1531. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1532. size = (125, -1),
  1533. choices = [ "",
  1534. "640x480",
  1535. "800x600",
  1536. "1024x768",
  1537. "1280x960",
  1538. "1600x1200",
  1539. "1920x1440" ])
  1540. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1541. self.btnOK.SetDefault()
  1542. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1543. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1544. self._layout()
  1545. self.SetSize(self.GetBestSize())
  1546. def _layout(self):
  1547. """!Do layout"""
  1548. sizer = wx.BoxSizer(wx.VERTICAL)
  1549. # body
  1550. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1551. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1552. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1553. label = _("Width:")),
  1554. flag = wx.ALIGN_CENTER_VERTICAL)
  1555. fbox.Add(item = self.width)
  1556. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1557. label = _("Height:")),
  1558. flag = wx.ALIGN_CENTER_VERTICAL)
  1559. fbox.Add(item = self.height)
  1560. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1561. label = _("Template:")),
  1562. flag = wx.ALIGN_CENTER_VERTICAL)
  1563. fbox.Add(item = self.template)
  1564. box.Add(item = fbox, proportion = 1,
  1565. flag = wx.EXPAND | wx.ALL, border = 5)
  1566. sizer.Add(item = box, proportion = 1,
  1567. flag=wx.EXPAND | wx.ALL, border = 3)
  1568. # buttons
  1569. btnsizer = wx.StdDialogButtonSizer()
  1570. btnsizer.AddButton(self.btnOK)
  1571. btnsizer.AddButton(self.btnCancel)
  1572. btnsizer.Realize()
  1573. sizer.Add(item = btnsizer, proportion = 0,
  1574. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1575. self.panel.SetSizer(sizer)
  1576. sizer.Fit(self.panel)
  1577. self.Layout()
  1578. def GetValues(self):
  1579. """!Get width/height values"""
  1580. return self.width.GetValue(), self.height.GetValue()
  1581. def OnTemplate(self, event):
  1582. """!Template selected"""
  1583. sel = event.GetString()
  1584. if not sel:
  1585. width, height = self.parent.GetWindow().GetClientSize()
  1586. else:
  1587. width, height = map(int, sel.split('x'))
  1588. self.width.SetValue(width)
  1589. self.height.SetValue(height)
  1590. class SqlQueryFrame(wx.Frame):
  1591. def __init__(self, parent, id = wx.ID_ANY,
  1592. title = _("GRASS GIS SQL Query Utility"),
  1593. *kwargs):
  1594. """!SQL Query Utility window
  1595. """
  1596. self.parent = parent
  1597. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1598. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1599. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1600. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1601. label = _(" SQL statement "))
  1602. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1603. style = wx.TE_MULTILINE)
  1604. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1605. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1606. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1607. self._layout()
  1608. self.SetMinSize(wx.Size(300, 150))
  1609. self.SetSize(wx.Size(500, 200))
  1610. def _layout(self):
  1611. """!Do layout"""
  1612. sizer = wx.BoxSizer(wx.VERTICAL)
  1613. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1614. sqlSizer.Add(item = self.sql, proportion = 1,
  1615. flag = wx.EXPAND)
  1616. btnSizer = wx.StdDialogButtonSizer()
  1617. btnSizer.AddButton(self.btnApply)
  1618. btnSizer.AddButton(self.btnCancel)
  1619. btnSizer.Realize()
  1620. sizer.Add(item = sqlSizer, proportion = 1,
  1621. flag = wx.EXPAND | wx.ALL, border = 5)
  1622. sizer.Add(item = btnSizer, proportion = 0,
  1623. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1624. self.panel.SetSizer(sizer)
  1625. self.Layout()
  1626. def OnCloseWindow(self, event):
  1627. """!Close window
  1628. """
  1629. self.Close()