forms.py 95 KB

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