forms.py 119 KB

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