forms.py 123 KB

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