forms.py 111 KB

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