forms.py 105 KB

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