frame.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. """!
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011 by Anna Kratochvilova, and the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  11. @author Martin Landa <landa.martin gmail.com> (mentor)
  12. """
  13. import os
  14. import sys
  15. import textwrap
  16. import Queue
  17. from math import sin, cos, pi
  18. try:
  19. import Image as PILImage
  20. havePILImage = True
  21. except ImportError:
  22. havePILImage = False
  23. if __name__ == "__main__":
  24. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  25. from core import globalvar
  26. import wx
  27. try:
  28. import wx.lib.agw.flatnotebook as fnb
  29. except ImportError:
  30. import wx.lib.flatnotebook as fnb
  31. import grass.script as grass
  32. from gui_core.menu import Menu
  33. from gui_core.goutput import CmdThread, EVT_CMD_DONE
  34. from psmap.toolbars import PsMapToolbar
  35. from core.gcmd import RunCommand, GError, GMessage
  36. from core.settings import UserSettings
  37. from gui_core.forms import GUI
  38. from psmap.menudata import PsMapData
  39. from psmap.dialogs import *
  40. class PsMapFrame(wx.Frame):
  41. def __init__(self, parent = None, id = wx.ID_ANY,
  42. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  43. """!Main window of ps.map GUI
  44. @param parent parent window
  45. @param id window id
  46. @param title window title
  47. @param kwargs wx.Frames' arguments
  48. """
  49. self.parent = parent
  50. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  51. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  52. #menubar
  53. self.menubar = Menu(parent = self, data = PsMapData())
  54. self.SetMenuBar(self.menubar)
  55. #toolbar
  56. self.toolbar = PsMapToolbar(parent = self)
  57. self.SetToolBar(self.toolbar)
  58. self.actionOld = self.toolbar.action['id']
  59. self.iconsize = (16, 16)
  60. #satusbar
  61. self.statusbar = self.CreateStatusBar(number = 1)
  62. # mouse attributes -- position on the screen, begin and end of
  63. # dragging, and type of drawing
  64. self.mouse = {
  65. 'begin': [0, 0], # screen coordinates
  66. 'end' : [0, 0],
  67. 'use' : "pointer",
  68. }
  69. # available cursors
  70. self.cursors = {
  71. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  72. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  73. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  74. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  75. }
  76. # pen and brush
  77. self.pen = {
  78. 'paper': wx.Pen(colour = "BLACK", width = 1),
  79. 'margins': wx.Pen(colour = "GREY", width = 1),
  80. 'map': wx.Pen(colour = wx.Color(86, 122, 17), width = 2),
  81. 'rasterLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  82. 'vectorLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  83. 'mapinfo': wx.Pen(colour = wx.Color(5, 184, 249), width = 2),
  84. 'scalebar': wx.Pen(colour = wx.Color(150, 150, 150), width = 2),
  85. 'image': wx.Pen(colour = wx.Color(255, 150, 50), width = 2),
  86. 'northArrow': wx.Pen(colour = wx.Color(200, 200, 200), width = 2),
  87. 'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
  88. 'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
  89. 'resize': wx.Pen(colour = 'BLACK', width = 1)
  90. }
  91. self.brush = {
  92. 'paper': wx.WHITE_BRUSH,
  93. 'margins': wx.TRANSPARENT_BRUSH,
  94. 'map': wx.Brush(wx.Color(151, 214, 90)),
  95. 'rasterLegend': wx.Brush(wx.Color(250, 247, 112)),
  96. 'vectorLegend': wx.Brush(wx.Color(250, 247, 112)),
  97. 'mapinfo': wx.Brush(wx.Color(127, 222, 252)),
  98. 'scalebar': wx.Brush(wx.Color(200, 200, 200)),
  99. 'image': wx.Brush(wx.Color(255, 200, 50)),
  100. 'northArrow': wx.Brush(wx.Color(255, 255, 255)),
  101. 'box': wx.TRANSPARENT_BRUSH,
  102. 'select':wx.TRANSPARENT_BRUSH,
  103. 'resize': wx.BLACK_BRUSH
  104. }
  105. # list of objects to draw
  106. self.objectId = []
  107. # instructions
  108. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  109. # open dialogs
  110. self.openDialogs = dict()
  111. self.pageId = wx.NewId()
  112. #current page of flatnotebook
  113. self.currentPage = 0
  114. #canvas for draft mode
  115. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  116. brush = self.brush, cursors = self.cursors,
  117. instruction = self.instruction, openDialogs = self.openDialogs,
  118. pageId = self.pageId, objectId = self.objectId,
  119. preview = False)
  120. self.canvas.SetCursor(self.cursors["default"])
  121. self.getInitMap()
  122. # image path
  123. env = grass.gisenv()
  124. self.imgName = grass.tempfile()
  125. #canvas for preview
  126. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  127. pen = self.pen, brush = self.brush, preview = True)
  128. # set WIND_OVERRIDE
  129. grass.use_temp_region()
  130. # create queues
  131. self.requestQ = Queue.Queue()
  132. self.resultQ = Queue.Queue()
  133. # thread
  134. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  135. self._layout()
  136. self.SetMinSize(wx.Size(750, 600))
  137. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  138. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  139. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  140. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  141. if not havePILImage:
  142. wx.CallAfter(self._showErrMsg)
  143. def _showErrMsg(self):
  144. """!Show error message (missing preview)
  145. """
  146. GError(parent = self,
  147. message = _("Python Imaging Library is not available.\n"
  148. "'Preview' functionality won't work."),
  149. showTraceback = False)
  150. def _layout(self):
  151. """!Do layout
  152. """
  153. mainSizer = wx.BoxSizer(wx.VERTICAL)
  154. if globalvar.hasAgw:
  155. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  156. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  157. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  158. else:
  159. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  160. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  161. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  162. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  163. self.book.AddPage(self.canvas, "Draft mode")
  164. self.book.AddPage(self.previewCanvas, "Preview")
  165. self.book.SetSelection(0)
  166. mainSizer.Add(self.book,1, wx.EXPAND)
  167. self.SetSizer(mainSizer)
  168. mainSizer.Fit(self)
  169. def InstructionFile(self):
  170. """!Creates mapping instructions"""
  171. return str(self.instruction)
  172. def OnPSFile(self, event):
  173. """!Generate PostScript"""
  174. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  175. if filename:
  176. self.PSFile(filename)
  177. def OnPsMapDialog(self, event):
  178. """!Launch ps.map dialog
  179. """
  180. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  181. def OnPDFFile(self, event):
  182. """!Generate PDF from PS with ps2pdf if available"""
  183. try:
  184. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  185. p.stderr.close()
  186. except OSError:
  187. GMessage(parent = self,
  188. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  189. return
  190. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  191. if filename:
  192. self.PSFile(filename, pdf = True)
  193. def OnPreview(self, event):
  194. """!Run ps.map and show result"""
  195. self.PSFile()
  196. def PSFile(self, filename = None, pdf = False):
  197. """!Create temporary instructions file and run ps.map with output = filename"""
  198. instrFile = grass.tempfile()
  199. instrFileFd = open(instrFile, mode = 'w')
  200. instrFileFd.write(self.InstructionFile())
  201. instrFileFd.flush()
  202. instrFileFd.close()
  203. temp = False
  204. regOld = grass.region()
  205. if pdf:
  206. pdfname = filename
  207. else:
  208. pdfname = None
  209. #preview or pdf
  210. if not filename or (filename and pdf):
  211. temp = True
  212. filename = grass.tempfile()
  213. if not pdf: # lower resolution for preview
  214. if self.instruction.FindInstructionByType('map'):
  215. mapId = self.instruction.FindInstructionByType('map').id
  216. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  217. height = self.instruction[mapId]['rect'][3])
  218. cmd = ['ps.map', '--overwrite']
  219. if os.path.splitext(filename)[1] == '.eps':
  220. cmd.append('-e')
  221. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  222. cmd.append('-r')
  223. cmd.append('input=%s' % instrFile)
  224. cmd.append('output=%s' % filename)
  225. if pdf:
  226. self.SetStatusText(_('Generating PDF...'), 0)
  227. elif not temp:
  228. self.SetStatusText(_('Generating PostScript...'), 0)
  229. else:
  230. self.SetStatusText(_('Generating preview...'), 0)
  231. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  232. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  233. def OnCmdDone(self, event):
  234. """!ps.map process finished"""
  235. if event.returncode != 0:
  236. GMessage(parent = self,
  237. message = _("Ps.map exited with return code %s") % event.returncode)
  238. grass.try_remove(event.userData['instrFile'])
  239. if event.userData['temp']:
  240. grass.try_remove(event.userData['filename'])
  241. return
  242. if event.userData['pdfname']:
  243. try:
  244. proc = grass.Popen(['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  245. event.userData['filename'], event.userData['pdfname']])
  246. ret = proc.wait()
  247. if ret > 0:
  248. GMessage(parent = self,
  249. message = _("ps2pdf exited with return code %s") % ret)
  250. except OSError, e:
  251. GError(parent = self,
  252. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  253. # show preview only when user doesn't want to create ps or pdf
  254. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  255. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  256. ## wx.BusyInfo does not display the message
  257. ## busy = wx.BusyInfo(message = "Generating preview, wait please", parent = self)
  258. try:
  259. im = PILImage.open(event.userData['filename'])
  260. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  261. im = im.rotate(270)
  262. im.save(self.imgName, format = 'PNG')
  263. except IOError, e:
  264. GError(parent = self,
  265. message = _("Unable to generate preview. %s") % e)
  266. return
  267. rect = self.previewCanvas.ImageRect()
  268. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  269. self.previewCanvas.DrawImage(rect = rect)
  270. ## busy.Destroy()
  271. self.SetStatusText(_('Preview generated'), 0)
  272. self.book.SetSelection(1)
  273. self.currentPage = 1
  274. grass.try_remove(event.userData['instrFile'])
  275. if event.userData['temp']:
  276. grass.try_remove(event.userData['filename'])
  277. def getFile(self, wildcard):
  278. suffix = []
  279. for filter in wildcard.split('|')[1::2]:
  280. s = filter.strip('*').split('.')[1]
  281. if s:
  282. s = '.' + s
  283. suffix.append(s)
  284. raster = self.instruction.FindInstructionByType('raster')
  285. if raster:
  286. rasterId = raster.id
  287. else:
  288. rasterId = None
  289. if rasterId and self.instruction[rasterId]['raster']:
  290. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  291. else:
  292. mapName = ''
  293. filename = ''
  294. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  295. defaultFile = mapName, wildcard = wildcard,
  296. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  297. if dlg.ShowModal() == wx.ID_OK:
  298. filename = dlg.GetPath()
  299. suffix = suffix[dlg.GetFilterIndex()]
  300. if not os.path.splitext(filename)[1]:
  301. filename = filename + suffix
  302. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  303. filename = os.path.splitext(filename)[0] + suffix
  304. dlg.Destroy()
  305. return filename
  306. def OnInstructionFile(self, event):
  307. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  308. if filename:
  309. instrFile = open(filename, "w")
  310. instrFile.write(self.InstructionFile())
  311. instrFile.close()
  312. def OnLoadFile(self, event):
  313. """!Load file and read instructions"""
  314. #find file
  315. filename = ''
  316. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  317. defaultFile = '', wildcard = "All files (*.*)|*.*",
  318. style = wx.CHANGE_DIR|wx.OPEN)
  319. if dlg.ShowModal() == wx.ID_OK:
  320. filename = dlg.GetPath()
  321. dlg.Destroy()
  322. if not filename:
  323. return
  324. # load instructions
  325. readObjectId = []
  326. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  327. ok = readInstruction.Read(filename)
  328. if not ok:
  329. GMessage(_("Failed to read file %s.") % filename)
  330. else:
  331. self.instruction = self.canvas.instruction = readInstruction
  332. self.objectId = self.canvas.objectId = readObjectId
  333. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  334. self.canvas.UpdateMapLabel()
  335. self.canvas.dragId = -1
  336. self.canvas.Clear()
  337. self.canvas.SetPage()
  338. #self.canvas.ZoomAll()
  339. self.DialogDataChanged(self.objectId)
  340. def OnPageSetup(self, event = None):
  341. """!Specify paper size, margins and orientation"""
  342. id = self.instruction.FindInstructionByType('page').id
  343. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  344. dlg.CenterOnScreen()
  345. val = dlg.ShowModal()
  346. if val == wx.ID_OK:
  347. self.canvas.SetPage()
  348. self.getInitMap()
  349. self.canvas.RecalculatePosition(ids = self.objectId)
  350. dlg.Destroy()
  351. def OnPointer(self, event):
  352. self.toolbar.OnTool(event)
  353. self.mouse["use"] = "pointer"
  354. self.canvas.SetCursor(self.cursors["default"])
  355. self.previewCanvas.SetCursor(self.cursors["default"])
  356. def OnPan(self, event):
  357. self.toolbar.OnTool(event)
  358. self.mouse["use"] = "pan"
  359. self.canvas.SetCursor(self.cursors["hand"])
  360. self.previewCanvas.SetCursor(self.cursors["hand"])
  361. def OnZoomIn(self, event):
  362. self.toolbar.OnTool(event)
  363. self.mouse["use"] = "zoomin"
  364. self.canvas.SetCursor(self.cursors["cross"])
  365. self.previewCanvas.SetCursor(self.cursors["cross"])
  366. def OnZoomOut(self, event):
  367. self.toolbar.OnTool(event)
  368. self.mouse["use"] = "zoomout"
  369. self.canvas.SetCursor(self.cursors["cross"])
  370. self.previewCanvas.SetCursor(self.cursors["cross"])
  371. def OnZoomAll(self, event):
  372. self.mouseOld = self.mouse['use']
  373. if self.currentPage == 0:
  374. self.cursorOld = self.canvas.GetCursor()
  375. else:
  376. self.cursorOld = self.previewCanvas.GetCursor()
  377. self.previewCanvas.GetCursor()
  378. self.mouse["use"] = "zoomin"
  379. if self.currentPage == 0:
  380. self.canvas.ZoomAll()
  381. else:
  382. self.previewCanvas.ZoomAll()
  383. self.mouse["use"] = self.mouseOld
  384. if self.currentPage == 0:
  385. self.canvas.SetCursor(self.cursorOld)
  386. else:
  387. self.previewCanvas.SetCursor(self.cursorOld)
  388. def OnAddMap(self, event, notebook = False):
  389. """!Add or edit map frame"""
  390. if event is not None:
  391. if event.GetId() != self.toolbar.action['id']:
  392. self.actionOld = self.toolbar.action['id']
  393. self.mouseOld = self.mouse['use']
  394. self.cursorOld = self.canvas.GetCursor()
  395. self.toolbar.OnTool(event)
  396. if self.instruction.FindInstructionByType('map'):
  397. mapId = self.instruction.FindInstructionByType('map').id
  398. else: mapId = None
  399. id = [mapId, None, None]
  400. if notebook:
  401. if self.instruction.FindInstructionByType('vector'):
  402. vectorId = self.instruction.FindInstructionByType('vector').id
  403. else: vectorId = None
  404. if self.instruction.FindInstructionByType('raster'):
  405. rasterId = self.instruction.FindInstructionByType('raster').id
  406. else: rasterId = None
  407. id[1] = rasterId
  408. id[2] = vectorId
  409. if mapId: # map exists
  410. self.toolbar.ToggleTool(self.actionOld, True)
  411. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  412. self.toolbar.action['id'] = self.actionOld
  413. try:
  414. self.canvas.SetCursor(self.cursorOld)
  415. except AttributeError:
  416. pass
  417. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  418. ## notebook = notebook)
  419. ## dlg.ShowModal()
  420. if notebook:
  421. #check map, raster, vector and save, destroy them
  422. if 'map' in self.openDialogs:
  423. self.openDialogs['map'].OnOK(event = None)
  424. if 'raster' in self.openDialogs:
  425. self.openDialogs['raster'].OnOK(event = None)
  426. if 'vector' in self.openDialogs:
  427. self.openDialogs['vector'].OnOK(event = None)
  428. if 'mapNotebook' not in self.openDialogs:
  429. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  430. notebook = notebook)
  431. self.openDialogs['mapNotebook'] = dlg
  432. self.openDialogs['mapNotebook'].Show()
  433. else:
  434. if 'mapNotebook' in self.openDialogs:
  435. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  436. else:
  437. if 'map' not in self.openDialogs:
  438. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  439. notebook = notebook)
  440. self.openDialogs['map'] = dlg
  441. self.openDialogs['map'].Show()
  442. else: # sofar no map
  443. self.mouse["use"] = "addMap"
  444. self.canvas.SetCursor(self.cursors["cross"])
  445. if self.currentPage == 1:
  446. self.book.SetSelection(0)
  447. self.currentPage = 0
  448. def OnAddRaster(self, event):
  449. """!Add raster map"""
  450. if self.instruction.FindInstructionByType('raster'):
  451. id = self.instruction.FindInstructionByType('raster').id
  452. else: id = None
  453. if self.instruction.FindInstructionByType('map'):
  454. mapId = self.instruction.FindInstructionByType('map').id
  455. else: mapId = None
  456. if not id:
  457. if not mapId:
  458. GMessage(message = _("Please, create map frame first."))
  459. return
  460. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  461. ## dlg.ShowModal()
  462. if 'mapNotebook' in self.openDialogs:
  463. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  464. else:
  465. if 'raster' not in self.openDialogs:
  466. dlg = RasterDialog(self, id = id, settings = self.instruction)
  467. self.openDialogs['raster'] = dlg
  468. self.openDialogs['raster'].Show()
  469. def OnAddVect(self, event):
  470. """!Add vector map"""
  471. if self.instruction.FindInstructionByType('vector'):
  472. id = self.instruction.FindInstructionByType('vector').id
  473. else: id = None
  474. if self.instruction.FindInstructionByType('map'):
  475. mapId = self.instruction.FindInstructionByType('map').id
  476. else: mapId = None
  477. if not id:
  478. if not mapId:
  479. GMessage(message = _("Please, create map frame first."))
  480. return
  481. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  482. ## dlg.ShowModal()
  483. if 'mapNotebook' in self.openDialogs:
  484. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  485. else:
  486. if 'vector' not in self.openDialogs:
  487. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  488. self.openDialogs['vector'] = dlg
  489. self.openDialogs['vector'].Show()
  490. def OnAddScalebar(self, event):
  491. """!Add scalebar"""
  492. if projInfo()['proj'] == 'll':
  493. GMessage(message = _("Scalebar is not appropriate for this projection"))
  494. return
  495. if self.instruction.FindInstructionByType('scalebar'):
  496. id = self.instruction.FindInstructionByType('scalebar').id
  497. else: id = None
  498. if 'scalebar' not in self.openDialogs:
  499. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  500. self.openDialogs['scalebar'] = dlg
  501. self.openDialogs['scalebar'].Show()
  502. def OnAddLegend(self, event, page = 0):
  503. """!Add raster or vector legend"""
  504. if self.instruction.FindInstructionByType('rasterLegend'):
  505. idR = self.instruction.FindInstructionByType('rasterLegend').id
  506. else: idR = None
  507. if self.instruction.FindInstructionByType('vectorLegend'):
  508. idV = self.instruction.FindInstructionByType('vectorLegend').id
  509. else: idV = None
  510. if 'rasterLegend' not in self.openDialogs:
  511. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  512. self.openDialogs['rasterLegend'] = dlg
  513. self.openDialogs['vectorLegend'] = dlg
  514. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  515. self.openDialogs['rasterLegend'].Show()
  516. def OnAddMapinfo(self, event):
  517. if self.instruction.FindInstructionByType('mapinfo'):
  518. id = self.instruction.FindInstructionByType('mapinfo').id
  519. else: id = None
  520. if 'mapinfo' not in self.openDialogs:
  521. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  522. self.openDialogs['mapinfo'] = dlg
  523. self.openDialogs['mapinfo'].Show()
  524. def OnAddImage(self, event, id = None):
  525. """!Show dialog for image adding and editing"""
  526. position = None
  527. if 'image' in self.openDialogs:
  528. position = self.openDialogs['image'].GetPosition()
  529. self.openDialogs['image'].OnApply(event = None)
  530. self.openDialogs['image'].Destroy()
  531. dlg = ImageDialog(self, id = id, settings = self.instruction)
  532. self.openDialogs['image'] = dlg
  533. if position:
  534. dlg.SetPosition(position)
  535. dlg.Show()
  536. def OnAddNorthArrow(self, event, id = None):
  537. """!Show dialog for north arrow adding and editing"""
  538. if self.instruction.FindInstructionByType('northArrow'):
  539. id = self.instruction.FindInstructionByType('northArrow').id
  540. else: id = None
  541. if 'northArrow' not in self.openDialogs:
  542. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  543. self.openDialogs['northArrow'] = dlg
  544. self.openDialogs['northArrow'].Show()
  545. def OnAddText(self, event, id = None):
  546. """!Show dialog for text adding and editing"""
  547. position = None
  548. if 'text' in self.openDialogs:
  549. position = self.openDialogs['text'].GetPosition()
  550. self.openDialogs['text'].OnApply(event = None)
  551. self.openDialogs['text'].Destroy()
  552. dlg = TextDialog(self, id = id, settings = self.instruction)
  553. self.openDialogs['text'] = dlg
  554. if position:
  555. dlg.SetPosition(position)
  556. dlg.Show()
  557. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  558. """!computes bounding box of rotated text, not very precisely"""
  559. w, h = textExtent
  560. rotation = float(rotation)/180*pi
  561. H = float(w) * sin(rotation)
  562. W = float(w) * cos(rotation)
  563. X, Y = x, y
  564. if pi/2 < rotation <= 3*pi/2:
  565. X = x + W
  566. if 0 < rotation < pi:
  567. Y = y - H
  568. if rotation == 0:
  569. return wx.Rect(x,y, *textExtent)
  570. else:
  571. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  572. def makePSFont(self, textDict):
  573. """!creates a wx.Font object from selected postscript font. To be
  574. used for estimating bounding rectangle of text"""
  575. fontsize = textDict['fontsize'] * self.canvas.currScale
  576. fontface = textDict['font'].split('-')[0]
  577. try:
  578. fontstyle = textDict['font'].split('-')[1]
  579. except IndexError:
  580. fontstyle = ''
  581. if fontface == "Times":
  582. family = wx.FONTFAMILY_ROMAN
  583. face = "times"
  584. elif fontface == "Helvetica":
  585. family = wx.FONTFAMILY_SWISS
  586. face = 'helvetica'
  587. elif fontface == "Courier":
  588. family = wx.FONTFAMILY_TELETYPE
  589. face = 'courier'
  590. else:
  591. family = wx.FONTFAMILY_DEFAULT
  592. face = ''
  593. style = wx.FONTSTYLE_NORMAL
  594. weight = wx.FONTWEIGHT_NORMAL
  595. if 'Oblique' in fontstyle:
  596. style = wx.FONTSTYLE_SLANT
  597. if 'Italic' in fontstyle:
  598. style = wx.FONTSTYLE_ITALIC
  599. if 'Bold' in fontstyle:
  600. weight = wx.FONTWEIGHT_BOLD
  601. try:
  602. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  603. weight = weight, face = face)
  604. except:
  605. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  606. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  607. return fn
  608. def getTextExtent(self, textDict):
  609. """!Estimates bounding rectangle of text"""
  610. #fontsize = str(fontsize if fontsize >= 4 else 4)
  611. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  612. fn = self.makePSFont(textDict)
  613. try:
  614. dc.SetFont(fn)
  615. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  616. return (w,h)
  617. except:
  618. return (0,0)
  619. def getInitMap(self):
  620. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  621. instrFile = grass.tempfile()
  622. instrFileFd = open(instrFile, mode = 'w')
  623. instrFileFd.write(self.InstructionFile())
  624. instrFileFd.flush()
  625. instrFileFd.close()
  626. page = self.instruction.FindInstructionByType('page')
  627. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  628. grass.try_remove(instrFile)
  629. region = grass.region()
  630. units = UnitConversion(self)
  631. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  632. scale = mapInitRect.Get()[2]/realWidth
  633. initMap = self.instruction.FindInstructionByType('initMap')
  634. if initMap:
  635. id = initMap.id
  636. else:
  637. id = None
  638. if not id:
  639. id = wx.NewId()
  640. initMap = InitMap(id)
  641. self.instruction.AddInstruction(initMap)
  642. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  643. def OnDelete(self, event):
  644. if self.canvas.dragId != -1 and self.currentPage == 0:
  645. if self.instruction[self.canvas.dragId].type == 'map':
  646. self.deleteObject(self.canvas.dragId)
  647. self.getInitMap()
  648. self.canvas.RecalculateEN()
  649. else:
  650. self.deleteObject(self.canvas.dragId)
  651. def deleteObject(self, id):
  652. """!Deletes object, his id and redraws"""
  653. #delete from canvas
  654. self.canvas.pdcObj.RemoveId(id)
  655. if id == self.canvas.dragId:
  656. self.canvas.pdcTmp.RemoveAll()
  657. self.canvas.dragId = -1
  658. self.canvas.Refresh()
  659. # delete from instructions
  660. del self.instruction[id]
  661. def DialogDataChanged(self, id):
  662. ids = id
  663. if type(id) == int:
  664. ids = [id]
  665. for id in ids:
  666. itype = self.instruction[id].type
  667. if itype in ('scalebar', 'mapinfo', 'image'):
  668. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  669. self.canvas.UpdateLabel(itype = itype, id = id)
  670. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  671. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  672. self.canvas.RedrawSelectBox(id)
  673. if itype == 'northArrow':
  674. self.canvas.UpdateLabel(itype = itype, id = id)
  675. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  676. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  677. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  678. self.canvas.RedrawSelectBox(id)
  679. if itype == 'text':
  680. if self.instruction[id]['rotate']:
  681. rot = float(self.instruction[id]['rotate'])
  682. else:
  683. rot = 0
  684. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  685. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  686. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  687. #computes text coordinates according to reference point, not precisely
  688. if self.instruction[id]['ref'].split()[0] == 'lower':
  689. self.instruction[id]['coords'][1] -= extent[1]
  690. elif self.instruction[id]['ref'].split()[0] == 'center':
  691. self.instruction[id]['coords'][1] -= extent[1]/2
  692. if self.instruction[id]['ref'].split()[1] == 'right':
  693. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  694. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  695. elif self.instruction[id]['ref'].split()[1] == 'center':
  696. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  697. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  698. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  699. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  700. coords = self.instruction[id]['coords']
  701. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  702. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  703. textDict = self.instruction[id].GetInstruction(),
  704. coords = coords, bounds = bounds)
  705. self.canvas.RedrawSelectBox(id)
  706. if itype in ('map', 'vector', 'raster'):
  707. if itype == 'raster':#set resolution
  708. info = grass.raster_info(self.instruction[id]['raster'])
  709. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  710. # change current raster in raster legend
  711. if 'rasterLegend' in self.openDialogs:
  712. self.openDialogs['rasterLegend'].updateDialog()
  713. id = self.instruction.FindInstructionByType('map').id
  714. #check resolution
  715. if itype == 'raster':
  716. SetResolution(dpi = self.instruction[id]['resolution'],
  717. width = self.instruction[id]['rect'].width,
  718. height = self.instruction[id]['rect'].height)
  719. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  720. canvasToPaper = False)
  721. self.canvas.RecalculateEN()
  722. self.canvas.UpdateMapLabel()
  723. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  724. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  725. # redraw select box
  726. self.canvas.RedrawSelectBox(id)
  727. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  728. # redraw to get map to the bottom layer
  729. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  730. if itype == 'rasterLegend':
  731. if self.instruction[id]['rLegend']:
  732. self.canvas.UpdateLabel(itype = itype, id = id)
  733. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  734. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  735. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  736. self.canvas.RedrawSelectBox(id)
  737. else:
  738. self.deleteObject(id)
  739. if itype == 'vectorLegend':
  740. if not self.instruction.FindInstructionByType('vector'):
  741. self.deleteObject(id)
  742. elif self.instruction[id]['vLegend']:
  743. self.canvas.UpdateLabel(itype = itype, id = id)
  744. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  745. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  746. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  747. self.canvas.RedrawSelectBox(id)
  748. else:
  749. self.deleteObject(id)
  750. def OnPageChanged(self, event):
  751. """!Flatnotebook page has changed"""
  752. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  753. def OnPageChanging(self, event):
  754. """!Flatnotebook page is changing"""
  755. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  756. event.Veto()
  757. def OnHelp(self, event):
  758. """!Show help"""
  759. if self.parent and self.parent.GetName() == 'LayerManager':
  760. log = self.parent.GetLogWindow()
  761. log.RunCmd(['g.manual',
  762. 'entry=wxGUI.PsMap'])
  763. else:
  764. RunCommand('g.manual',
  765. quiet = True,
  766. entry = 'wxGUI.PsMap')
  767. def OnAbout(self, event):
  768. """!Display About window"""
  769. info = wx.AboutDialogInfo()
  770. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  771. info.SetName(_('wxGUI Cartographic Composer'))
  772. info.SetWebSite('http://grass.osgeo.org')
  773. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  774. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  775. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  776. wx.AboutBox(info)
  777. def OnCloseWindow(self, event):
  778. """!Close window"""
  779. try:
  780. os.remove(self.imgName)
  781. except OSError:
  782. pass
  783. grass.set_raise_on_error(False)
  784. self.Destroy()
  785. class PsMapBufferedWindow(wx.Window):
  786. """!A buffered window class.
  787. @param parent parent window
  788. @param kwargs other wx.Window parameters
  789. """
  790. def __init__(self, parent, id = wx.ID_ANY,
  791. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  792. **kwargs):
  793. wx.Window.__init__(self, parent, id = id, style = style)
  794. self.parent = parent
  795. self.FitInside()
  796. # store an off screen empty bitmap for saving to file
  797. self._buffer = None
  798. # indicates whether or not a resize event has taken place
  799. self.resize = False
  800. self.mouse = kwargs['mouse']
  801. self.cursors = kwargs['cursors']
  802. self.preview = kwargs['preview']
  803. self.pen = kwargs['pen']
  804. self.brush = kwargs['brush']
  805. if kwargs.has_key('instruction'):
  806. self.instruction = kwargs['instruction']
  807. if kwargs.has_key('openDialogs'):
  808. self.openDialogs = kwargs['openDialogs']
  809. if kwargs.has_key('pageId'):
  810. self.pageId = kwargs['pageId']
  811. if kwargs.has_key('objectId'):
  812. self.objectId = kwargs['objectId']
  813. #labels
  814. self.itemLabelsDict = { 'map': 'MAP FRAME',
  815. 'rasterLegend': 'RASTER LEGEND',
  816. 'vectorLegend': 'VECTOR LEGEND',
  817. 'mapinfo': 'MAP INFO',
  818. 'scalebar': 'SCALE BAR',
  819. 'image': 'IMAGE',
  820. 'northArrow': 'NORTH ARROW'}
  821. self.itemLabels = {}
  822. # define PseudoDC
  823. self.pdc = wx.PseudoDC()
  824. self.pdcObj = wx.PseudoDC()
  825. self.pdcPaper = wx.PseudoDC()
  826. self.pdcTmp = wx.PseudoDC()
  827. self.pdcImage = wx.PseudoDC()
  828. dc = wx.ClientDC(self)
  829. self.font = dc.GetFont()
  830. self.SetClientSize((700,510))#?
  831. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  832. self.idBoxTmp = wx.NewId()
  833. self.idZoomBoxTmp = wx.NewId()
  834. self.idResizeBoxTmp = wx.NewId()
  835. self.dragId = -1
  836. if self.preview:
  837. self.image = None
  838. self.imageId = 2000
  839. self.imgName = self.parent.imgName
  840. self.currScale = None
  841. self.Clear()
  842. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  843. self.Bind(wx.EVT_PAINT, self.OnPaint)
  844. self.Bind(wx.EVT_SIZE, self.OnSize)
  845. self.Bind(wx.EVT_IDLE, self.OnIdle)
  846. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  847. def Clear(self):
  848. """!Clear canvas and set paper
  849. """
  850. bg = wx.LIGHT_GREY_BRUSH
  851. self.pdcPaper.BeginDrawing()
  852. self.pdcPaper.SetBackground(bg)
  853. self.pdcPaper.Clear()
  854. self.pdcPaper.EndDrawing()
  855. self.pdcObj.RemoveAll()
  856. self.pdcTmp.RemoveAll()
  857. if not self.preview:
  858. self.SetPage()
  859. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  860. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  861. units = UnitConversion(self)
  862. fromU = 'pixel'
  863. toU = 'inch'
  864. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  865. pRectx, pRecty = pRect.x, pRect.y
  866. scale = 1/self.currScale
  867. if not canvasToPaper: # paper -> canvas
  868. fromU = 'inch'
  869. toU = 'pixel'
  870. scale = self.currScale
  871. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  872. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  873. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  874. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  875. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  876. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  877. return wx.Rect2D(X, Y, Width, Height)
  878. def SetPage(self):
  879. """!Sets and changes page, redraws paper"""
  880. page = self.instruction[self.pageId]
  881. if not page:
  882. page = PageSetup(id = self.pageId)
  883. self.instruction.AddInstruction(page)
  884. ppi = wx.ClientDC(self).GetPPI()
  885. cW, cH = self.GetClientSize()
  886. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  887. if self.currScale is None:
  888. self.currScale = min(cW/pW, cH/pH)
  889. pW = pW * self.currScale
  890. pH = pH * self.currScale
  891. x = cW/2 - pW/2
  892. y = cH/2 - pH/2
  893. self.DrawPaper(wx.Rect(x, y, pW, pH))
  894. def modifyRectangle(self, r):
  895. """! Recalculates rectangle not to have negative size"""
  896. if r.GetWidth() < 0:
  897. r.SetX(r.GetX() + r.GetWidth())
  898. if r.GetHeight() < 0:
  899. r.SetY(r.GetY() + r.GetHeight())
  900. r.SetWidth(abs(r.GetWidth()))
  901. r.SetHeight(abs(r.GetHeight()))
  902. return r
  903. def RecalculateEN(self):
  904. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  905. try:
  906. mapId = self.instruction.FindInstructionByType('map').id
  907. except AttributeError:
  908. mapId = self.instruction.FindInstructionByType('initMap').id
  909. for itemType in ('text', 'image', 'northArrow'):
  910. items = self.instruction.FindInstructionByType(itemType, list = True)
  911. for item in items:
  912. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[item.id]['where'][0],
  913. y = self.instruction[item.id]['where'][1], paperToMap = True)
  914. self.instruction[item.id]['east'], self.instruction[item.id]['north'] = e, n
  915. def OnPaint(self, event):
  916. """!Draw pseudo DC to buffer
  917. """
  918. if not self._buffer:
  919. return
  920. dc = wx.BufferedPaintDC(self, self._buffer)
  921. # use PrepareDC to set position correctly
  922. self.PrepareDC(dc)
  923. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  924. dc.Clear()
  925. # draw paper
  926. if not self.preview:
  927. self.pdcPaper.DrawToDC(dc)
  928. # draw to the DC using the calculated clipping rect
  929. rgn = self.GetUpdateRegion()
  930. if not self.preview:
  931. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  932. else:
  933. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  934. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  935. def OnMouse(self, event):
  936. if event.GetWheelRotation() and UserSettings.Get(group = 'display',
  937. key = 'mouseWheelZoom',
  938. subkey = 'enabled'):
  939. zoom = event.GetWheelRotation()
  940. use = self.mouse['use']
  941. self.mouse['begin'] = event.GetPosition()
  942. if UserSettings.Get(group = 'display',
  943. key = 'mouseWheelZoom',
  944. subkey = 'selection'):
  945. zoom *= -1
  946. if zoom > 0:
  947. self.mouse['use'] = 'zoomin'
  948. else:
  949. self.mouse['use'] = 'zoomout'
  950. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  951. self.Zoom(zoomFactor, view)
  952. self.mouse['use'] = use
  953. if event.Moving():
  954. if self.mouse['use'] in ('pointer', 'resize'):
  955. pos = event.GetPosition()
  956. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  957. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  958. self.SetCursor(self.cursors["sizenwse"])
  959. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  960. else:
  961. self.parent.SetStatusText('', 0)
  962. self.SetCursor(self.cursors["default"])
  963. elif event.MiddleDown():
  964. self.mouse['begin'] = event.GetPosition()
  965. elif event.LeftDown():
  966. self.mouse['begin'] = event.GetPosition()
  967. self.begin = self.mouse['begin']
  968. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  969. pass
  970. #select
  971. if self.mouse['use'] == 'pointer':
  972. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  973. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  974. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  975. self.mouse['use'] = 'resize'
  976. # when resizing, proportions match region
  977. if self.instruction[self.dragId].type == 'map':
  978. self.constraint = False
  979. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  980. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  981. self.constraint = True
  982. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  983. elif found:
  984. self.dragId = found[0]
  985. self.RedrawSelectBox(self.dragId)
  986. if self.instruction[self.dragId].type != 'map':
  987. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  988. self.Refresh()
  989. else:
  990. self.dragId = -1
  991. self.pdcTmp.RemoveId(self.idBoxTmp)
  992. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  993. self.Refresh()
  994. elif event.Dragging() and event.MiddleIsDown():
  995. self.mouse['end'] = event.GetPosition()
  996. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  997. self.mouse['begin'] = event.GetPosition()
  998. elif event.Dragging() and event.LeftIsDown():
  999. #draw box when zooming, creating map
  1000. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  1001. self.mouse['end'] = event.GetPosition()
  1002. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1003. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1004. r = self.modifyRectangle(r)
  1005. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1006. pdctype = 'rect', bb = r)
  1007. # panning
  1008. if self.mouse["use"] == 'pan':
  1009. self.mouse['end'] = event.GetPosition()
  1010. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1011. self.mouse['begin'] = event.GetPosition()
  1012. #move object
  1013. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1014. self.mouse['end'] = event.GetPosition()
  1015. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1016. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1017. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1018. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1019. if self.instruction[self.dragId].type == 'text':
  1020. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1021. self.instruction[self.dragId]['coords'][1] + dy
  1022. self.begin = event.GetPosition()
  1023. self.Refresh()
  1024. # resize object
  1025. if self.mouse['use'] == 'resize':
  1026. type = self.instruction[self.dragId].type
  1027. pos = event.GetPosition()
  1028. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1029. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1030. diffX = pos[0] - self.mouse['begin'][0]
  1031. diffY = pos[1] - self.mouse['begin'][1]
  1032. # match given region
  1033. if self.constraint:
  1034. if width > height:
  1035. newWidth = width + diffX
  1036. newHeight = height + diffX * (float(height) / width)
  1037. else:
  1038. newWidth = width + diffY * (float(width) / height)
  1039. newHeight = height + diffY
  1040. else:
  1041. newWidth = width + diffX
  1042. newHeight = height + diffY
  1043. if newWidth < 10 or newHeight < 10:
  1044. return
  1045. bounds = wx.Rect(x, y, newWidth, newHeight)
  1046. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  1047. pdctype = 'rectText', bb = bounds)
  1048. self.RedrawSelectBox(self.dragId)
  1049. elif event.LeftUp():
  1050. # zoom in, zoom out
  1051. if self.mouse['use'] in ('zoomin','zoomout'):
  1052. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1053. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1054. self.Refresh()
  1055. zoomFactor, view = self.ComputeZoom(zoomR)
  1056. self.Zoom(zoomFactor, view)
  1057. # draw map frame
  1058. if self.mouse['use'] == 'addMap':
  1059. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1060. # too small rectangle, it's usually some mistake
  1061. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1062. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1063. self.Refresh()
  1064. return
  1065. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1066. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1067. rect = rectPaper)
  1068. self.openDialogs['map'] = dlg
  1069. self.openDialogs['map'].Show()
  1070. self.mouse['use'] = self.parent.mouseOld
  1071. self.SetCursor(self.parent.cursorOld)
  1072. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1073. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1074. self.parent.toolbar.action['id'] = self.parent.actionOld
  1075. # resize resizable objects (only map sofar)
  1076. if self.mouse['use'] == 'resize':
  1077. mapId = self.instruction.FindInstructionByType('map').id
  1078. if self.dragId == mapId:
  1079. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1080. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1081. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1082. self.instruction[mapId]['rect'] = newRectPaper
  1083. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1084. if self.instruction[mapId]['scaleType'] == 0:
  1085. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1086. map = self.instruction[mapId]['map'],
  1087. mapType = self.instruction[mapId]['mapType'],
  1088. rect = self.instruction[mapId]['rect'])
  1089. elif self.instruction[mapId]['scaleType'] == 1:
  1090. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1091. region = self.instruction[mapId]['region'],
  1092. rect = self.instruction[mapId]['rect'])
  1093. else:
  1094. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1095. rect = self.instruction[mapId]['rect'])
  1096. self.instruction[mapId]['rect'] = rect
  1097. self.instruction[mapId]['scale'] = scale
  1098. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1099. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1100. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1101. elif self.instruction[mapId]['scaleType'] == 3:
  1102. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1103. #check resolution
  1104. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1105. width = self.instruction[mapId]['rect'].width,
  1106. height = self.instruction[mapId]['rect'].height)
  1107. self.RedrawSelectBox(mapId)
  1108. self.Zoom(zoomFactor = 1, view = (0, 0))
  1109. self.mouse['use'] = 'pointer'
  1110. # recalculate the position of objects after dragging
  1111. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1112. if self.mouse['begin'] != event.GetPosition(): #for double click
  1113. self.RecalculatePosition(ids = [self.dragId])
  1114. if self.instruction[self.dragId].type in self.openDialogs:
  1115. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1116. # double click launches dialogs
  1117. elif event.LeftDClick():
  1118. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1119. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1120. 'scalebar': self.parent.OnAddScalebar, 'image': self.parent.OnAddImage,
  1121. 'northArrow' : self.parent.OnAddNorthArrow,
  1122. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1123. 'map': self.parent.OnAddMap}
  1124. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1125. 'scalebar': dict(event = None), 'image': dict(event = None, id = self.dragId),
  1126. 'northArrow': dict(event = None, id = self.dragId),
  1127. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1128. 'map': dict(event = None, notebook = True)}
  1129. type = self.instruction[self.dragId].type
  1130. itemCall[type](**itemArg[type])
  1131. def Pan(self, begin, end):
  1132. """!Move canvas while dragging.
  1133. @param begin x,y coordinates of first point
  1134. @param end x,y coordinates of second point
  1135. """
  1136. view = begin[0] - end[0], begin[1] - end[1]
  1137. zoomFactor = 1
  1138. self.Zoom(zoomFactor, view)
  1139. def RecalculatePosition(self, ids):
  1140. for id in ids:
  1141. itype = self.instruction[id].type
  1142. if itype == 'map':
  1143. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1144. canvasToPaper = True)
  1145. self.RecalculateEN()
  1146. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1147. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1148. canvasToPaper = True)
  1149. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1150. canvasToPaper = True)[:2]
  1151. if itype in ('image', 'northArrow'):
  1152. self.RecalculateEN()
  1153. elif itype == 'scalebar':
  1154. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1155. canvasToPaper = True)
  1156. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1157. elif itype == 'text':
  1158. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1159. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1160. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1161. if self.instruction[id]['rotate'] is not None:
  1162. rot = float(self.instruction[id]['rotate'])/180*pi
  1163. else:
  1164. rot = 0
  1165. if self.instruction[id]['ref'].split()[0] == 'lower':
  1166. y += extent[1]
  1167. elif self.instruction[id]['ref'].split()[0] == 'center':
  1168. y += extent[1]/2
  1169. if self.instruction[id]['ref'].split()[1] == 'right':
  1170. x += extent[0] * cos(rot)
  1171. y -= extent[0] * sin(rot)
  1172. elif self.instruction[id]['ref'].split()[1] == 'center':
  1173. x += extent[0]/2 * cos(rot)
  1174. y -= extent[0]/2 * sin(rot)
  1175. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1176. canvasToPaper = True)[:2]
  1177. self.RecalculateEN()
  1178. def ComputeZoom(self, rect):
  1179. """!Computes zoom factor and scroll view"""
  1180. zoomFactor = 1
  1181. cW, cH = self.GetClientSize()
  1182. cW = float(cW)
  1183. if rect.IsEmpty(): # clicked on canvas
  1184. zoomFactor = 1.5
  1185. if self.mouse['use'] == 'zoomout':
  1186. zoomFactor = 1./zoomFactor
  1187. x,y = self.mouse['begin']
  1188. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1189. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1190. else: #dragging
  1191. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1192. try:
  1193. zoomFactor = 1/max(rW/cW, rH/cH)
  1194. except ZeroDivisionError:
  1195. zoomFactor = 1
  1196. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1197. if abs(zoomFactor - 1) > 0.01:
  1198. zoomFactor = zoomFactor
  1199. else:
  1200. zoomFactor = 1.
  1201. if self.mouse['use'] == 'zoomout':
  1202. zoomFactor = min(rW/cW, rH/cH)
  1203. try:
  1204. if rW/rH > cW/cH:
  1205. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1206. xView = rect.GetX()
  1207. if self.mouse['use'] == 'zoomout':
  1208. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1209. xView, yView = -x, -y
  1210. else:
  1211. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1212. yView = rect.GetY()
  1213. if self.mouse['use'] == 'zoomout':
  1214. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1215. xView, yView = -x, -y
  1216. except ZeroDivisionError:
  1217. xView, yView = rect.GetX(), rect.GetY()
  1218. return zoomFactor, (int(xView), int(yView))
  1219. def Zoom(self, zoomFactor, view):
  1220. """! Zoom to specified region, scroll view, redraw"""
  1221. if not self.currScale:
  1222. return
  1223. self.currScale = self.currScale*zoomFactor
  1224. if self.currScale > 10 or self.currScale < 0.1:
  1225. self.currScale = self.currScale/zoomFactor
  1226. return
  1227. if not self.preview:
  1228. # redraw paper
  1229. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1230. pRect.OffsetXY(-view[0], -view[1])
  1231. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1232. self.DrawPaper(pRect)
  1233. #redraw objects
  1234. for id in self.objectId:
  1235. oRect = self.CanvasPaperCoordinates(
  1236. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1237. type = self.instruction[id].type
  1238. if type == 'text':
  1239. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1240. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1241. for i, coord in enumerate(coords)]
  1242. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1243. coords = coords, bounds = oRect )
  1244. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1245. if self.instruction[id]['rotate']:
  1246. rot = float(self.instruction[id]['rotate'])
  1247. else:
  1248. rot = 0
  1249. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1250. self.pdcObj.SetIdBounds(id, bounds)
  1251. elif type == 'northArrow':
  1252. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1253. drawid = id, pdctype = 'bitmap', bb = oRect)
  1254. else:
  1255. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1256. drawid = id, pdctype = 'rectText', bb = oRect)
  1257. #redraw tmp objects
  1258. if self.dragId != -1:
  1259. self.RedrawSelectBox(self.dragId)
  1260. #redraw preview
  1261. else: # preview mode
  1262. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1263. imageRect.OffsetXY(-view[0], -view[1])
  1264. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1265. self.DrawImage(imageRect)
  1266. def ZoomAll(self):
  1267. """! Zoom to full extent"""
  1268. if not self.preview:
  1269. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1270. else:
  1271. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1272. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1273. zoomFactor, view = self.ComputeZoom(zoomP)
  1274. self.Zoom(zoomFactor, view)
  1275. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1276. """! Draw object"""
  1277. if drawid is None:
  1278. drawid = wx.NewId()
  1279. bb = bb.Get()
  1280. pdc.BeginDrawing()
  1281. pdc.RemoveId(drawid)
  1282. pdc.SetId(drawid)
  1283. pdc.SetPen(pen)
  1284. pdc.SetBrush(brush)
  1285. if pdctype == 'bitmap':
  1286. if havePILImage:
  1287. file = self.instruction[drawid]['epsfile']
  1288. rotation = self.instruction[drawid]['rotate']
  1289. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1290. else: # draw only rectangle with label
  1291. pdctype = 'rectText'
  1292. if pdctype in ('rect', 'rectText'):
  1293. pdc.DrawRectangle(*bb)
  1294. if pdctype == 'rectText':
  1295. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1296. font = self.font
  1297. size = 10
  1298. font.SetPointSize(size)
  1299. font.SetStyle(wx.ITALIC)
  1300. dc.SetFont(font)
  1301. pdc.SetFont(font)
  1302. text = '\n'.join(self.itemLabels[drawid])
  1303. w,h,lh = dc.GetMultiLineTextExtent(text)
  1304. textExtent = (w,h)
  1305. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1306. r = map(int, bb)
  1307. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1308. size -= 2
  1309. font.SetPointSize(size)
  1310. dc.SetFont(font)
  1311. pdc.SetFont(font)
  1312. textExtent = dc.GetTextExtent(text)
  1313. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1314. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1315. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1316. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1317. pdc.SetIdBounds(drawid, bb)
  1318. pdc.EndDrawing()
  1319. self.Refresh()
  1320. return drawid
  1321. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1322. """!Draw bitmap using PIL"""
  1323. pImg = PILImage.open(filePath)
  1324. if rotation:
  1325. # get rid of black background
  1326. pImg = pImg.convert("RGBA")
  1327. rot = pImg.rotate(rotation, expand = 1)
  1328. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1329. pImg = PILImage.composite(rot, new, rot)
  1330. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1331. img = PilImageToWxImage(pImg)
  1332. bitmap = img.ConvertToBitmap()
  1333. mask = wx.Mask(bitmap, wx.WHITE)
  1334. bitmap.SetMask(mask)
  1335. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1336. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1337. if textDict['rotate']:
  1338. rot = float(textDict['rotate'])
  1339. else:
  1340. rot = 0
  1341. fontsize = textDict['fontsize'] * self.currScale
  1342. if textDict['background'] != 'none':
  1343. background = textDict['background']
  1344. else:
  1345. background = None
  1346. pdc.RemoveId(drawId)
  1347. pdc.SetId(drawId)
  1348. pdc.BeginDrawing()
  1349. # border is not redrawn when zoom changes, why?
  1350. ## if textDict['border'] != 'none' and not rot:
  1351. ## units = UnitConversion(self)
  1352. ## borderWidth = units.convert(value = textDict['width'],
  1353. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1354. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1355. ## pdc.DrawRectangle(*bounds)
  1356. if background:
  1357. pdc.SetTextBackground(convertRGB(background))
  1358. pdc.SetBackgroundMode(wx.SOLID)
  1359. else:
  1360. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1361. fn = self.parent.makePSFont(textDict)
  1362. pdc.SetFont(fn)
  1363. pdc.SetTextForeground(convertRGB(textDict['color']))
  1364. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1365. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1366. self.Refresh()
  1367. pdc.EndDrawing()
  1368. def DrawImage(self, rect):
  1369. """!Draw preview image to pseudoDC"""
  1370. self.pdcImage.ClearId(self.imageId)
  1371. self.pdcImage.SetId(self.imageId)
  1372. img = self.image
  1373. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1374. img = img.Scale(rect.width, rect.height)
  1375. bitmap = img.ConvertToBitmap()
  1376. self.pdcImage.BeginDrawing()
  1377. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1378. self.pdcImage.SetIdBounds(self.imageId, rect)
  1379. self.pdcImage.EndDrawing()
  1380. self.Refresh()
  1381. def DrawPaper(self, rect):
  1382. """!Draw paper and margins"""
  1383. page = self.instruction[self.pageId]
  1384. scale = page['Width'] / rect.GetWidth()
  1385. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1386. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1387. x = page['Left'] / scale + rect.GetX()
  1388. y = page['Top'] / scale + rect.GetY()
  1389. self.pdcPaper.BeginDrawing()
  1390. self.pdcPaper.RemoveId(self.pageId)
  1391. self.pdcPaper.SetId(self.pageId)
  1392. self.pdcPaper.SetPen(self.pen['paper'])
  1393. self.pdcPaper.SetBrush(self.brush['paper'])
  1394. self.pdcPaper.DrawRectangleRect(rect)
  1395. self.pdcPaper.SetPen(self.pen['margins'])
  1396. self.pdcPaper.SetBrush(self.brush['margins'])
  1397. self.pdcPaper.DrawRectangle(x, y, w, h)
  1398. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1399. self.pdcPaper.EndDrawing()
  1400. self.Refresh()
  1401. def ImageRect(self):
  1402. """!Returns image centered in canvas, computes scale"""
  1403. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1404. cW, cH = self.GetClientSize()
  1405. iW, iH = img.GetWidth(), img.GetHeight()
  1406. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1407. iW = iW * self.currScale
  1408. iH = iH * self.currScale
  1409. x = cW/2 - iW/2
  1410. y = cH/2 - iH/2
  1411. imageRect = wx.Rect(x, y, iW, iH)
  1412. return imageRect
  1413. def RedrawSelectBox(self, id):
  1414. """!Redraws select box when selected object changes its size"""
  1415. if self.dragId == id:
  1416. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1417. type = ['select']
  1418. ids = [self.idBoxTmp]
  1419. if self.instruction[id].type == 'map':
  1420. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1421. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1422. type.append('resize')
  1423. ids.append(self.idResizeBoxTmp)
  1424. for id, type, rect in zip(ids, type, rect):
  1425. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1426. drawid = id, pdctype = 'rect', bb = rect)
  1427. def UpdateMapLabel(self):
  1428. """!Updates map frame label"""
  1429. vector = self.instruction.FindInstructionByType('vector')
  1430. if vector:
  1431. vectorId = vector.id
  1432. else:
  1433. vectorId = None
  1434. raster = self.instruction.FindInstructionByType('raster')
  1435. if raster:
  1436. rasterId = raster.id
  1437. else:
  1438. rasterId = None
  1439. rasterName = 'None'
  1440. if rasterId:
  1441. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1442. mapId = self.instruction.FindInstructionByType('map').id
  1443. self.itemLabels[mapId] = []
  1444. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1445. self.itemLabels[mapId].append("raster: " + rasterName)
  1446. if vectorId:
  1447. for map in self.instruction[vectorId]['list']:
  1448. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1449. def UpdateLabel(self, itype, id):
  1450. self.itemLabels[id] = []
  1451. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1452. if itype == 'image':
  1453. file = os.path.basename(self.instruction[id]['epsfile'])
  1454. self.itemLabels[id].append(file)
  1455. def OnSize(self, event):
  1456. """!Init image size to match window size
  1457. """
  1458. # not zoom all when notebook page is changed
  1459. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1460. self.ZoomAll()
  1461. self.OnIdle(None)
  1462. event.Skip()
  1463. def OnIdle(self, event):
  1464. """!Only re-render a image during idle time instead of
  1465. multiple times during resizing.
  1466. """
  1467. width, height = self.GetClientSize()
  1468. # Make new off screen bitmap: this bitmap will always have the
  1469. # current drawing in it, so it can be used to save the image
  1470. # to a file, or whatever.
  1471. self._buffer = wx.EmptyBitmap(width, height)
  1472. # re-render image on idle
  1473. self.resize = True
  1474. def ScaleRect(self, rect, scale):
  1475. """! Scale rectangle"""
  1476. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1477. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1478. def main():
  1479. import gettext
  1480. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1481. app = wx.PySimpleApp()
  1482. wx.InitAllImageHandlers()
  1483. frame = PsMapFrame()
  1484. frame.Show()
  1485. app.MainLoop()
  1486. if __name__ == "__main__":
  1487. main()