forms.py 128 KB

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