forms.py 106 KB

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