forms.py 106 KB

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