forms.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  12. This program is just a coarse approach to automatically build a GUI
  13. from a xml-based GRASS user interface description.
  14. You need to have Python 2.4, wxPython 2.8 and python-xml.
  15. The XML stream is read from executing the command given in the
  16. command line, thus you may call it for instance this way:
  17. python <this file.py> r.basins.fill
  18. Or you set an alias or wrap the call up in a nice shell script, GUI
  19. environment ... please contribute your idea.
  20. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  21. make it callable by gui. Method added to automatically re-run with
  22. pythonw on a Mac.
  23. @todo
  24. - verify option value types
  25. Copyright(C) 2000-2013 by the GRASS Development Team
  26. This program is free software under the GPL(>=v2) Read the file
  27. COPYING coming with GRASS for details.
  28. @author Jan-Oliver Wagner <jan@intevation.de>
  29. @author Bernhard Reiter <bernhard@intevation.de>
  30. @author Michael Barton, Arizona State University
  31. @author Daniel Calvelo <dca.gis@gmail.com>
  32. @author Martin Landa <landa.martin@gmail.com>
  33. @author Luca Delucchi <lucadeluge@gmail.com>
  34. @author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
  35. """
  36. import sys
  37. import string
  38. import textwrap
  39. import os
  40. import copy
  41. import locale
  42. import Queue
  43. import re
  44. import codecs
  45. from threading import Thread
  46. gisbase = os.getenv("GISBASE")
  47. if gisbase is None:
  48. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  49. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  50. wxbase = gisbase
  51. else:
  52. wxbase = os.path.join(gisbase, 'etc', 'gui', 'wxpython')
  53. sys.path.append(wxbase)
  54. from core import globalvar
  55. import wx
  56. try:
  57. import wx.lib.agw.flatnotebook as FN
  58. except ImportError:
  59. import wx.lib.flatnotebook as FN
  60. import wx.lib.colourselect as csel
  61. import wx.lib.filebrowsebutton as filebrowse
  62. from wx.lib.newevent import NewEvent
  63. try:
  64. import xml.etree.ElementTree as etree
  65. except ImportError:
  66. import elementtree.ElementTree as etree # Python <= 2.4
  67. from grass.pydispatch.signal import Signal
  68. from grass.script import core as grass
  69. from grass.script import task as gtask
  70. from gui_core.widgets import StaticWrapText, ScrolledPanel
  71. from gui_core.ghelp import HelpPanel
  72. from gui_core import gselect
  73. from core import gcmd
  74. from core import utils
  75. from core.settings import UserSettings
  76. from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
  77. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  78. """!Hide some options in the GUI"""
  79. #_blackList = { 'enabled' : False,
  80. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  81. # 'flags' : ['z', 'overwrite']}}}
  82. _blackList = { 'enabled' : False,
  83. 'items' : {} }
  84. def text_beautify(someString , width = 70):
  85. """!Make really long texts shorter, clean up whitespace and remove
  86. trailing punctuation.
  87. """
  88. if width > 0:
  89. return escape_ampersand(string.strip(
  90. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  91. ".,;:"))
  92. else:
  93. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  94. def escape_ampersand(text):
  95. """!Escapes ampersands with additional ampersand for GUI"""
  96. return string.replace(text, "&", "&&")
  97. class UpdateThread(Thread):
  98. """!Update dialog widgets in the thread"""
  99. def __init__(self, parent, event, eventId, task):
  100. Thread.__init__(self)
  101. self.parent = parent
  102. self.event = event
  103. self.eventId = eventId
  104. self.task = task
  105. self.setDaemon(True)
  106. # list of functions which updates the dialog
  107. self.data = {}
  108. def run(self):
  109. # get widget id
  110. if not self.eventId:
  111. for p in self.task.params:
  112. if p.get('gisprompt', False) == False:
  113. continue
  114. prompt = p.get('element', '')
  115. if prompt == 'vector':
  116. name = p.get('name', '')
  117. if name in ('map', 'input'):
  118. self.eventId = p['wxId'][0]
  119. if self.eventId is None:
  120. return
  121. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  122. if not p or 'wxId-bind' not in p:
  123. return
  124. # is this check necessary?
  125. # get widget prompt
  126. # pType = p.get('prompt', '')
  127. # if not pType:
  128. # return
  129. # check for map/input parameter
  130. pMap = self.task.get_param('map', raiseError = False)
  131. if not pMap:
  132. pMap = self.task.get_param('input', raiseError = False)
  133. if pMap:
  134. map = pMap.get('value', '')
  135. else:
  136. map = None
  137. # avoid running db.describe several times
  138. cparams = dict()
  139. cparams[map] = { 'dbInfo' : None,
  140. 'layers' : None, }
  141. # update reference widgets
  142. for uid in p['wxId-bind']:
  143. win = self.parent.FindWindowById(uid)
  144. if not win:
  145. continue
  146. name = win.GetName()
  147. pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
  148. if pBind:
  149. pBind['value'] = ''
  150. # set appropriate types in t.* modules element selections
  151. if name == 'Select':
  152. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  153. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  154. self.data[win.GetParent().SetType] = {'etype': type_param.get('value')}
  155. # t.(un)register has one type for 'input', 'maps'
  156. if maps_param is not None:
  157. if maps_param['wxId'][0] != uid:
  158. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  159. self.data[win.GetParent().SetType] = {'etype': element_dict[type_param.get('value')]}
  160. map = layer = None
  161. driver = db = None
  162. if name in ('LayerSelect', 'ColumnSelect'):
  163. if p.get('element', '') == 'vector': # -> vector
  164. # get map name
  165. map = p.get('value', '')
  166. # get layer
  167. for bid in p['wxId-bind']:
  168. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  169. if not p:
  170. continue
  171. if p.get('element', '') == 'layer':
  172. layer = p.get('value', '')
  173. if layer != '':
  174. layer = p.get('value', '')
  175. else:
  176. layer = p.get('default', '')
  177. break
  178. elif p.get('element', '') == 'layer': # -> layer
  179. # get layer
  180. layer = p.get('value', '')
  181. if layer != '':
  182. layer = p.get('value', '')
  183. else:
  184. layer = p.get('default', '')
  185. # get map name
  186. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  187. if pMapL:
  188. map = pMapL.get('value', '')
  189. if name == 'TableSelect' or \
  190. (name == 'ColumnSelect' and not map):
  191. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  192. if pDriver:
  193. driver = pDriver.get('value', '')
  194. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  195. if pDb:
  196. db = pDb.get('value', '')
  197. if name == 'ColumnSelect':
  198. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  199. if pTable:
  200. table = pTable.get('value', '')
  201. if name == 'LayerSelect':
  202. # determine format
  203. native = True
  204. for id in pMap['wxId']:
  205. winVec = self.parent.FindWindowById(id)
  206. if winVec.GetName() == 'VectorFormat' and \
  207. winVec.GetSelection() != 0:
  208. native = False
  209. break
  210. # TODO: update only if needed
  211. if native:
  212. if map:
  213. self.data[win.InsertLayers] = { 'vector' : map }
  214. else:
  215. self.data[win.InsertLayers] = { }
  216. else:
  217. if map:
  218. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  219. else:
  220. self.data[win.InsertLayers] = { }
  221. elif name == 'TableSelect':
  222. self.data[win.InsertTables] = { 'driver' : driver,
  223. 'database' : db }
  224. elif name == 'ColumnSelect':
  225. if map:
  226. if map in cparams:
  227. if not cparams[map]['dbInfo']:
  228. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  229. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  230. 'dbInfo' : cparams[map]['dbInfo'] }
  231. else: # table
  232. if driver and db:
  233. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  234. 'driver' : driver,
  235. 'database' : db }
  236. elif pTable:
  237. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  238. elif name == 'SubGroupSelect':
  239. self.data[win.Insert] = { 'group' : p.get('value', '')}
  240. elif name == 'SignatureSelect':
  241. if p.get('prompt', 'group') == 'group':
  242. group = p.get('value', '')
  243. pSubGroup = self.task.get_param('subgroup', element = 'prompt', raiseError = False)
  244. if pSubGroup:
  245. subgroup = pSubGroup.get('value', '')
  246. else:
  247. subgroup = None
  248. else:
  249. subgroup = p.get('value', '')
  250. pGroup = self.task.get_param('group', element = 'prompt', raiseError = False)
  251. if pGroup:
  252. group = pGroup.get('value', '')
  253. else:
  254. group = None
  255. self.data[win.Insert] = { 'group' : group,
  256. 'subgroup' : subgroup}
  257. elif name == 'LocationSelect':
  258. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  259. if pDbase:
  260. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  261. elif name == 'MapsetSelect':
  262. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  263. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  264. if pDbase and pLocation:
  265. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  266. 'location' : pLocation.get('value', '')}
  267. elif name == 'ProjSelect':
  268. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  269. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  270. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  271. if pDbase and pLocation and pMapset:
  272. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  273. 'location' : pLocation.get('value', ''),
  274. 'mapset' : pMapset.get('value', '')}
  275. def UpdateDialog(parent, event, eventId, task):
  276. return UpdateThread(parent, event, eventId, task)
  277. class UpdateQThread(Thread):
  278. """!Update dialog widgets in the thread"""
  279. requestId = 0
  280. def __init__(self, parent, requestQ, resultQ, **kwds):
  281. Thread.__init__(self, **kwds)
  282. self.parent = parent # cmdPanel
  283. self.setDaemon(True)
  284. self.requestQ = requestQ
  285. self.resultQ = resultQ
  286. self.start()
  287. def Update(self, callable, *args, **kwds):
  288. UpdateQThread.requestId += 1
  289. self.request = None
  290. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  291. return UpdateQThread.requestId
  292. def run(self):
  293. while True:
  294. requestId, callable, args, kwds = self.requestQ.get()
  295. self.request = callable(*args, **kwds)
  296. self.resultQ.put((requestId, self.request.run()))
  297. if self.request:
  298. event = wxUpdateDialog(data = self.request.data)
  299. wx.PostEvent(self.parent, event)
  300. class TaskFrame(wx.Frame):
  301. """!This is the Frame containing the dialog for options input.
  302. The dialog is organized in a notebook according to the guisections
  303. defined by each GRASS command.
  304. If run with a parent, it may Apply, Ok or Cancel; the latter two
  305. close the dialog. The former two trigger a callback.
  306. If run standalone, it will allow execution of the command.
  307. The command is checked and sent to the clipboard when clicking
  308. 'Copy'.
  309. """
  310. def __init__(self, parent, giface, task_description, id = wx.ID_ANY,
  311. get_dcmd = None, layer = None,
  312. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  313. self.get_dcmd = get_dcmd
  314. self.layer = layer
  315. self.task = task_description
  316. self.parent = parent # LayerTree | Modeler | None | ...
  317. self._giface = giface
  318. if parent and parent.GetName() == 'Modeler':
  319. self.modeler = self.parent
  320. else:
  321. self.modeler = None
  322. # module name + keywords
  323. title = self.task.get_name()
  324. try:
  325. if self.task.keywords != ['']:
  326. title += " [" + ', '.join(self.task.keywords) + "]"
  327. except ValueError:
  328. pass
  329. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  330. name = "MainFrame", style = style, **kwargs)
  331. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  332. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  333. # statusbar
  334. self.CreateStatusBar()
  335. # icon
  336. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  337. guisizer = wx.BoxSizer(wx.VERTICAL)
  338. # set apropriate output window
  339. if self.parent:
  340. self.standalone = False
  341. else:
  342. self.standalone = True
  343. # logo + description
  344. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  345. # GRASS logo
  346. self.logo = wx.StaticBitmap(parent = self.panel,
  347. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  348. 'grass_form.png'),
  349. type = wx.BITMAP_TYPE_PNG))
  350. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  351. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  352. # add module description
  353. if self.task.label:
  354. module_desc = self.task.label + ' ' + self.task.description
  355. else:
  356. module_desc = self.task.description
  357. self.description = StaticWrapText(parent = self.panel,
  358. label = module_desc)
  359. topsizer.Add(item = self.description, proportion = 1, border = 5,
  360. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  361. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  362. self.panel.SetSizerAndFit(guisizer)
  363. self.Layout()
  364. # notebooks
  365. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  366. frame = self)
  367. self._gconsole = self.notebookpanel._gconsole
  368. self.goutput = self.notebookpanel.goutput
  369. if self._gconsole:
  370. self._gconsole.mapCreated.connect(self.OnMapCreated)
  371. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  372. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  373. # status bar
  374. status_text = _("Enter parameters for '") + self.task.name + "'"
  375. try:
  376. self.task.get_cmd()
  377. self.updateValuesHook()
  378. except ValueError:
  379. self.SetStatusText(status_text)
  380. # buttons
  381. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  382. # cancel
  383. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  384. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  385. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  386. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  387. if self.get_dcmd is not None: # A callback has been set up
  388. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  389. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  390. btn_ok.SetDefault()
  391. btnsizer.Add(item = btn_apply, proportion = 0,
  392. flag = wx.ALL | wx.ALIGN_CENTER,
  393. border = 10)
  394. btnsizer.Add(item = btn_ok, proportion = 0,
  395. flag = wx.ALL | wx.ALIGN_CENTER,
  396. border = 10)
  397. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  398. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  399. else: # We're standalone
  400. # run
  401. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  402. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  403. self.btn_run.SetDefault()
  404. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  405. # copy
  406. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY)
  407. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  408. btnsizer.Add(item = self.btn_run, proportion = 0,
  409. flag = wx.ALL | wx.ALIGN_CENTER,
  410. border = 10)
  411. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  412. flag = wx.ALL | wx.ALIGN_CENTER,
  413. border = 10)
  414. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  415. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  416. # help
  417. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  418. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  419. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  420. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  421. self.btn_help.Hide()
  422. # add help button
  423. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  424. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  425. border = 30)
  426. if self.parent and not self.modeler:
  427. addLayer = False
  428. for p in self.task.params:
  429. if p.get('age', 'old') == 'new' and \
  430. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  431. addLayer = True
  432. if addLayer:
  433. # add newly created map into layer tree
  434. self.addbox = wx.CheckBox(parent = self.panel,
  435. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  436. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  437. guisizer.Add(item = self.addbox, proportion = 0,
  438. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  439. border = 5)
  440. hasNew = False
  441. for p in self.task.params:
  442. if p.get('age', 'old') == 'new':
  443. hasNew = True
  444. break
  445. if self.get_dcmd is None and hasNew:
  446. # close dialog when command is terminated
  447. self.closebox = wx.CheckBox(parent = self.panel,
  448. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  449. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  450. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  451. "Change this settings in Preferences dialog ('Command' tab)."))
  452. guisizer.Add(item = self.closebox, proportion = 0,
  453. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  454. border = 5)
  455. # bindings
  456. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  457. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  458. # do layout
  459. # called automatically by SetSizer()
  460. self.panel.SetAutoLayout(True)
  461. self.panel.SetSizerAndFit(guisizer)
  462. sizeFrame = self.GetBestSize()
  463. self.SetMinSize(sizeFrame)
  464. if hasattr(self, "closebox"):
  465. scale = 0.33
  466. else:
  467. scale = 0.50
  468. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  469. self.notebookpanel.constrained_size[1])))
  470. # thread to update dialog
  471. # create queues
  472. self.requestQ = Queue.Queue()
  473. self.resultQ = Queue.Queue()
  474. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  475. self.Layout()
  476. # keep initial window size limited for small screens
  477. width, height = self.GetSizeTuple()
  478. self.SetSize(wx.Size(min(width, 650),
  479. min(height, 500)))
  480. # fix goutput's pane size (required for Mac OSX)
  481. if self.goutput:
  482. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  483. def updateValuesHook(self, event = None):
  484. """!Update status bar data"""
  485. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  486. if event:
  487. event.Skip()
  488. def OnKeyUp(self, event):
  489. """!Key released (check hot-keys)"""
  490. try:
  491. kc = chr(event.GetKeyCode())
  492. except ValueError:
  493. event.Skip()
  494. return
  495. if not event.ControlDown():
  496. event.Skip()
  497. return
  498. if kc == 'Q':
  499. self.OnCancel(None)
  500. elif kc == 'S':
  501. self.OnAbort(None)
  502. elif kc == 'H':
  503. self.OnHelp(None)
  504. elif kc == 'R':
  505. self.OnRun(None)
  506. elif kc == 'C':
  507. self.OnCopy(None)
  508. event.Skip()
  509. def OnDone(self, cmd, returncode):
  510. """!This function is launched from OnRun() when command is
  511. finished
  512. @param returncode command's return code (0 for success)
  513. """
  514. if hasattr(self, "btn_cancel"):
  515. self.btn_cancel.Enable(True)
  516. if hasattr(self, "btn_clipboard"):
  517. self.btn_clipboard.Enable(True)
  518. if hasattr(self, "btn_help"):
  519. self.btn_help.Enable(True)
  520. if hasattr(self, "btn_run"):
  521. self.btn_run.Enable(True)
  522. if hasattr(self, "get_dcmd") and \
  523. self.get_dcmd is None and \
  524. hasattr(self, "closebox") and \
  525. self.closebox.IsChecked() and \
  526. (returncode == 0):
  527. # was closed also when aborted but better is leave it open
  528. wx.FutureCall(2000, self.Close)
  529. def OnMapCreated(self, name, ltype):
  530. if hasattr(self, "addbox") and self.addbox.IsChecked():
  531. add = True
  532. else:
  533. add = False
  534. self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
  535. def OnOK(self, event):
  536. """!OK button pressed"""
  537. cmd = self.OnApply(event)
  538. if cmd is not None and self.get_dcmd is not None:
  539. self.OnCancel(event)
  540. def OnApply(self, event):
  541. """!Apply the command"""
  542. if self.modeler:
  543. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  544. else:
  545. cmd = self.createCmd()
  546. if cmd is not None and self.get_dcmd is not None:
  547. # return d.* command to layer tree for rendering
  548. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  549. "flags" : self.task.flags},
  550. self)
  551. # echo d.* command to output console
  552. # self.parent.writeDCommand(cmd)
  553. return cmd
  554. def OnRun(self, event):
  555. """!Run the command"""
  556. cmd = self.createCmd()
  557. if not cmd or len(cmd) < 1:
  558. return
  559. ret = 0
  560. if self.standalone or cmd[0][0:2] != "d.":
  561. # Send any non-display command to parent window (probably wxgui.py)
  562. # put to parents switch to 'Command output'
  563. self.notebookpanel.notebook.SetSelectionByName('output')
  564. try:
  565. if self.task.path:
  566. cmd[0] = self.task.path # full path
  567. ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
  568. except AttributeError, e:
  569. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  570. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  571. else:
  572. gcmd.Command(cmd)
  573. if ret != 0:
  574. self.notebookpanel.notebook.SetSelection(0)
  575. return
  576. # update buttons status
  577. for btn in (self.btn_run,
  578. self.btn_cancel,
  579. self.btn_clipboard,
  580. self.btn_help):
  581. btn.Enable(False)
  582. def OnAbort(self, event):
  583. """!Abort running command"""
  584. from core.gconsole import wxCmdAbort
  585. event = wxCmdAbort(aborted = True)
  586. wx.PostEvent(self._gconsole, event)
  587. def OnCopy(self, event):
  588. """!Copy the command"""
  589. cmddata = wx.TextDataObject()
  590. # list -> string
  591. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  592. cmddata.SetText(cmdstring)
  593. if wx.TheClipboard.Open():
  594. # wx.TheClipboard.UsePrimarySelection(True)
  595. wx.TheClipboard.SetData(cmddata)
  596. wx.TheClipboard.Close()
  597. self.SetStatusText(_("'%s' copied to clipboard") % \
  598. (cmdstring))
  599. def OnCancel(self, event):
  600. """!Cancel button pressed"""
  601. self.MakeModal(False)
  602. if self.get_dcmd and \
  603. self.parent and \
  604. self.parent.GetName() in ('LayerTree',
  605. 'MapWindow'):
  606. # display decorations and
  607. # pressing OK or cancel after setting layer properties
  608. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  609. or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >= 1:
  610. self.Hide()
  611. # canceled layer with nothing set
  612. elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
  613. self.parent.Delete(self.layer)
  614. self.Destroy()
  615. else:
  616. # cancel for non-display commands
  617. self.Destroy()
  618. def OnHelp(self, event):
  619. """!Show manual page (switch to the 'Manual' notebook page)"""
  620. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  621. self.notebookpanel.notebook.SetSelectionByName('manual')
  622. self.notebookpanel.OnPageChange(None)
  623. if event:
  624. event.Skip()
  625. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  626. """!Create command string (python list)"""
  627. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  628. ignoreRequired = ignoreRequired)
  629. class CmdPanel(wx.Panel):
  630. """!A panel containing a notebook dividing in tabs the different
  631. guisections of the GRASS cmd.
  632. """
  633. def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  634. if frame:
  635. self.parent = frame
  636. else:
  637. self.parent = parent
  638. self.task = task
  639. self._giface = giface
  640. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  641. self.mapCreated = Signal
  642. # Determine tab layout
  643. sections = []
  644. is_section = {}
  645. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  646. self.label_id = [] # wrap titles on resize
  647. self.Bind(wx.EVT_SIZE, self.OnSize)
  648. for task in not_hidden:
  649. if task.get('required', False):
  650. # All required go into Main, even if they had defined another guisection
  651. task['guisection'] = _('Required')
  652. if task.get('guisection','') == '':
  653. # Undefined guisections end up into Options
  654. task['guisection'] = _('Optional')
  655. if task['guisection'] not in is_section:
  656. # We do it like this to keep the original order, except for Main which goes first
  657. is_section[task['guisection']] = 1
  658. sections.append(task['guisection'])
  659. else:
  660. is_section[ task['guisection'] ] += 1
  661. del is_section
  662. # 'Required' tab goes first, 'Optional' as the last one
  663. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  664. if content in sections:
  665. idx = sections.index(content)
  666. sections[idx:idx+1] = []
  667. sections[newidx:newidx] = [content]
  668. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  669. # build notebook
  670. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  671. if style == 0: # basic top
  672. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  673. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  674. elif style == 1: # basic left
  675. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  676. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  677. elif style == 2: # fancy green
  678. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  679. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  680. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  681. elif style == 3:
  682. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  683. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  684. self.notebook.Refresh()
  685. tab = {}
  686. tabsizer = {}
  687. for section in sections:
  688. tab[section] = ScrolledPanel(parent = self.notebook)
  689. tab[section].SetScrollRate(10, 10)
  690. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  691. #
  692. # flags
  693. #
  694. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  695. for f in visible_flags:
  696. which_sizer = tabsizer[ f['guisection'] ]
  697. which_panel = tab[ f['guisection'] ]
  698. # if label is given: description -> tooltip
  699. if f.get('label','') != '':
  700. title = text_beautify(f['label'])
  701. tooltip = text_beautify(f['description'], width = -1)
  702. else:
  703. title = text_beautify(f['description'])
  704. tooltip = None
  705. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  706. rtitle_txt = wx.StaticText(parent = which_panel,
  707. label = '(' + f['name'] + ')')
  708. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  709. self.label_id.append(chk.GetId())
  710. if tooltip:
  711. chk.SetToolTipString(tooltip)
  712. chk.SetValue(f.get('value', False))
  713. title_sizer.Add(item = chk, proportion = 1,
  714. flag = wx.EXPAND)
  715. title_sizer.Add(item = rtitle_txt, proportion = 0,
  716. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  717. which_sizer.Add(item = title_sizer, proportion = 0,
  718. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  719. f['wxId'] = [ chk.GetId(), ]
  720. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  721. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  722. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  723. label = _("Parameterized in model"))
  724. parChk.SetName('ModelParam')
  725. parChk.SetValue(f.get('parameterized', False))
  726. if 'wxId' in f:
  727. f['wxId'].append(parChk.GetId())
  728. else:
  729. f['wxId'] = [ parChk.GetId() ]
  730. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  731. which_sizer.Add(item = parChk, proportion = 0,
  732. flag = wx.LEFT, border = 20)
  733. if f['name'] in ('verbose', 'quiet'):
  734. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  735. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  736. if f['name'] == vq:
  737. chk.SetValue(True)
  738. f['value'] = True
  739. elif f['name'] == 'overwrite' and 'value' not in f:
  740. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  741. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  742. #
  743. # parameters
  744. #
  745. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  746. try:
  747. first_param = visible_params[0]
  748. except IndexError:
  749. first_param = None
  750. for p in visible_params:
  751. which_sizer = tabsizer[p['guisection']]
  752. which_panel = tab[p['guisection']]
  753. # if label is given -> label and description -> tooltip
  754. # otherwise description -> lavel
  755. if p.get('label','') != '':
  756. title = text_beautify(p['label'])
  757. tooltip = text_beautify(p['description'], width = -1)
  758. else:
  759. title = text_beautify(p['description'])
  760. tooltip = None
  761. prompt = p.get('prompt', '')
  762. # text style (required -> bold)
  763. if not p.get('required', False):
  764. text_style = wx.FONTWEIGHT_NORMAL
  765. else:
  766. text_style = wx.FONTWEIGHT_BOLD
  767. # title sizer (description, name, type)
  768. if (len(p.get('values', [])) > 0) and \
  769. p.get('multiple', False) and \
  770. p.get('gisprompt', False) == False and \
  771. p.get('type', '') == 'string':
  772. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  773. else:
  774. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  775. title_txt = wx.StaticText(parent = which_panel)
  776. if p['key_desc']:
  777. ltype = ','.join(p['key_desc'])
  778. else:
  779. ltype = p['type']
  780. rtitle_txt = wx.StaticText(parent = which_panel,
  781. label = '(' + p['name'] + '=' + ltype + ')')
  782. title_sizer.Add(item = title_txt, proportion = 1,
  783. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  784. title_sizer.Add(item = rtitle_txt, proportion = 0,
  785. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  786. which_sizer.Add(item = title_sizer, proportion = 0,
  787. flag = wx.EXPAND)
  788. self.label_id.append(title_txt.GetId())
  789. # title expansion
  790. if p.get('multiple', False) and len(p.get('values','')) == 0:
  791. title = _("[multiple]") + " " + title
  792. if p.get('value','') == '' :
  793. p['value'] = p.get('default','')
  794. if (len(p.get('values', [])) > 0):
  795. valuelist = map(str, p.get('values',[]))
  796. valuelist_desc = map(unicode, p.get('values_desc',[]))
  797. if p.get('multiple', False) and \
  798. p.get('gisprompt',False) == False and \
  799. p.get('type', '') == 'string':
  800. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  801. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  802. if valuelist_desc:
  803. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  804. else:
  805. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  806. isEnabled = {}
  807. # copy default values
  808. if p['value'] == '':
  809. p['value'] = p.get('default', '')
  810. for defval in p.get('value', '').split(','):
  811. isEnabled[ defval ] = 'yes'
  812. # for multi checkboxes, this is an array of all wx IDs
  813. # for each individual checkbox
  814. p[ 'wxId' ] = list()
  815. idx = 0
  816. for val in valuelist:
  817. try:
  818. label = valuelist_desc[idx]
  819. except IndexError:
  820. label = val
  821. chkbox = wx.CheckBox(parent = which_panel,
  822. label = text_beautify(label))
  823. p[ 'wxId' ].append(chkbox.GetId())
  824. if val in isEnabled:
  825. chkbox.SetValue(True)
  826. hSizer.Add(item = chkbox, proportion = 0)
  827. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  828. idx += 1
  829. stSizer.Add(item = hSizer, proportion = 0,
  830. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  831. which_sizer.Add(item = stSizer, proportion = 0,
  832. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  833. elif p.get('gisprompt', False) is False:
  834. if len(valuelist) == 1: # -> textctrl
  835. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  836. str(valuelist[0])))
  837. if p.get('type', '') == 'integer' and \
  838. not p.get('multiple', False):
  839. # for multiple integers use textctrl instead of spinsctrl
  840. try:
  841. minValue, maxValue = map(int, valuelist[0].split('-'))
  842. except ValueError:
  843. minValue = -1e6
  844. maxValue = 1e6
  845. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  846. min = minValue, max = maxValue)
  847. style = wx.BOTTOM | wx.LEFT
  848. else:
  849. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  850. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  851. value = self._getValue(p)
  852. # parameter previously set
  853. if value:
  854. if isinstance(txt2, wx.SpinCtrl):
  855. txt2.SetValue(int(value))
  856. else:
  857. txt2.SetValue(value)
  858. which_sizer.Add(item = txt2, proportion = 0,
  859. flag = style, border = 5)
  860. p['wxId'] = [ txt2.GetId(), ]
  861. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  862. else:
  863. title_txt.SetLabel(title + ':')
  864. value = self._getValue(p)
  865. if p['name'] == 'icon': # symbols
  866. bitmap = wx.Bitmap(os.path.join(globalvar.ETCSYMBOLDIR, value) + '.png')
  867. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  868. bitmap = bitmap)
  869. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  870. iconLabel.SetLabel(value)
  871. p['value'] = value
  872. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  873. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  874. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  875. this_sizer.Add(item = bb, proportion = 0,
  876. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  877. this_sizer.Add(item = iconLabel, proportion = 0,
  878. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  879. which_sizer.Add(item = this_sizer, proportion = 0,
  880. flag = wx.ADJUST_MINSIZE, border = 0)
  881. else:
  882. # list of values (combo)
  883. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  884. size = globalvar.DIALOG_COMBOBOX_SIZE,
  885. choices = valuelist, style = wx.CB_DROPDOWN)
  886. if value:
  887. cb.SetValue(value) # parameter previously set
  888. which_sizer.Add(item = cb, proportion = 0,
  889. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  890. p['wxId'] = [cb.GetId(),]
  891. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  892. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  893. if p.get('guidependency', ''):
  894. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  895. # text entry
  896. if (p.get('type','string') in ('string','integer','float')
  897. and len(p.get('values',[])) == 0
  898. and p.get('gisprompt',False) == False
  899. and p.get('prompt','') != 'color'):
  900. title_txt.SetLabel(title + ':')
  901. if p.get('multiple', False) or \
  902. p.get('type', 'string') == 'string' or \
  903. len(p.get('key_desc', [])) > 1:
  904. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  905. value = self._getValue(p)
  906. if value:
  907. # parameter previously set
  908. txt3.SetValue(str(value))
  909. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  910. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  911. elif p.get('type', '') == 'integer':
  912. minValue = -1e9
  913. maxValue = 1e9
  914. value = self._getValue(p)
  915. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  916. size = globalvar.DIALOG_SPIN_SIZE,
  917. min = minValue, max = maxValue)
  918. if value:
  919. txt3.SetValue(int(value)) # parameter previously set
  920. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  921. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  922. else: # float
  923. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  924. validator = FloatValidator())
  925. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  926. value = self._getValue(p)
  927. if value:
  928. txt3.SetValue(str(value)) # parameter previously set
  929. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  930. which_sizer.Add(item = txt3, proportion = 0,
  931. flag = style, border = 5)
  932. p['wxId'] = [ txt3.GetId(), ]
  933. #
  934. # element selection tree combobox (maps, icons, regions, etc.)
  935. #
  936. if p.get('gisprompt', False):
  937. title_txt.SetLabel(title + ':')
  938. # GIS element entry
  939. if p.get('prompt','') not in ('color',
  940. 'subgroup',
  941. 'sigfile',
  942. 'dbdriver',
  943. 'dbname',
  944. 'dbtable',
  945. 'dbcolumn',
  946. 'layer',
  947. 'location',
  948. 'mapset',
  949. 'dbase',
  950. 'coords',
  951. 'file',
  952. 'dir'):
  953. multiple = p.get('multiple', False)
  954. if p.get('age', '') == 'new':
  955. mapsets = [grass.gisenv()['MAPSET'],]
  956. else:
  957. mapsets = None
  958. if self.task.name in ('r.proj', 'v.proj') \
  959. and p.get('name', '') == 'input':
  960. if self.task.name == 'r.proj':
  961. isRaster = True
  962. else:
  963. isRaster = False
  964. selection = gselect.ProjSelect(parent = which_panel,
  965. isRaster = isRaster)
  966. p['wxId'] = [ selection.GetId(), ]
  967. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  968. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  969. else:
  970. elem = p.get('element', None)
  971. # hack for t.* modules
  972. if elem in ('stds', 'map'):
  973. orig_elem = elem
  974. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  975. if type_param:
  976. elem = type_param.get('default', None)
  977. # for t.(un)register:
  978. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  979. if maps_param and orig_elem == 'stds':
  980. element_dict = {'rast': 'strds', 'vect': 'stvds', 'rast3d': 'str3ds'}
  981. elem = element_dict[type_param.get('default')]
  982. if self.parent.modeler:
  983. extraItems = {_('Graphical Modeler') : self.parent.modeler.GetModel().GetMaps(p.get('prompt'))}
  984. else:
  985. extraItems = None
  986. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  987. size = globalvar.DIALOG_GSELECT_SIZE,
  988. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  989. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  990. extraItems = extraItems)
  991. value = self._getValue(p)
  992. if value:
  993. selection.SetValue(value)
  994. formatSelector = True
  995. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  996. # we target the textctl here
  997. textWin = selection.GetTextCtrl()
  998. p['wxId'] = [ textWin.GetId(), ]
  999. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1000. if prompt == 'vector':
  1001. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1002. # if formatSelector and p.get('age', 'old') == 'old':
  1003. # # OGR supported (read-only)
  1004. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1005. # self.hsizer.Add(item = selection,
  1006. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1007. # border = 5)
  1008. # # format (native / ogr)
  1009. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1010. # label = " %s " % _("Format"),
  1011. # style = wx.RA_SPECIFY_ROWS,
  1012. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1013. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1014. # rbox.SetSelection(1)
  1015. # rbox.SetName('VectorFormat')
  1016. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1017. # self.hsizer.Add(item = rbox,
  1018. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1019. # wx.RIGHT | wx.ALIGN_TOP,
  1020. # border = 5)
  1021. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1022. # default = 'dir',
  1023. # exclude = ['file'])
  1024. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1025. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1026. # ogrSelection.SetName('OgrSelect')
  1027. # ogrSelection.Hide()
  1028. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1029. # p['wxId'].append(rbox.GetId())
  1030. # p['wxId'].append(ogrSelection.GetId())
  1031. # for win in ogrSelection.GetDsnWin():
  1032. # p['wxId'].append(win.GetId())
  1033. # else:
  1034. which_sizer.Add(item = selection, proportion = 0,
  1035. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1036. border = 5)
  1037. elif prompt == 'group':
  1038. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1039. which_sizer.Add(item = selection, proportion = 0,
  1040. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1041. border = 5)
  1042. else:
  1043. which_sizer.Add(item = selection, proportion = 0,
  1044. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1045. border = 5)
  1046. # subgroup
  1047. elif prompt == 'subgroup':
  1048. selection = gselect.SubGroupSelect(parent = which_panel)
  1049. p['wxId'] = [ selection.GetId() ]
  1050. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1051. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1052. which_sizer.Add(item = selection, proportion = 0,
  1053. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1054. border = 5)
  1055. # sigrature file
  1056. elif prompt == 'sigfile':
  1057. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1058. p['wxId'] = [ selection.GetId() ]
  1059. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1060. which_sizer.Add(item = selection, proportion = 0,
  1061. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1062. border = 5)
  1063. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1064. elif prompt in ('dbdriver',
  1065. 'dbname',
  1066. 'dbtable',
  1067. 'dbcolumn',
  1068. 'layer',
  1069. 'location',
  1070. 'mapset',
  1071. 'dbase'):
  1072. if p.get('multiple', 'no') == 'yes':
  1073. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1074. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1075. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1076. else:
  1077. value = self._getValue(p)
  1078. if prompt == 'layer':
  1079. if p.get('element', 'layer') == 'layer_all':
  1080. all = True
  1081. else:
  1082. all = False
  1083. if p.get('age', 'old') == 'old':
  1084. win = gselect.LayerSelect(parent = which_panel,
  1085. all = all,
  1086. default = p['default'])
  1087. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1088. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1089. win.SetValue(str(value)) # default or previously set value
  1090. else:
  1091. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1092. min = 1, max = 100, initial = int(p['default']))
  1093. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1094. win.SetValue(int(value)) # default or previously set value
  1095. p['wxId'] = [ win.GetId() ]
  1096. elif prompt == 'dbdriver':
  1097. win = gselect.DriverSelect(parent = which_panel,
  1098. choices = p.get('values', []),
  1099. value = value)
  1100. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1101. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1102. elif prompt == 'dbname':
  1103. win = gselect.DatabaseSelect(parent = which_panel,
  1104. value = value)
  1105. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1106. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1107. elif prompt == 'dbtable':
  1108. if p.get('age', 'old') == 'old':
  1109. win = gselect.TableSelect(parent = which_panel)
  1110. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1111. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1112. else:
  1113. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1114. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1115. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1116. elif prompt == 'dbcolumn':
  1117. win = gselect.ColumnSelect(parent = which_panel,
  1118. value = value,
  1119. param = p)
  1120. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1121. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1122. elif prompt == 'location':
  1123. win = gselect.LocationSelect(parent = which_panel,
  1124. value = value)
  1125. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1126. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1127. elif prompt == 'mapset':
  1128. if p.get('age', 'old') == 'old':
  1129. new = False
  1130. else:
  1131. new = True
  1132. win = gselect.MapsetSelect(parent = which_panel,
  1133. value = value, new = new)
  1134. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1135. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1136. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1137. elif prompt == 'dbase':
  1138. win = gselect.DbaseSelect(parent = which_panel,
  1139. changeCallback = self.OnSetValue)
  1140. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1141. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1142. if 'wxId' not in p:
  1143. try:
  1144. p['wxId'] = [ win.GetId(), ]
  1145. except AttributeError:
  1146. pass
  1147. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1148. if prompt == 'dbname':
  1149. flags |= wx.EXPAND
  1150. which_sizer.Add(item = win, proportion = 0,
  1151. flag = flags, border = 5)
  1152. # color entry
  1153. elif prompt == 'color':
  1154. default_color = (200,200,200)
  1155. label_color = _("Select Color")
  1156. if p.get('default','') != '':
  1157. default_color, label_color = utils.color_resolve(p['default'])
  1158. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1159. default_color, label_color = utils.color_resolve(p['value'])
  1160. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1161. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1162. else:
  1163. this_sizer = which_sizer
  1164. colorSize = 150
  1165. # For color selectors, this is a three-member array, holding the IDs of
  1166. # the text control for multiple colors (or None),
  1167. # the selector proper and either a "transparent" checkbox or None
  1168. if p.get('multiple', False):
  1169. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1170. this_sizer.Add(item = txt, proportion = 1,
  1171. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1172. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1173. colorSize = 40
  1174. label_color = ''
  1175. p['wxId'] = [txt.GetId(),]
  1176. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1177. else:
  1178. p['wxId'] = [None,]
  1179. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1180. label = label_color, colour = default_color,
  1181. pos = wx.DefaultPosition, size = (colorSize,-1))
  1182. this_sizer.Add(item = btn_colour, proportion = 0,
  1183. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1184. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1185. p['wxId'].append(btn_colour.GetId())
  1186. if p.get('element', '') == 'color_none':
  1187. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1188. if p.get('value','') == "none":
  1189. none_check.SetValue(True)
  1190. else:
  1191. none_check.SetValue(False)
  1192. this_sizer.Add(item = none_check, proportion = 0,
  1193. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1194. which_sizer.Add(this_sizer)
  1195. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1196. p['wxId'].append(none_check.GetId())
  1197. else:
  1198. p['wxId'].append(None)
  1199. # file selector
  1200. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1201. if p.get('age', 'new') == 'new':
  1202. fmode = wx.SAVE
  1203. else:
  1204. fmode = wx.OPEN
  1205. # check wildcard
  1206. try:
  1207. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1208. except:
  1209. fExt = None
  1210. if not fExt:
  1211. fMask = '*.*'
  1212. else:
  1213. fMask = '%s files (*%s)|*%s|Files (*.*)|*.*' % (fExt[1:].upper(), fExt, fExt)
  1214. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1215. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1216. dialogTitle = _('Choose %s') % \
  1217. p.get('description', _('file')).lower(),
  1218. buttonText = _('Browse'),
  1219. startDirectory = os.getcwd(), fileMode = fmode,
  1220. changeCallback = self.OnSetValue)
  1221. value = self._getValue(p)
  1222. if value:
  1223. fbb.SetValue(value) # parameter previously set
  1224. which_sizer.Add(item = fbb, proportion = 0,
  1225. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1226. # A file browse button is a combobox with two children:
  1227. # a textctl and a button;
  1228. # we have to target the button here
  1229. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1230. if p.get('age', 'new') == 'old' and \
  1231. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1232. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1233. # widget for interactive input
  1234. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1235. style = wx.TE_MULTILINE,
  1236. size = (-1, 75))
  1237. if p.get('value', '') and os.path.isfile(p['value']):
  1238. f = open(p['value'])
  1239. ifbb.SetValue(''.join(f.readlines()))
  1240. f.close()
  1241. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1242. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1243. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1244. btnSave = wx.Button(parent = which_panel, id = wx.ID_SAVEAS)
  1245. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1246. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1247. label = _('or enter values interactively')),
  1248. proportion = 0,
  1249. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1250. which_sizer.Add(item = ifbb, proportion = 1,
  1251. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1252. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1253. btnSizer.Add(item = btnLoad, proportion = 0,
  1254. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1255. btnSizer.Add(item = btnSave, proportion = 0,
  1256. flag = wx.ALIGN_RIGHT)
  1257. which_sizer.Add(item = btnSizer, proportion = 0,
  1258. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1259. p['wxId'].append(ifbb.GetId())
  1260. p['wxId'].append(btnLoad.GetId())
  1261. p['wxId'].append(btnSave.GetId())
  1262. # directory selector
  1263. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1264. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1265. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1266. dialogTitle = _('Choose %s') % \
  1267. p.get('description', _('Directory')),
  1268. buttonText = _('Browse'),
  1269. startDirectory = os.getcwd(),
  1270. changeCallback = self.OnSetValue)
  1271. value = self._getValue(p)
  1272. if value:
  1273. fbb.SetValue(value) # parameter previously set
  1274. which_sizer.Add(item = fbb, proportion = 0,
  1275. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1276. # A file browse button is a combobox with two children:
  1277. # a textctl and a button;
  1278. # we have to target the button here
  1279. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1280. # interactive inserting of coordinates from map window
  1281. elif prompt == 'coords':
  1282. # interactive inserting if layer manager is accessible
  1283. if self._giface:
  1284. win = gselect.CoordinatesSelect(parent = which_panel,
  1285. giface = self._giface,
  1286. multiple = p.get('multiple', False),
  1287. param = p)
  1288. p['wxId'] = [win.GetTextWin().GetId()]
  1289. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1290. # normal text field
  1291. else:
  1292. win = wx.TextCtrl(parent = which_panel)
  1293. p['wxId'] = [win.GetId()]
  1294. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1295. which_sizer.Add(item = win,
  1296. proportion = 0,
  1297. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1298. border = 5)
  1299. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1300. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1301. label = _("Parameterized in model"))
  1302. parChk.SetName('ModelParam')
  1303. parChk.SetValue(p.get('parameterized', False))
  1304. if 'wxId' in p:
  1305. p['wxId'].append(parChk.GetId())
  1306. else:
  1307. p['wxId'] = [ parChk.GetId() ]
  1308. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1309. which_sizer.Add(item = parChk, proportion = 0,
  1310. flag = wx.LEFT, border = 20)
  1311. if title_txt is not None:
  1312. # create tooltip if given
  1313. if len(p['values_desc']) > 0:
  1314. if tooltip:
  1315. tooltip += 2 * os.linesep
  1316. else:
  1317. tooltip = ''
  1318. if len(p['values']) == len(p['values_desc']):
  1319. for i in range(len(p['values'])):
  1320. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1321. tooltip.strip(os.linesep)
  1322. if tooltip:
  1323. title_txt.SetToolTipString(tooltip)
  1324. if p == first_param:
  1325. if 'wxId' in p and len(p['wxId']) > 0:
  1326. win = self.FindWindowById(p['wxId'][0])
  1327. win.SetFocus()
  1328. #
  1329. # set widget relations for OnUpdateSelection
  1330. #
  1331. pMap = None
  1332. pLayer = []
  1333. pDriver = None
  1334. pDatabase = None
  1335. pTable = None
  1336. pColumn = []
  1337. pGroup = None
  1338. pSubGroup = None
  1339. pSigFile = None
  1340. pDbase = None
  1341. pLocation = None
  1342. pMapset = None
  1343. for p in self.task.params:
  1344. guidep = p.get('guidependency', '')
  1345. if guidep:
  1346. # fixed options dependency defined
  1347. options = guidep.split(',')
  1348. for opt in options:
  1349. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1350. if id:
  1351. if 'wxId-bind' not in p:
  1352. p['wxId-bind'] = list()
  1353. p['wxId-bind'] += pOpt['wxId']
  1354. continue
  1355. if p.get('gisprompt', False) == False:
  1356. continue
  1357. prompt = p.get('prompt', '')
  1358. if prompt in ('raster', 'vector'):
  1359. name = p.get('name', '')
  1360. if name in ('map', 'input'):
  1361. pMap = p
  1362. elif prompt == 'layer':
  1363. pLayer.append(p)
  1364. elif prompt == 'dbcolumn':
  1365. pColumn.append(p)
  1366. elif prompt == 'dbdriver':
  1367. pDriver = p
  1368. elif prompt == 'dbname':
  1369. pDatabase = p
  1370. elif prompt == 'dbtable':
  1371. pTable = p
  1372. elif prompt == 'group':
  1373. pGroup = p
  1374. elif prompt == 'subgroup':
  1375. pSubGroup = p
  1376. elif prompt == 'sigfile':
  1377. pSigFile = p
  1378. elif prompt == 'dbase':
  1379. pDbase = p
  1380. elif prompt == 'location':
  1381. pLocation = p
  1382. elif prompt == 'mapset':
  1383. pMapset = p
  1384. # collect ids
  1385. pColumnIds = []
  1386. for p in pColumn:
  1387. pColumnIds += p['wxId']
  1388. pLayerIds = []
  1389. for p in pLayer:
  1390. pLayerIds += p['wxId']
  1391. # set wxId-bindings
  1392. if pMap:
  1393. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1394. if pLayer:
  1395. pMap['wxId-bind'] += pLayerIds
  1396. if pLayer:
  1397. for p in pLayer:
  1398. p['wxId-bind'] = copy.copy(pColumnIds)
  1399. if pDriver and pTable:
  1400. pDriver['wxId-bind'] = pTable['wxId']
  1401. if pDatabase and pTable:
  1402. pDatabase['wxId-bind'] = pTable['wxId']
  1403. if pTable and pColumnIds:
  1404. pTable['wxId-bind'] = pColumnIds
  1405. if pGroup and pSubGroup:
  1406. if pSigFile:
  1407. pGroup['wxId-bind'] = copy.copy(pSigFile['wxId']) + pSubGroup['wxId']
  1408. pSubGroup['wxId-bind'] = pSigFile['wxId']
  1409. else:
  1410. pGroup['wxId-bind'] = pSubGroup['wxId']
  1411. if pDbase and pLocation:
  1412. pDbase['wxId-bind'] = pLocation['wxId']
  1413. if pLocation and pMapset:
  1414. pLocation['wxId-bind'] = pMapset['wxId']
  1415. if pLocation and pMapset and pMap:
  1416. pLocation['wxId-bind'] += pMap['wxId']
  1417. pMapset['wxId-bind'] = pMap['wxId']
  1418. #
  1419. # determine panel size
  1420. #
  1421. maxsizes = (0, 0)
  1422. for section in sections:
  1423. tab[section].SetSizer(tabsizer[section])
  1424. tabsizer[section].Fit(tab[section])
  1425. tab[section].Layout()
  1426. minsecsizes = tabsizer[section].GetSize()
  1427. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1428. # TODO: be less arbitrary with these 600
  1429. self.panelMinHeight = 100
  1430. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1431. for section in sections:
  1432. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1433. # add pages to notebook
  1434. imageList = wx.ImageList(16, 16)
  1435. self.notebook.AssignImageList(imageList)
  1436. for section in sections:
  1437. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1438. index = self.AddBitmapToImageList(section, imageList)
  1439. if index >= 0:
  1440. self.notebook.SetPageImage(section, index)
  1441. # are we running from command line?
  1442. ### add 'command output' tab regardless standalone dialog
  1443. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1444. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1445. from gui_core.goutput import GConsoleWindow
  1446. self._gconsole = GConsole(guiparent = self.notebook)
  1447. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1448. self._gconsole.Bind(EVT_CMD_RUN,
  1449. lambda event:
  1450. self._switchPageHandler(event = event, priority = 2))
  1451. self._gconsole.Bind(EVT_CMD_DONE,
  1452. lambda event:
  1453. self._switchPageHandler(event = event, priority = 3))
  1454. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1455. index = self.AddBitmapToImageList(section = 'output', imageList = imageList)
  1456. if index >= 0:
  1457. self.notebook.SetPageImage('output', index)
  1458. else:
  1459. self.goutput = None
  1460. self._gconsole = None
  1461. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.name)
  1462. if not self.manualTab.GetFile():
  1463. self.manualTab.Hide()
  1464. else:
  1465. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1466. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1467. if index >= 0:
  1468. self.notebook.SetPageImage('manual', index)
  1469. if self.manualTab.IsLoaded():
  1470. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1471. self.notebook.SetSelection(0)
  1472. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1473. self.SetSizer(panelsizer)
  1474. panelsizer.Fit(self.notebook)
  1475. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1476. def _getValue(self, p):
  1477. """!Get value or default value of given parameter
  1478. @param p parameter directory
  1479. """
  1480. if p.get('value', '') != '':
  1481. return p['value']
  1482. return p.get('default', '')
  1483. def OnFileLoad(self, event):
  1484. """!Load file to interactive input"""
  1485. me = event.GetId()
  1486. win = dict()
  1487. for p in self.task.params:
  1488. if 'wxId' in p and me in p['wxId']:
  1489. win['file'] = self.FindWindowById(p['wxId'][0])
  1490. win['text'] = self.FindWindowById(p['wxId'][1])
  1491. break
  1492. if not win:
  1493. return
  1494. path = win['file'].GetValue()
  1495. if not path:
  1496. gcmd.GMessage(parent = self,
  1497. message = _("Nothing to load."))
  1498. return
  1499. data = ''
  1500. f = open(path, "r")
  1501. try:
  1502. data = f.read()
  1503. finally:
  1504. f.close()
  1505. win['text'].SetValue(data)
  1506. def OnFileSave(self, event):
  1507. """!Save interactive input to the file"""
  1508. wId = event.GetId()
  1509. win = {}
  1510. for p in self.task.params:
  1511. if wId in p.get('wxId', []):
  1512. win['file'] = self.FindWindowById(p['wxId'][0])
  1513. win['text'] = self.FindWindowById(p['wxId'][1])
  1514. break
  1515. if not win:
  1516. return
  1517. text = win['text'].GetValue()
  1518. if not text:
  1519. gcmd.GMessage(parent = self,
  1520. message = _("Nothing to save."))
  1521. return
  1522. dlg = wx.FileDialog(parent = self,
  1523. message = _("Save input as..."),
  1524. defaultDir = os.getcwd(),
  1525. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  1526. if dlg.ShowModal() == wx.ID_OK:
  1527. path = dlg.GetPath()
  1528. enc = locale.getdefaultlocale()[1]
  1529. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1530. try:
  1531. f.write(text + os.linesep)
  1532. finally:
  1533. f.close()
  1534. win['file'].SetValue(path)
  1535. dlg.Destroy()
  1536. def OnFileText(self, event):
  1537. """File input interactively entered"""
  1538. text = event.GetString()
  1539. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1540. if not p:
  1541. return # should not happen
  1542. win = self.FindWindowById(p['wxId'][0])
  1543. if text:
  1544. filename = win.GetValue()
  1545. if not filename:
  1546. filename = grass.tempfile()
  1547. win.SetValue(filename)
  1548. enc = locale.getdefaultlocale()[1]
  1549. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1550. try:
  1551. f.write(text)
  1552. if text[-1] != os.linesep:
  1553. f.write(os.linesep)
  1554. finally:
  1555. f.close()
  1556. else:
  1557. win.SetValue('')
  1558. def OnVectorFormat(self, event):
  1559. """!Change vector format (native / ogr).
  1560. Currently unused.
  1561. """
  1562. sel = event.GetSelection()
  1563. idEvent = event.GetId()
  1564. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1565. if not p:
  1566. return # should not happen
  1567. # detect windows
  1568. winNative = None
  1569. winOgr = None
  1570. for id in p['wxId']:
  1571. if id == idEvent:
  1572. continue
  1573. name = self.FindWindowById(id).GetName()
  1574. if name == 'Select':
  1575. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1576. elif name == 'OgrSelect':
  1577. winOgr = self.FindWindowById(id)
  1578. # enable / disable widgets & update values
  1579. rbox = self.FindWindowByName('VectorFormat')
  1580. self.hsizer.Remove(rbox)
  1581. if sel == 0: # -> native
  1582. winOgr.Hide()
  1583. self.hsizer.Remove(winOgr)
  1584. self.hsizer.Add(item = winNative,
  1585. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1586. border = 5)
  1587. winNative.Show()
  1588. p['value'] = winNative.GetValue()
  1589. elif sel == 1: # -> OGR
  1590. sizer = wx.BoxSizer(wx.VERTICAL)
  1591. winNative.Hide()
  1592. self.hsizer.Remove(winNative)
  1593. sizer.Add(item = winOgr)
  1594. winOgr.Show()
  1595. p['value'] = winOgr.GetDsn()
  1596. self.hsizer.Add(item = sizer,
  1597. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1598. border = 5)
  1599. self.hsizer.Add(item = rbox,
  1600. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1601. wx.RIGHT | wx.ALIGN_TOP,
  1602. border = 5)
  1603. self.hsizer.Layout()
  1604. self.Layout()
  1605. self.OnUpdateValues()
  1606. self.OnUpdateSelection(event)
  1607. def OnUpdateDialog(self, event):
  1608. for fn, kwargs in event.data.iteritems():
  1609. fn(**kwargs)
  1610. self.parent.updateValuesHook()
  1611. def OnVerbosity(self, event):
  1612. """!Verbosity level changed"""
  1613. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1614. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1615. if event.IsChecked():
  1616. if event.GetId() == verbose.GetId():
  1617. if quiet.IsChecked():
  1618. quiet.SetValue(False)
  1619. self.task.get_flag('quiet')['value'] = False
  1620. else:
  1621. if verbose.IsChecked():
  1622. verbose.SetValue(False)
  1623. self.task.get_flag('verbose')['value'] = False
  1624. event.Skip()
  1625. def OnPageChange(self, event):
  1626. if not event:
  1627. sel = self.notebook.GetSelection()
  1628. else:
  1629. sel = event.GetSelection()
  1630. idx = self.notebook.GetPageIndexByName('manual')
  1631. if idx > -1 and sel == idx:
  1632. # calling LoadPage() is strangely time-consuming (only first call)
  1633. # FIXME: move to helpPage.__init__()
  1634. if not self.manualTab.IsLoaded():
  1635. wx.Yield()
  1636. self.manualTab.LoadPage()
  1637. self.Layout()
  1638. if event:
  1639. # skip is needed for wx.Notebook on Windows
  1640. event.Skip()
  1641. # this is needed for dialogs launched from layer manager
  1642. # event is somehow propagated?
  1643. event.StopPropagation()
  1644. def _switchPageHandler(self, event, priority):
  1645. self._switchPage(priority = priority)
  1646. event.Skip()
  1647. def _switchPage(self, priority):
  1648. """!Manages @c 'output' notebook page according to event priority."""
  1649. if priority == 1:
  1650. self.notebook.HighlightPageByName('output')
  1651. if priority >= 2:
  1652. self.notebook.SetSelectionByName('output')
  1653. if priority >= 3:
  1654. self.SetFocus()
  1655. self.Raise()
  1656. def OnColorChange(self, event):
  1657. myId = event.GetId()
  1658. for p in self.task.params:
  1659. if 'wxId' in p and myId in p['wxId']:
  1660. multiple = p['wxId'][0] is not None # multiple colors
  1661. hasTansp = p['wxId'][2] is not None
  1662. if multiple:
  1663. # selected color is added at the end of textCtrl
  1664. colorchooser = wx.FindWindowById(p['wxId'][1])
  1665. new_color = colorchooser.GetValue()[:]
  1666. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1667. textCtrl = wx.FindWindowById(p['wxId'][0])
  1668. val = textCtrl.GetValue()
  1669. sep = ','
  1670. if val and val[-1] != sep:
  1671. val += sep
  1672. val += new_label
  1673. textCtrl.SetValue(val)
  1674. p[ 'value' ] = val
  1675. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1676. p[ 'value' ] = 'none'
  1677. else:
  1678. colorchooser = wx.FindWindowById(p['wxId'][1])
  1679. new_color = colorchooser.GetValue()[:]
  1680. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1681. # under wx2.8.1
  1682. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1683. colorchooser.SetLabel(new_label)
  1684. colorchooser.SetColour(new_color)
  1685. colorchooser.Refresh()
  1686. p[ 'value' ] = colorchooser.GetLabel()
  1687. self.OnUpdateValues()
  1688. def OnUpdateValues(self, event = None):
  1689. """!If we were part of a richer interface, report back the
  1690. current command being built.
  1691. This method should be set by the parent of this panel if
  1692. needed. It's a hook, actually. Beware of what is 'self' in
  1693. the method def, though. It will be called with no arguments.
  1694. """
  1695. pass
  1696. def OnCheckBoxMulti(self, event):
  1697. """!Fill the values as a ','-separated string according to
  1698. current status of the checkboxes.
  1699. """
  1700. me = event.GetId()
  1701. theParam = None
  1702. for p in self.task.params:
  1703. if 'wxId' in p and me in p['wxId']:
  1704. theParam = p
  1705. myIndex = p['wxId'].index(me)
  1706. # Unpack current value list
  1707. currentValues = {}
  1708. for isThere in theParam.get('value', '').split(','):
  1709. currentValues[isThere] = 1
  1710. theValue = theParam['values'][myIndex]
  1711. if event.Checked():
  1712. currentValues[ theValue ] = 1
  1713. else:
  1714. del currentValues[ theValue ]
  1715. # Keep the original order, so that some defaults may be recovered
  1716. currentValueList = []
  1717. for v in theParam['values']:
  1718. if v in currentValues:
  1719. currentValueList.append(v)
  1720. # Pack it back
  1721. theParam['value'] = ','.join(currentValueList)
  1722. self.OnUpdateValues()
  1723. def OnSetValue(self, event):
  1724. """!Retrieve the widget value and set the task value field
  1725. accordingly.
  1726. Use for widgets that have a proper GetValue() method, i.e. not
  1727. for selectors.
  1728. """
  1729. myId = event.GetId()
  1730. me = wx.FindWindowById(myId)
  1731. name = me.GetName()
  1732. found = False
  1733. for porf in self.task.params + self.task.flags:
  1734. if 'wxId' not in porf:
  1735. continue
  1736. if myId in porf['wxId']:
  1737. found = True
  1738. break
  1739. if not found:
  1740. return
  1741. if name == 'GdalSelect':
  1742. porf['value'] = event.dsn
  1743. elif name == 'ModelParam':
  1744. porf['parameterized'] = me.IsChecked()
  1745. else:
  1746. porf['value'] = me.GetValue()
  1747. self.OnUpdateValues(event)
  1748. event.Skip()
  1749. def OnSetSymbol(self, event):
  1750. """!Shows dialog for symbol selection"""
  1751. myId = event.GetId()
  1752. for p in self.task.params:
  1753. if 'wxId' in p and myId in p['wxId']:
  1754. from gui_core.dialogs import SymbolDialog
  1755. dlg = SymbolDialog(self, symbolPath = globalvar.ETCSYMBOLDIR,
  1756. currentSymbol = p['value'])
  1757. if dlg.ShowModal() == wx.ID_OK:
  1758. img = dlg.GetSelectedSymbolPath()
  1759. p['value'] = dlg.GetSelectedSymbolName()
  1760. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1761. label = wx.FindWindowById(p['wxId'][1])
  1762. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1763. label.SetLabel(p['value'])
  1764. self.OnUpdateValues(event)
  1765. dlg.Destroy()
  1766. def OnUpdateSelection(self, event):
  1767. """!Update dialog (layers, tables, columns, etc.)
  1768. """
  1769. if not hasattr(self.parent, "updateThread"):
  1770. if event:
  1771. event.Skip()
  1772. return
  1773. if event:
  1774. self.parent.updateThread.Update(UpdateDialog,
  1775. self,
  1776. event,
  1777. event.GetId(),
  1778. self.task)
  1779. else:
  1780. self.parent.updateThread.Update(UpdateDialog,
  1781. self,
  1782. None,
  1783. None,
  1784. self.task)
  1785. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1786. """!Produce a command line string (list) or feeding into GRASS.
  1787. @param ignoreErrors True then it will return whatever has been
  1788. built so far, even though it would not be a correct command
  1789. for GRASS
  1790. """
  1791. try:
  1792. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1793. ignoreRequired = ignoreRequired)
  1794. except ValueError, err:
  1795. dlg = wx.MessageDialog(parent = self,
  1796. message = unicode(err),
  1797. caption = _("Error in %s") % self.task.name,
  1798. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1799. dlg.ShowModal()
  1800. dlg.Destroy()
  1801. cmd = None
  1802. return cmd
  1803. def OnSize(self, event):
  1804. width = event.GetSize()[0]
  1805. fontsize = self.GetFont().GetPointSize()
  1806. text_width = max(width / (fontsize - 3), 70)
  1807. for id in self.label_id:
  1808. win = self.FindWindowById(id)
  1809. label = win.GetLabel()
  1810. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1811. win.SetLabel(label_new)
  1812. event.Skip()
  1813. def AddBitmapToImageList(self, section, imageList):
  1814. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1815. iconSectionDict = {'manual': os.path.join(globalvar.ETCICONDIR, iconTheme, 'help.png'),
  1816. _("Optional"): os.path.join(globalvar.ETCICONDIR, iconTheme, 'settings.png')}
  1817. if section in iconSectionDict.keys():
  1818. bitmap = wx.Bitmap(iconSectionDict[section])
  1819. bitmap.SetSize((16, 16))
  1820. idx = imageList.Add(bitmap)
  1821. return idx
  1822. return -1
  1823. class GUI:
  1824. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1825. centreOnParent = False, checkError = False):
  1826. """!Parses GRASS commands when module is imported and used from
  1827. Layer Manager.
  1828. """
  1829. self.parent = parent
  1830. self.show = show
  1831. self.modal = modal
  1832. self._giface = giface
  1833. self.centreOnParent = centreOnParent
  1834. self.checkError = checkError
  1835. self.grass_task = None
  1836. self.cmd = list()
  1837. global _blackList
  1838. if self.parent:
  1839. _blackList['enabled'] = True
  1840. else:
  1841. _blackList['enabled'] = False
  1842. def GetCmd(self):
  1843. """!Get validated command"""
  1844. return self.cmd
  1845. def ParseCommand(self, cmd, completed = None):
  1846. """!Parse command
  1847. Note: cmd is given as list
  1848. If command is given with options, return validated cmd list:
  1849. - add key name for first parameter if not given
  1850. - change mapname to mapname@mapset
  1851. """
  1852. dcmd_params = {}
  1853. if completed == None:
  1854. get_dcmd = None
  1855. layer = None
  1856. dcmd_params = None
  1857. else:
  1858. get_dcmd = completed[0]
  1859. layer = completed[1]
  1860. if completed[2]:
  1861. dcmd_params.update(completed[2])
  1862. # parse the interface decription
  1863. try:
  1864. global _blackList
  1865. self.grass_task = gtask.parse_interface(gcmd.GetRealCmd(cmd[0]),
  1866. blackList = _blackList)
  1867. except (grass.ScriptError, ValueError), e:
  1868. raise gcmd.GException(e.value)
  1869. # if layer parameters previously set, re-insert them into dialog
  1870. if completed is not None:
  1871. if 'params' in dcmd_params:
  1872. self.grass_task.params = dcmd_params['params']
  1873. if 'flags' in dcmd_params:
  1874. self.grass_task.flags = dcmd_params['flags']
  1875. err = list()
  1876. # update parameters if needed && validate command
  1877. if len(cmd) > 1:
  1878. i = 0
  1879. cmd_validated = [cmd[0]]
  1880. for option in cmd[1:]:
  1881. if option[0] == '-': # flag
  1882. if option[1] == '-':
  1883. self.grass_task.set_flag(option[2:], True)
  1884. else:
  1885. self.grass_task.set_flag(option[1], True)
  1886. cmd_validated.append(option)
  1887. else: # parameter
  1888. try:
  1889. key, value = option.split('=', 1)
  1890. except ValueError:
  1891. if self.grass_task.firstParam:
  1892. if i == 0: # add key name of first parameter if not given
  1893. key = self.grass_task.firstParam
  1894. value = option
  1895. else:
  1896. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1897. else:
  1898. continue
  1899. element = self.grass_task.get_param(key, raiseError = False)
  1900. if not element:
  1901. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1902. { 'cmd' : cmd[0],
  1903. 'key' : key })
  1904. continue
  1905. element = element['element']
  1906. if element in ['cell', 'vector']:
  1907. # mapname -> mapname@mapset
  1908. try:
  1909. name, mapset = value.split('@')
  1910. except ValueError:
  1911. mapset = grass.find_file(value, element)['mapset']
  1912. curr_mapset = grass.gisenv()['MAPSET']
  1913. if mapset and mapset != curr_mapset:
  1914. value = value + '@' + mapset
  1915. self.grass_task.set_param(key, value)
  1916. cmd_validated.append(key + '=' + value)
  1917. i += 1
  1918. # update original command list
  1919. cmd = cmd_validated
  1920. if self.show is not None:
  1921. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  1922. task_description = self.grass_task,
  1923. get_dcmd = get_dcmd, layer = layer)
  1924. else:
  1925. self.mf = None
  1926. if get_dcmd is not None:
  1927. # update only propwin reference
  1928. get_dcmd(dcmd = None, layer = layer, params = None,
  1929. propwin = self.mf)
  1930. if self.show is not None:
  1931. self.mf.notebookpanel.OnUpdateSelection(None)
  1932. if self.show is True:
  1933. if self.parent and self.centreOnParent:
  1934. self.mf.CentreOnParent()
  1935. else:
  1936. self.mf.CenterOnScreen()
  1937. self.mf.Show(self.show)
  1938. self.mf.MakeModal(self.modal)
  1939. else:
  1940. self.mf.OnApply(None)
  1941. self.cmd = cmd
  1942. if self.checkError:
  1943. return self.grass_task, err
  1944. else:
  1945. return self.grass_task
  1946. def GetCommandInputMapParamKey(self, cmd):
  1947. """!Get parameter key for input raster/vector map
  1948. @param cmd module name
  1949. @return parameter key
  1950. @return None on failure
  1951. """
  1952. # parse the interface decription
  1953. if not self.grass_task:
  1954. enc = locale.getdefaultlocale()[1]
  1955. if enc and enc.lower() == "cp932":
  1956. p = re.compile('encoding="' + enc + '"', re.IGNORECASE)
  1957. tree = etree.fromstring(p.sub('encoding="utf-8"',
  1958. gtask.get_interface_description(cmd).decode(enc).encode('utf-8')))
  1959. else:
  1960. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1961. self.grass_task = gtask.processTask(tree).get_task()
  1962. for p in self.grass_task.params:
  1963. if p.get('name', '') in ('input', 'map'):
  1964. age = p.get('age', '')
  1965. prompt = p.get('prompt', '')
  1966. element = p.get('element', '')
  1967. if age == 'old' and \
  1968. element in ('cell', 'grid3', 'vector') and \
  1969. prompt in ('raster', '3d-raster', 'vector'):
  1970. return p.get('name', None)
  1971. return None
  1972. class GrassGUIApp(wx.App):
  1973. """!Stand-alone GRASS command GUI
  1974. """
  1975. def __init__(self, grass_task):
  1976. self.grass_task = grass_task
  1977. wx.App.__init__(self, False)
  1978. def OnInit(self):
  1979. msg = self.grass_task.get_error_msg()
  1980. if msg:
  1981. gcmd.GError(msg + '\n\n' +
  1982. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  1983. return True
  1984. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  1985. self.mf.CentreOnScreen()
  1986. self.mf.Show(True)
  1987. self.SetTopWindow(self.mf)
  1988. return True
  1989. if __name__ == "__main__":
  1990. import gettext
  1991. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1992. if len(sys.argv) == 1:
  1993. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1994. if sys.argv[1] != 'test':
  1995. q = wx.LogNull()
  1996. cmd = utils.split(sys.argv[1])
  1997. task = gtask.grassTask(gcmd.GetRealCmd(cmd[0]))
  1998. task.set_options(cmd[1:])
  1999. app = GrassGUIApp(task)
  2000. app.MainLoop()
  2001. else: #Test
  2002. # Test grassTask from within a GRASS session
  2003. if os.getenv("GISBASE") is not None:
  2004. task = gtask.grassTask("d.vect")
  2005. task.get_param('map')['value'] = "map_name"
  2006. task.get_flag('v')['value'] = True
  2007. task.get_param('layer')['value'] = 1
  2008. task.get_param('bcolor')['value'] = "red"
  2009. assert ' '.join(task.get_cmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  2010. # Test interface building with handmade grassTask,
  2011. # possibly outside of a GRASS session.
  2012. task = gtask.grassTask()
  2013. task.name = "TestTask"
  2014. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2015. task.keywords = ["grass","test","task"]
  2016. task.params = [
  2017. {
  2018. "name" : "text",
  2019. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2020. "label" : "Enter some text",
  2021. },{
  2022. "name" : "hidden_text",
  2023. "description" : "This text should not appear in the form",
  2024. "hidden" : True
  2025. },{
  2026. "name" : "text_default",
  2027. "description" : "Enter text to override the default",
  2028. "default" : "default text"
  2029. },{
  2030. "name" : "text_prefilled",
  2031. "description" : "You should see a friendly welcome message here",
  2032. "value" : "hello, world"
  2033. },{
  2034. "name" : "plain_color",
  2035. "description" : "This is a plain color, and it is a compulsory parameter",
  2036. "required" : False,
  2037. "gisprompt" : True,
  2038. "prompt" : "color"
  2039. },{
  2040. "name" : "transparent_color",
  2041. "description" : "This color becomes transparent when set to none",
  2042. "guisection" : "tab",
  2043. "gisprompt" : True,
  2044. "prompt" : "color"
  2045. },{
  2046. "name" : "multi",
  2047. "description" : "A multiple selection",
  2048. 'default': u'red,green,blue',
  2049. 'gisprompt': False,
  2050. 'guisection': 'tab',
  2051. 'multiple': u'yes',
  2052. 'type': u'string',
  2053. 'value': '',
  2054. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  2055. },{
  2056. "name" : "single",
  2057. "description" : "A single multiple-choice selection",
  2058. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2059. "guisection" : "tab"
  2060. },{
  2061. "name" : "large_multi",
  2062. "description" : "A large multiple selection",
  2063. "gisprompt" : False,
  2064. "multiple" : "yes",
  2065. # values must be an array of strings
  2066. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values())
  2067. },{
  2068. "name" : "a_file",
  2069. "description" : "A file selector",
  2070. "gisprompt" : True,
  2071. "element" : "file"
  2072. }
  2073. ]
  2074. task.flags = [
  2075. {
  2076. "name" : "a",
  2077. "description" : "Some flag, will appear in Main since it is required",
  2078. "required" : True
  2079. },{
  2080. "name" : "b",
  2081. "description" : "pre-filled flag, will appear in options since it is not required",
  2082. "value" : True
  2083. },{
  2084. "name" : "hidden_flag",
  2085. "description" : "hidden flag, should not be changeable",
  2086. "hidden" : "yes",
  2087. "value" : True
  2088. }
  2089. ]
  2090. q = wx.LogNull()
  2091. GrassGUIApp(task).MainLoop()