forms.py 114 KB

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