forms.py 116 KB

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