forms.py 126 KB

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