frame.py 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  1. """
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011-2012 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 Queue
  16. from math import sin, cos, pi, sqrt
  17. import wx
  18. try:
  19. import wx.lib.agw.flatnotebook as fnb
  20. except ImportError:
  21. import wx.lib.flatnotebook as fnb
  22. import grass.script as grass
  23. from core import globalvar
  24. from gui_core.menu import Menu
  25. from core.gconsole import CmdThread, EVT_CMD_DONE
  26. from psmap.toolbars import PsMapToolbar
  27. from core.gcmd import RunCommand, GError, GMessage
  28. from core.settings import UserSettings
  29. from core.utils import _
  30. from gui_core.forms import GUI
  31. from gui_core.dialogs import HyperlinkDialog
  32. from gui_core.ghelp import ShowAboutDialog
  33. from psmap.menudata import PsMapMenuData
  34. from gui_core.toolbars import ToolSwitcher
  35. from psmap.dialogs import *
  36. from psmap.instructions import *
  37. from psmap.utils import *
  38. class PsMapFrame(wx.Frame):
  39. def __init__(self, parent = None, id = wx.ID_ANY,
  40. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  41. """Main window of ps.map GUI
  42. :param parent: parent window
  43. :param id: window id
  44. :param title: window title
  45. :param kwargs: wx.Frames' arguments
  46. """
  47. self.parent = parent
  48. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  49. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  50. #menubar
  51. self.menubar = Menu(parent = self, model = PsMapMenuData().GetModel(separators=True))
  52. self.SetMenuBar(self.menubar)
  53. #toolbar
  54. self._toolSwitcher = ToolSwitcher()
  55. self.toolbar = PsMapToolbar(parent=self, toolSwitcher=self._toolSwitcher)
  56. self.SetToolBar(self.toolbar)
  57. self.iconsize = (16, 16)
  58. #satusbar
  59. self.statusbar = self.CreateStatusBar(number = 1)
  60. # mouse attributes -- position on the screen, begin and end of
  61. # dragging, and type of drawing
  62. self.mouse = {
  63. 'begin': [0, 0], # screen coordinates
  64. 'end' : [0, 0],
  65. 'use' : "pointer",
  66. }
  67. # available cursors
  68. self.cursors = {
  69. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  70. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  71. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  72. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  73. }
  74. # pen and brush
  75. self.pen = {
  76. 'paper': wx.Pen(colour = "BLACK", width = 1),
  77. 'margins': wx.Pen(colour = "GREY", width = 1),
  78. 'map': wx.Pen(colour = wx.Colour(86, 122, 17), width = 2),
  79. 'rasterLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  80. 'vectorLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  81. 'mapinfo': wx.Pen(colour = wx.Colour(5, 184, 249), width = 2),
  82. 'scalebar': wx.Pen(colour = wx.Colour(150, 150, 150), width = 2),
  83. 'image': wx.Pen(colour = wx.Colour(255, 150, 50), width = 2),
  84. 'northArrow': wx.Pen(colour = wx.Colour(200, 200, 200), width = 2),
  85. 'point': wx.Pen(colour = wx.Colour(100, 100, 100), width = 2),
  86. 'line': wx.Pen(colour = wx.Colour(0, 0, 0), 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.Colour(151, 214, 90)),
  95. 'rasterLegend': wx.Brush(wx.Colour(250, 247, 112)),
  96. 'vectorLegend': wx.Brush(wx.Colour(250, 247, 112)),
  97. 'mapinfo': wx.Brush(wx.Colour(127, 222, 252)),
  98. 'scalebar': wx.Brush(wx.Colour(200, 200, 200)),
  99. 'image': wx.Brush(wx.Colour(255, 200, 50)),
  100. 'northArrow': wx.Brush(wx.Colour(255, 255, 255)),
  101. 'point': wx.Brush(wx.Colour(200, 200, 200)),
  102. 'line': wx.TRANSPARENT_BRUSH,
  103. 'box': wx.TRANSPARENT_BRUSH,
  104. 'select':wx.TRANSPARENT_BRUSH,
  105. 'resize': wx.BLACK_BRUSH
  106. }
  107. # list of objects to draw
  108. self.objectId = []
  109. # instructions
  110. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  111. # open dialogs
  112. self.openDialogs = dict()
  113. self.pageId = wx.NewId()
  114. #current page of flatnotebook
  115. self.currentPage = 0
  116. #canvas for draft mode
  117. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  118. brush = self.brush, cursors = self.cursors,
  119. instruction = self.instruction, openDialogs = self.openDialogs,
  120. pageId = self.pageId, objectId = self.objectId,
  121. preview = False)
  122. self.canvas.SetCursor(self.cursors["default"])
  123. self.getInitMap()
  124. # image path
  125. env = grass.gisenv()
  126. self.imgName = grass.tempfile()
  127. #canvas for preview
  128. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  129. pen = self.pen, brush = self.brush, preview = True)
  130. # set WIND_OVERRIDE
  131. grass.use_temp_region()
  132. self.toolbar.SelectDefault()
  133. # create queues
  134. self.requestQ = Queue.Queue()
  135. self.resultQ = Queue.Queue()
  136. # thread
  137. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  138. self._layout()
  139. self.SetMinSize(wx.Size(775, 600))
  140. # workaround for http://trac.wxwidgets.org/ticket/13628
  141. self.SetSize(self.GetBestSize())
  142. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  143. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  144. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  145. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  146. if not havePILImage:
  147. wx.CallAfter(self._showErrMsg)
  148. def _showErrMsg(self):
  149. """Show error message (missing preview)
  150. """
  151. GError(parent = self,
  152. message = _("Python Imaging Library is not available.\n"
  153. "'Preview' functionality won't work."),
  154. showTraceback = False)
  155. def _layout(self):
  156. """Do layout
  157. """
  158. mainSizer = wx.BoxSizer(wx.VERTICAL)
  159. if globalvar.hasAgw:
  160. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  161. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  162. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  163. else:
  164. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  165. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  166. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  167. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  168. self.book.AddPage(self.canvas, "Draft mode")
  169. self.book.AddPage(self.previewCanvas, "Preview")
  170. self.book.SetSelection(0)
  171. mainSizer.Add(self.book,1, wx.EXPAND)
  172. self.SetSizer(mainSizer)
  173. mainSizer.Fit(self)
  174. def InstructionFile(self):
  175. """Creates mapping instructions"""
  176. return str(self.instruction)
  177. def OnPSFile(self, event):
  178. """Generate PostScript"""
  179. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  180. if filename:
  181. self.PSFile(filename)
  182. def OnPsMapDialog(self, event):
  183. """Launch ps.map dialog
  184. """
  185. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  186. def OnPDFFile(self, event):
  187. """Generate PDF from PS with ps2pdf if available"""
  188. if not sys.platform == 'win32':
  189. try:
  190. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  191. p.stderr.close()
  192. except OSError:
  193. GMessage(parent = self,
  194. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  195. return
  196. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  197. if filename:
  198. self.PSFile(filename, pdf = True)
  199. def OnPreview(self, event):
  200. """Run ps.map and show result"""
  201. self.PSFile()
  202. def PSFile(self, filename = None, pdf = False):
  203. """Create temporary instructions file and run ps.map with output = filename"""
  204. instrFile = grass.tempfile()
  205. instrFileFd = open(instrFile, mode = 'w')
  206. instrFileFd.write(self.InstructionFile())
  207. instrFileFd.flush()
  208. instrFileFd.close()
  209. temp = False
  210. regOld = grass.region()
  211. if pdf:
  212. pdfname = filename
  213. else:
  214. pdfname = None
  215. #preview or pdf
  216. if not filename or (filename and pdf):
  217. temp = True
  218. filename = grass.tempfile()
  219. if not pdf: # lower resolution for preview
  220. if self.instruction.FindInstructionByType('map'):
  221. mapId = self.instruction.FindInstructionByType('map').id
  222. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  223. height = self.instruction[mapId]['rect'][3])
  224. cmd = ['ps.map', '--overwrite']
  225. if os.path.splitext(filename)[1] == '.eps':
  226. cmd.append('-e')
  227. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  228. cmd.append('-r')
  229. cmd.append('input=%s' % instrFile)
  230. cmd.append('output=%s' % filename)
  231. if pdf:
  232. self.SetStatusText(_('Generating PDF...'), 0)
  233. elif not temp:
  234. self.SetStatusText(_('Generating PostScript...'), 0)
  235. else:
  236. self.SetStatusText(_('Generating preview...'), 0)
  237. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  238. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  239. def OnCmdDone(self, event):
  240. """ps.map process finished"""
  241. if event.returncode != 0:
  242. GMessage(parent = self,
  243. message = _("Ps.map exited with return code %s") % event.returncode)
  244. grass.try_remove(event.userData['instrFile'])
  245. if event.userData['temp']:
  246. grass.try_remove(event.userData['filename'])
  247. return
  248. if event.userData['pdfname']:
  249. if sys.platform == 'win32':
  250. command = ['gswin32c',
  251. '-P-', '-dSAFER',
  252. '-dCompatibilityLevel=1.4',
  253. '-q', '-P-',
  254. '-dNOPAUSE', '-dBATCH',
  255. '-sDEVICE=pdfwrite',
  256. '-dPDFSETTINGS=/prepress', '-r1200',
  257. '-sstdout=%stderr',
  258. '-sOutputFile=%s' % event.userData['pdfname'],
  259. '-P-', '-dSAFER',
  260. '-dCompatibilityLevel=1.4',
  261. '-c', '.setpdfwrite', '-f',
  262. event.userData['filename']]
  263. else:
  264. command = ['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  265. event.userData['filename'], event.userData['pdfname']]
  266. try:
  267. proc = grass.Popen(command)
  268. ret = proc.wait()
  269. if ret > 0:
  270. GMessage(parent = self,
  271. message = _("%(prg)s exited with return code %(code)s") % {'prg': command[0],
  272. 'code': ret})
  273. else:
  274. self.SetStatusText(_('PDF generated'), 0)
  275. except OSError as e:
  276. GError(parent = self,
  277. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  278. elif not event.userData['temp']:
  279. self.SetStatusText(_('PostScript file generated'), 0)
  280. # show preview only when user doesn't want to create ps or pdf
  281. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  282. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  283. # wx.BusyInfo does not display the message
  284. busy = wx.BusyInfo(message = _("Generating preview, wait please"), parent = self)
  285. wx.Yield()
  286. try:
  287. im = PILImage.open(event.userData['filename'])
  288. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  289. im = im.rotate(270)
  290. # hack for Windows, change method for loading EPS
  291. if sys.platform == 'win32':
  292. import types
  293. im.load = types.MethodType(loadPSForWindows, im)
  294. im.save(self.imgName, format = 'PNG')
  295. except IOError as e:
  296. del busy
  297. dlg = HyperlinkDialog(self, title=_("Preview not available"),
  298. message=_("Preview is not available probably due to missing Ghostscript."),
  299. hyperlink='http://trac.osgeo.org/grass/wiki/CompileOnWindows#Ghostscript',
  300. hyperlinkLabel=_("Please follow instructions on GRASS Trac Wiki."))
  301. dlg.ShowModal()
  302. dlg.Destroy()
  303. return
  304. rect = self.previewCanvas.ImageRect()
  305. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  306. self.previewCanvas.DrawImage(rect = rect)
  307. del busy
  308. self.SetStatusText(_('Preview generated'), 0)
  309. self.book.SetSelection(1)
  310. self.currentPage = 1
  311. grass.try_remove(event.userData['instrFile'])
  312. if event.userData['temp']:
  313. grass.try_remove(event.userData['filename'])
  314. self.delayedCall = wx.CallLater(4000, lambda: self.SetStatusText("", 0))
  315. def getFile(self, wildcard):
  316. suffix = []
  317. for filter in wildcard.split('|')[1::2]:
  318. s = filter.strip('*').split('.')[1]
  319. if s:
  320. s = '.' + s
  321. suffix.append(s)
  322. raster = self.instruction.FindInstructionByType('raster')
  323. if raster:
  324. rasterId = raster.id
  325. else:
  326. rasterId = None
  327. if rasterId and self.instruction[rasterId]['raster']:
  328. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  329. else:
  330. mapName = ''
  331. filename = ''
  332. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  333. defaultFile = mapName, wildcard = wildcard,
  334. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  335. if dlg.ShowModal() == wx.ID_OK:
  336. filename = dlg.GetPath()
  337. suffix = suffix[dlg.GetFilterIndex()]
  338. if not os.path.splitext(filename)[1]:
  339. filename = filename + suffix
  340. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  341. filename = os.path.splitext(filename)[0] + suffix
  342. dlg.Destroy()
  343. return filename
  344. def OnInstructionFile(self, event):
  345. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  346. if filename:
  347. instrFile = open(filename, "w")
  348. instrFile.write(self.InstructionFile())
  349. instrFile.close()
  350. def OnLoadFile(self, event):
  351. """Launch file dialog and load selected file"""
  352. #find file
  353. filename = ''
  354. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  355. defaultFile = '', wildcard = "All files (*.*)|*.*",
  356. style = wx.CHANGE_DIR|wx.OPEN)
  357. if dlg.ShowModal() == wx.ID_OK:
  358. filename = dlg.GetPath()
  359. dlg.Destroy()
  360. if not filename:
  361. return
  362. # load instructions
  363. self.LoadFile(filename)
  364. def LoadFile(self, filename):
  365. """Load file and read instructions"""
  366. readObjectId = []
  367. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  368. ok = readInstruction.Read(filename)
  369. if not ok:
  370. GMessage(_("Failed to read file %s.") % filename)
  371. else:
  372. self.instruction = self.canvas.instruction = readInstruction
  373. self.objectId = self.canvas.objectId = readObjectId
  374. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  375. self.canvas.UpdateMapLabel()
  376. self.canvas.dragId = -1
  377. self.canvas.Clear()
  378. self.canvas.SetPage()
  379. #self.canvas.ZoomAll()
  380. self.DialogDataChanged(self.objectId)
  381. def OnPageSetup(self, event = None):
  382. """Specify paper size, margins and orientation"""
  383. id = self.instruction.FindInstructionByType('page').id
  384. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  385. dlg.CenterOnScreen()
  386. val = dlg.ShowModal()
  387. if val == wx.ID_OK:
  388. self.canvas.SetPage()
  389. self.getInitMap()
  390. self.canvas.RecalculatePosition(ids = self.objectId)
  391. dlg.Destroy()
  392. def OnPointer(self, event):
  393. self.mouse["use"] = "pointer"
  394. self.canvas.SetCursor(self.cursors["default"])
  395. self.previewCanvas.SetCursor(self.cursors["default"])
  396. def OnPan(self, event):
  397. self.mouse["use"] = "pan"
  398. self.canvas.SetCursor(self.cursors["hand"])
  399. self.previewCanvas.SetCursor(self.cursors["hand"])
  400. def OnZoomIn(self, event):
  401. self.mouse["use"] = "zoomin"
  402. self.canvas.SetCursor(self.cursors["cross"])
  403. self.previewCanvas.SetCursor(self.cursors["cross"])
  404. def OnZoomOut(self, event):
  405. self.mouse["use"] = "zoomout"
  406. self.canvas.SetCursor(self.cursors["cross"])
  407. self.previewCanvas.SetCursor(self.cursors["cross"])
  408. def OnZoomAll(self, event):
  409. self.mouseOld = self.mouse['use']
  410. if self.currentPage == 0:
  411. self.cursorOld = self.canvas.GetCursor()
  412. else:
  413. self.cursorOld = self.previewCanvas.GetCursor()
  414. self.previewCanvas.GetCursor()
  415. self.mouse["use"] = "zoomin"
  416. if self.currentPage == 0:
  417. self.canvas.ZoomAll()
  418. else:
  419. self.previewCanvas.ZoomAll()
  420. self.mouse["use"] = self.mouseOld
  421. if self.currentPage == 0:
  422. self.canvas.SetCursor(self.cursorOld)
  423. else:
  424. self.previewCanvas.SetCursor(self.cursorOld)
  425. def OnAddMap(self, event, notebook = False):
  426. """Add or edit map frame"""
  427. if self.instruction.FindInstructionByType('map'):
  428. mapId = self.instruction.FindInstructionByType('map').id
  429. else: mapId = None
  430. id = [mapId, None, None]
  431. if notebook:
  432. if self.instruction.FindInstructionByType('vector'):
  433. vectorId = self.instruction.FindInstructionByType('vector').id
  434. else: vectorId = None
  435. if self.instruction.FindInstructionByType('raster'):
  436. rasterId = self.instruction.FindInstructionByType('raster').id
  437. else: rasterId = None
  438. id[1] = rasterId
  439. id[2] = vectorId
  440. if mapId: # map exists
  441. self.toolbar.SelectDefault()
  442. if notebook:
  443. #check map, raster, vector and save, destroy them
  444. if 'map' in self.openDialogs:
  445. self.openDialogs['map'].OnOK(event = None)
  446. if 'raster' in self.openDialogs:
  447. self.openDialogs['raster'].OnOK(event = None)
  448. if 'vector' in self.openDialogs:
  449. self.openDialogs['vector'].OnOK(event = None)
  450. if 'mapNotebook' not in self.openDialogs:
  451. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  452. notebook = notebook)
  453. self.openDialogs['mapNotebook'] = dlg
  454. self.openDialogs['mapNotebook'].Show()
  455. else:
  456. if 'mapNotebook' in self.openDialogs:
  457. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  458. else:
  459. if 'map' not in self.openDialogs:
  460. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  461. notebook = notebook)
  462. self.openDialogs['map'] = dlg
  463. self.openDialogs['map'].Show()
  464. else: # sofar no map
  465. self.mouse["use"] = "addMap"
  466. self.canvas.SetCursor(self.cursors["cross"])
  467. if self.currentPage == 1:
  468. self.book.SetSelection(0)
  469. self.currentPage = 0
  470. def OnAddRaster(self, event):
  471. """Add raster map"""
  472. if self.instruction.FindInstructionByType('raster'):
  473. id = self.instruction.FindInstructionByType('raster').id
  474. else: id = None
  475. if self.instruction.FindInstructionByType('map'):
  476. mapId = self.instruction.FindInstructionByType('map').id
  477. else: mapId = None
  478. if not id:
  479. if not mapId:
  480. GMessage(message = _("Please, create map frame first."))
  481. return
  482. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  483. ## dlg.ShowModal()
  484. if 'mapNotebook' in self.openDialogs:
  485. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  486. else:
  487. if 'raster' not in self.openDialogs:
  488. dlg = RasterDialog(self, id = id, settings = self.instruction)
  489. self.openDialogs['raster'] = dlg
  490. self.openDialogs['raster'].Show()
  491. def OnAddVect(self, event):
  492. """Add vector map"""
  493. if self.instruction.FindInstructionByType('vector'):
  494. id = self.instruction.FindInstructionByType('vector').id
  495. else: id = None
  496. if self.instruction.FindInstructionByType('map'):
  497. mapId = self.instruction.FindInstructionByType('map').id
  498. else: mapId = None
  499. if not id:
  500. if not mapId:
  501. GMessage(message = _("Please, create map frame first."))
  502. return
  503. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  504. ## dlg.ShowModal()
  505. if 'mapNotebook' in self.openDialogs:
  506. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  507. else:
  508. if 'vector' not in self.openDialogs:
  509. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  510. self.openDialogs['vector'] = dlg
  511. self.openDialogs['vector'].Show()
  512. def OnAddScalebar(self, event):
  513. """Add scalebar"""
  514. if projInfo()['proj'] == 'll':
  515. GMessage(message = _("Scalebar is not appropriate for this projection"))
  516. return
  517. if self.instruction.FindInstructionByType('scalebar'):
  518. id = self.instruction.FindInstructionByType('scalebar').id
  519. else: id = None
  520. if 'scalebar' not in self.openDialogs:
  521. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  522. self.openDialogs['scalebar'] = dlg
  523. self.openDialogs['scalebar'].Show()
  524. def OnAddLegend(self, event, page = 0):
  525. """Add raster or vector legend"""
  526. if self.instruction.FindInstructionByType('rasterLegend'):
  527. idR = self.instruction.FindInstructionByType('rasterLegend').id
  528. else: idR = None
  529. if self.instruction.FindInstructionByType('vectorLegend'):
  530. idV = self.instruction.FindInstructionByType('vectorLegend').id
  531. else: idV = None
  532. if 'rasterLegend' not in self.openDialogs:
  533. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  534. self.openDialogs['rasterLegend'] = dlg
  535. self.openDialogs['vectorLegend'] = dlg
  536. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  537. self.openDialogs['rasterLegend'].Show()
  538. def OnAddMapinfo(self, event):
  539. if self.instruction.FindInstructionByType('mapinfo'):
  540. id = self.instruction.FindInstructionByType('mapinfo').id
  541. else: id = None
  542. if 'mapinfo' not in self.openDialogs:
  543. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  544. self.openDialogs['mapinfo'] = dlg
  545. self.openDialogs['mapinfo'].Show()
  546. def OnAddImage(self, event, id = None):
  547. """Show dialog for image adding and editing"""
  548. position = None
  549. if 'image' in self.openDialogs:
  550. position = self.openDialogs['image'].GetPosition()
  551. self.openDialogs['image'].OnApply(event = None)
  552. self.openDialogs['image'].Destroy()
  553. dlg = ImageDialog(self, id = id, settings = self.instruction)
  554. self.openDialogs['image'] = dlg
  555. if position:
  556. dlg.SetPosition(position)
  557. dlg.Show()
  558. def OnAddNorthArrow(self, event, id = None):
  559. """Show dialog for north arrow adding and editing"""
  560. if self.instruction.FindInstructionByType('northArrow'):
  561. id = self.instruction.FindInstructionByType('northArrow').id
  562. else: id = None
  563. if 'northArrow' not in self.openDialogs:
  564. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  565. self.openDialogs['northArrow'] = dlg
  566. self.openDialogs['northArrow'].Show()
  567. def OnAddText(self, event, id = None):
  568. """Show dialog for text adding and editing"""
  569. position = None
  570. if 'text' in self.openDialogs:
  571. position = self.openDialogs['text'].GetPosition()
  572. self.openDialogs['text'].OnApply(event = None)
  573. self.openDialogs['text'].Destroy()
  574. dlg = TextDialog(self, id = id, settings = self.instruction)
  575. self.openDialogs['text'] = dlg
  576. if position:
  577. dlg.SetPosition(position)
  578. dlg.Show()
  579. def OnAddPoint(self, event):
  580. """Add point action selected"""
  581. self.mouse["use"] = "addPoint"
  582. self.canvas.SetCursor(self.cursors["cross"])
  583. def AddPoint(self, id = None, coordinates = None):
  584. """Add point and open property dialog.
  585. :param id: id point id (None if creating new point)
  586. :param coordinates: coordinates of new point
  587. """
  588. position = None
  589. if 'point' in self.openDialogs:
  590. position = self.openDialogs['point'].GetPosition()
  591. self.openDialogs['point'].OnApply(event = None)
  592. self.openDialogs['point'].Destroy()
  593. dlg = PointDialog(self, id = id, settings = self.instruction,
  594. coordinates = coordinates)
  595. self.openDialogs['point'] = dlg
  596. if position:
  597. dlg.SetPosition(position)
  598. if coordinates:
  599. dlg.OnApply(event = None)
  600. dlg.Show()
  601. def OnAddLine(self, event):
  602. """Add line action selected"""
  603. self.mouse["use"] = "addLine"
  604. self.canvas.SetCursor(self.cursors["cross"])
  605. def AddLine(self, id = None, coordinates = None):
  606. """Add line and open property dialog.
  607. :param id: id line id (None if creating new line)
  608. :param coordinates: coordinates of new line
  609. """
  610. position = None
  611. if 'line' in self.openDialogs:
  612. position = self.openDialogs['line'].GetPosition()
  613. self.openDialogs['line'].OnApply(event = None)
  614. self.openDialogs['line'].Destroy()
  615. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  616. type = 'line', coordinates = coordinates)
  617. self.openDialogs['line'] = dlg
  618. if position:
  619. dlg.SetPosition(position)
  620. if coordinates:
  621. dlg.OnApply(event = None)
  622. dlg.Show()
  623. def OnAddRectangle(self, event):
  624. """Add rectangle action selected"""
  625. self.mouse["use"] = "addRectangle"
  626. self.canvas.SetCursor(self.cursors["cross"])
  627. def AddRectangle(self, id = None, coordinates = None):
  628. """Add rectangle and open property dialog.
  629. :param id: id rectangle id (None if creating new rectangle)
  630. :param coordinates: coordinates of new rectangle
  631. """
  632. position = None
  633. if 'rectangle' in self.openDialogs:
  634. position = self.openDialogs['rectangle'].GetPosition()
  635. self.openDialogs['rectangle'].OnApply(event = None)
  636. self.openDialogs['rectangle'].Destroy()
  637. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  638. type = 'rectangle', coordinates = coordinates)
  639. self.openDialogs['rectangle'] = dlg
  640. if position:
  641. dlg.SetPosition(position)
  642. if coordinates:
  643. dlg.OnApply(event = None)
  644. dlg.Show()
  645. def OnAddLabels(self, event, id = None):
  646. """Show dialog for labels"""
  647. if self.instruction.FindInstructionByType('labels'):
  648. id = self.instruction.FindInstructionByType('labels').id
  649. else: id = None
  650. if 'labels' not in self.openDialogs:
  651. dlg = LabelsDialog(self, id = id, settings = self.instruction)
  652. self.openDialogs['labels'] = dlg
  653. self.openDialogs['labels'].Show()
  654. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  655. """computes bounding box of rotated text, not very precisely"""
  656. w, h = textExtent
  657. rotation = float(rotation)/180*pi
  658. H = float(w) * sin(rotation)
  659. W = float(w) * cos(rotation)
  660. X, Y = x, y
  661. if pi/2 < rotation <= 3*pi/2:
  662. X = x + W
  663. if 0 < rotation < pi:
  664. Y = y - H
  665. if rotation == 0:
  666. return wx.Rect(x,y, *textExtent)
  667. else:
  668. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  669. def makePSFont(self, textDict):
  670. """creates a wx.Font object from selected postscript font. To be
  671. used for estimating bounding rectangle of text"""
  672. fontsize = textDict['fontsize'] * self.canvas.currScale
  673. fontface = textDict['font'].split('-')[0]
  674. try:
  675. fontstyle = textDict['font'].split('-')[1]
  676. except IndexError:
  677. fontstyle = ''
  678. if fontface == "Times":
  679. family = wx.FONTFAMILY_ROMAN
  680. face = "times"
  681. elif fontface == "Helvetica":
  682. family = wx.FONTFAMILY_SWISS
  683. face = 'helvetica'
  684. elif fontface == "Courier":
  685. family = wx.FONTFAMILY_TELETYPE
  686. face = 'courier'
  687. else:
  688. family = wx.FONTFAMILY_DEFAULT
  689. face = ''
  690. style = wx.FONTSTYLE_NORMAL
  691. weight = wx.FONTWEIGHT_NORMAL
  692. if 'Oblique' in fontstyle:
  693. style = wx.FONTSTYLE_SLANT
  694. if 'Italic' in fontstyle:
  695. style = wx.FONTSTYLE_ITALIC
  696. if 'Bold' in fontstyle:
  697. weight = wx.FONTWEIGHT_BOLD
  698. try:
  699. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  700. weight = weight, face = face)
  701. except:
  702. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  703. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  704. return fn
  705. def getTextExtent(self, textDict):
  706. """Estimates bounding rectangle of text"""
  707. #fontsize = str(fontsize if fontsize >= 4 else 4)
  708. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  709. fn = self.makePSFont(textDict)
  710. try:
  711. dc.SetFont(fn)
  712. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  713. return (w,h)
  714. except:
  715. return (0,0)
  716. def getInitMap(self):
  717. """Create default map frame when no map is selected, needed for coordinates in map units"""
  718. instrFile = grass.tempfile()
  719. instrFileFd = open(instrFile, mode = 'w')
  720. instrFileFd.write(self.InstructionFile())
  721. instrFileFd.flush()
  722. instrFileFd.close()
  723. page = self.instruction.FindInstructionByType('page')
  724. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  725. grass.try_remove(instrFile)
  726. region = grass.region()
  727. units = UnitConversion(self)
  728. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  729. scale = mapInitRect.Get()[2]/realWidth
  730. initMap = self.instruction.FindInstructionByType('initMap')
  731. if initMap:
  732. id = initMap.id
  733. else:
  734. id = None
  735. if not id:
  736. id = wx.NewId()
  737. initMap = InitMap(id)
  738. self.instruction.AddInstruction(initMap)
  739. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  740. def OnDelete(self, event):
  741. if self.canvas.dragId != -1 and self.currentPage == 0:
  742. if self.instruction[self.canvas.dragId].type == 'map':
  743. self.deleteObject(self.canvas.dragId)
  744. self.getInitMap()
  745. self.canvas.RecalculateEN()
  746. else:
  747. self.deleteObject(self.canvas.dragId)
  748. def deleteObject(self, id):
  749. """Deletes object, his id and redraws"""
  750. #delete from canvas
  751. self.canvas.pdcObj.RemoveId(id)
  752. if id == self.canvas.dragId:
  753. self.canvas.pdcTmp.RemoveAll()
  754. self.canvas.dragId = -1
  755. self.canvas.Refresh()
  756. # delete from instructions
  757. del self.instruction[id]
  758. def DialogDataChanged(self, id):
  759. ids = id
  760. if type(id) == int:
  761. ids = [id]
  762. for id in ids:
  763. itype = self.instruction[id].type
  764. if itype in ('scalebar', 'mapinfo', 'image'):
  765. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  766. self.canvas.UpdateLabel(itype = itype, id = id)
  767. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  768. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  769. self.canvas.RedrawSelectBox(id)
  770. if itype == 'northArrow':
  771. self.canvas.UpdateLabel(itype = itype, id = id)
  772. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  773. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  774. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  775. self.canvas.RedrawSelectBox(id)
  776. if itype in ('point', 'line', 'rectangle'):
  777. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  778. # coords only for line
  779. coords = None
  780. if itype == 'line':
  781. point1 = self.instruction[id]['where'][0]
  782. point2 = self.instruction[id]['where'][1]
  783. point1Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)), canvasToPaper = False)[:2]
  784. point2Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)), canvasToPaper = False)[:2]
  785. coords = (point1Coords, point2Coords)
  786. # fill color is not in line
  787. fcolor = None
  788. if 'fcolor' in self.instruction[id].GetInstruction():
  789. fcolor = self.instruction[id]['fcolor']
  790. # width is not in point
  791. width = None
  792. if 'width' in self.instruction[id].GetInstruction():
  793. width = self.instruction[id]['width']
  794. self.canvas.DrawGraphics(drawid = id, color = self.instruction[id]['color'], shape = itype,
  795. fcolor = fcolor, width = width, bb = drawRectangle, lineCoords = coords)
  796. self.canvas.RedrawSelectBox(id)
  797. if itype == 'text':
  798. if self.instruction[id]['rotate']:
  799. rot = float(self.instruction[id]['rotate'])
  800. else:
  801. rot = 0
  802. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  803. rect = Rect2DPS(self.instruction[id]['where'], (0, 0))
  804. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  805. #computes text coordinates according to reference point, not precisely
  806. if self.instruction[id]['ref'].split()[0] == 'lower':
  807. self.instruction[id]['coords'][1] -= extent[1]
  808. elif self.instruction[id]['ref'].split()[0] == 'center':
  809. self.instruction[id]['coords'][1] -= extent[1]/2
  810. if self.instruction[id]['ref'].split()[1] == 'right':
  811. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  812. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  813. elif self.instruction[id]['ref'].split()[1] == 'center':
  814. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  815. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  816. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  817. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  818. coords = self.instruction[id]['coords']
  819. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  820. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  821. textDict = self.instruction[id].GetInstruction(),
  822. coords = coords, bounds = bounds)
  823. self.canvas.RedrawSelectBox(id)
  824. if itype in ('map', 'vector', 'raster', 'labels'):
  825. if itype == 'raster':#set resolution
  826. info = grass.raster_info(self.instruction[id]['raster'])
  827. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  828. # change current raster in raster legend
  829. if 'rasterLegend' in self.openDialogs:
  830. self.openDialogs['rasterLegend'].updateDialog()
  831. id = self.instruction.FindInstructionByType('map').id
  832. #check resolution
  833. if itype == 'raster':
  834. SetResolution(dpi = self.instruction[id]['resolution'],
  835. width = self.instruction[id]['rect'].width,
  836. height = self.instruction[id]['rect'].height)
  837. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  838. canvasToPaper = False)
  839. self.canvas.RecalculateEN()
  840. self.canvas.UpdateMapLabel()
  841. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  842. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  843. # redraw select box
  844. self.canvas.RedrawSelectBox(id)
  845. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  846. # redraw to get map to the bottom layer
  847. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  848. if itype == 'rasterLegend':
  849. if self.instruction[id]['rLegend']:
  850. self.canvas.UpdateLabel(itype = itype, id = id)
  851. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  852. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  853. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  854. self.canvas.RedrawSelectBox(id)
  855. else:
  856. self.deleteObject(id)
  857. if itype == 'vectorLegend':
  858. if not self.instruction.FindInstructionByType('vector'):
  859. self.deleteObject(id)
  860. elif self.instruction[id]['vLegend']:
  861. self.canvas.UpdateLabel(itype = itype, id = id)
  862. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  863. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  864. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  865. self.canvas.RedrawSelectBox(id)
  866. else:
  867. self.deleteObject(id)
  868. def OnPageChanged(self, event):
  869. """Flatnotebook page has changed"""
  870. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  871. if self.currentPage == 1:
  872. self.SetStatusText(_("Press button with green triangle icon to generate preview."))
  873. else:
  874. self.SetStatusText('')
  875. def OnPageChanging(self, event):
  876. """Flatnotebook page is changing"""
  877. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  878. event.Veto()
  879. def OnHelp(self, event):
  880. """Show help"""
  881. if self.parent and self.parent.GetName() == 'LayerManager':
  882. log = self.parent.GetLogWindow()
  883. log.RunCmd(['g.manual',
  884. 'entry=wxGUI.psmap'])
  885. else:
  886. RunCommand('g.manual',
  887. quiet = True,
  888. entry = 'wxGUI.psmap')
  889. def OnAbout(self, event):
  890. """Display About window"""
  891. ShowAboutDialog(prgName=_('wxGUI Cartographic Composer'), startYear='2011')
  892. def OnCloseWindow(self, event):
  893. """Close window"""
  894. try:
  895. os.remove(self.imgName)
  896. except OSError:
  897. pass
  898. grass.set_raise_on_error(False)
  899. if hasattr(self, 'delayedCall') and self.delayedCall.IsRunning():
  900. self.delayedCall.Stop()
  901. self.Destroy()
  902. class PsMapBufferedWindow(wx.Window):
  903. """A buffered window class."""
  904. def __init__(self, parent, id = wx.ID_ANY,
  905. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  906. **kwargs):
  907. """
  908. :param parent: parent window
  909. :param kwargs: other wx.Window parameters
  910. """
  911. wx.Window.__init__(self, parent, id = id, style = style)
  912. self.parent = parent
  913. self.FitInside()
  914. # store an off screen empty bitmap for saving to file
  915. self._buffer = None
  916. # indicates whether or not a resize event has taken place
  917. self.resize = False
  918. self.mouse = kwargs['mouse']
  919. self.cursors = kwargs['cursors']
  920. self.preview = kwargs['preview']
  921. self.pen = kwargs['pen']
  922. self.brush = kwargs['brush']
  923. if kwargs.has_key('instruction'):
  924. self.instruction = kwargs['instruction']
  925. if kwargs.has_key('openDialogs'):
  926. self.openDialogs = kwargs['openDialogs']
  927. if kwargs.has_key('pageId'):
  928. self.pageId = kwargs['pageId']
  929. if kwargs.has_key('objectId'):
  930. self.objectId = kwargs['objectId']
  931. #labels
  932. self.itemLabelsDict = { 'map': _("MAP FRAME"),
  933. 'rasterLegend': _("RASTER LEGEND"),
  934. 'vectorLegend': _("VECTOR LEGEND"),
  935. 'mapinfo': _("MAP INFO"),
  936. 'scalebar': _("SCALE BAR"),
  937. 'image': _("IMAGE"),
  938. 'northArrow': _("NORTH ARROW")}
  939. self.itemLabels = {}
  940. # define PseudoDC
  941. self.pdc = wx.PseudoDC()
  942. self.pdcObj = wx.PseudoDC()
  943. self.pdcPaper = wx.PseudoDC()
  944. self.pdcTmp = wx.PseudoDC()
  945. self.pdcImage = wx.PseudoDC()
  946. self.SetClientSize((700,510))#?
  947. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  948. self.idBoxTmp = wx.NewId()
  949. self.idZoomBoxTmp = wx.NewId()
  950. self.idResizeBoxTmp = wx.NewId()
  951. self.idLinePointsTmp = (wx.NewId(), wx.NewId()) # ids of marks for moving line vertices
  952. self.resizeBoxSize = wx.Size(8, 8)
  953. self.showResizeHelp = False # helper for correctly working statusbar
  954. self.dragId = -1
  955. if self.preview:
  956. self.image = None
  957. self.imageId = 2000
  958. self.imgName = self.parent.imgName
  959. self.currScale = None
  960. self.Clear()
  961. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  962. self.Bind(wx.EVT_PAINT, self.OnPaint)
  963. self.Bind(wx.EVT_SIZE, self.OnSize)
  964. self.Bind(wx.EVT_IDLE, self.OnIdle)
  965. # self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  966. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  967. def Clear(self):
  968. """Clear canvas and set paper
  969. """
  970. bg = wx.LIGHT_GREY_BRUSH
  971. self.pdcPaper.BeginDrawing()
  972. self.pdcPaper.SetBackground(bg)
  973. self.pdcPaper.Clear()
  974. self.pdcPaper.EndDrawing()
  975. self.pdcObj.RemoveAll()
  976. self.pdcTmp.RemoveAll()
  977. if not self.preview:
  978. self.SetPage()
  979. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  980. """Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  981. units = UnitConversion(self)
  982. fromU = 'pixel'
  983. toU = 'inch'
  984. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  985. pRectx, pRecty = pRect.x, pRect.y
  986. scale = 1/self.currScale
  987. if not canvasToPaper: # paper -> canvas
  988. fromU = 'inch'
  989. toU = 'pixel'
  990. scale = self.currScale
  991. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  992. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  993. Width = units.convert(value = rect.GetWidth(), fromUnit = fromU, toUnit = toU) * scale
  994. Height = units.convert(value = rect.GetHeight(), fromUnit = fromU, toUnit = toU) * scale
  995. X = units.convert(value = (rect.GetX() - pRectx), fromUnit = fromU, toUnit = toU) * scale
  996. Y = units.convert(value = (rect.GetY() - pRecty), fromUnit = fromU, toUnit = toU) * scale
  997. return Rect2D(X, Y, Width, Height)
  998. def SetPage(self):
  999. """Sets and changes page, redraws paper"""
  1000. page = self.instruction[self.pageId]
  1001. if not page:
  1002. page = PageSetup(id = self.pageId)
  1003. self.instruction.AddInstruction(page)
  1004. ppi = wx.ClientDC(self).GetPPI()
  1005. cW, cH = self.GetClientSize()
  1006. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  1007. if self.currScale is None:
  1008. self.currScale = min(cW/pW, cH/pH)
  1009. pW = pW * self.currScale
  1010. pH = pH * self.currScale
  1011. x = cW/2 - pW/2
  1012. y = cH/2 - pH/2
  1013. self.DrawPaper(wx.Rect(x, y, pW, pH))
  1014. def modifyRectangle(self, r):
  1015. """Recalculates rectangle not to have negative size"""
  1016. if r.GetWidth() < 0:
  1017. r.SetX(r.GetX() + r.GetWidth())
  1018. if r.GetHeight() < 0:
  1019. r.SetY(r.GetY() + r.GetHeight())
  1020. r.SetWidth(abs(r.GetWidth()))
  1021. r.SetHeight(abs(r.GetHeight()))
  1022. return r
  1023. def RecalculateEN(self):
  1024. """Recalculate east and north for texts (eps, points) after their or map's movement"""
  1025. try:
  1026. mapId = self.instruction.FindInstructionByType('map').id
  1027. except AttributeError:
  1028. mapId = self.instruction.FindInstructionByType('initMap').id
  1029. for itemType in ('text', 'image', 'northArrow', 'point', 'line', 'rectangle'):
  1030. items = self.instruction.FindInstructionByType(itemType, list = True)
  1031. for item in items:
  1032. instr = self.instruction[item.id]
  1033. if itemType in ('line', 'rectangle'):
  1034. if itemType == 'line':
  1035. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0][0],
  1036. y = instr['where'][0][1], paperToMap = True)
  1037. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][1][0],
  1038. y = instr['where'][1][1], paperToMap = True)
  1039. else:
  1040. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetLeft(),
  1041. y = instr['rect'].GetTop(), paperToMap = True)
  1042. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetRight(),
  1043. y = instr['rect'].GetBottom(), paperToMap = True)
  1044. instr['east1'] = e1
  1045. instr['north1'] = n1
  1046. instr['east2'] = e2
  1047. instr['north2'] = n2
  1048. else:
  1049. e, n = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0],
  1050. y = instr['where'][1], paperToMap = True)
  1051. instr['east'], instr['north'] = e, n
  1052. def OnPaint(self, event):
  1053. """Draw pseudo DC to buffer
  1054. """
  1055. if not self._buffer:
  1056. return
  1057. dc = wx.BufferedPaintDC(self, self._buffer)
  1058. # use PrepareDC to set position correctly
  1059. # probably does nothing, removed from wxPython 2.9
  1060. # self.PrepareDC(dc)
  1061. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1062. dc.Clear()
  1063. # draw paper
  1064. if not self.preview:
  1065. self.pdcPaper.DrawToDC(dc)
  1066. # draw to the DC using the calculated clipping rect
  1067. rgn = self.GetUpdateRegion()
  1068. if not self.preview:
  1069. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1070. else:
  1071. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1072. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1073. def MouseActions(self, event):
  1074. """Mouse motion and button click notifier
  1075. """
  1076. # zoom with mouse wheel
  1077. if event.GetWheelRotation() != 0:
  1078. self.OnMouseWheel(event)
  1079. # left mouse button pressed
  1080. elif event.LeftDown():
  1081. self.OnLeftDown(event)
  1082. # left mouse button released
  1083. elif event.LeftUp():
  1084. self.OnLeftUp(event)
  1085. # dragging
  1086. elif event.Dragging():
  1087. self.OnDragging(event)
  1088. # double click
  1089. elif event.ButtonDClick():
  1090. self.OnButtonDClick(event)
  1091. # middle mouse button pressed
  1092. elif event.MiddleDown():
  1093. self.OnMiddleDown(event)
  1094. elif event.Moving():
  1095. self.OnMouseMoving(event)
  1096. def OnMouseWheel(self, event):
  1097. """Mouse wheel scrolled.
  1098. Changes zoom."""
  1099. if UserSettings.Get(group = 'display',
  1100. key = 'mouseWheelZoom',
  1101. subkey = 'selection') == 2:
  1102. event.Skip()
  1103. return
  1104. zoom = event.GetWheelRotation()
  1105. oldUse = self.mouse['use']
  1106. self.mouse['begin'] = event.GetPosition()
  1107. if UserSettings.Get(group = 'display',
  1108. key = 'scrollDirection',
  1109. subkey = 'selection'):
  1110. zoom *= -1
  1111. if zoom > 0:
  1112. self.mouse['use'] = 'zoomin'
  1113. else:
  1114. self.mouse['use'] = 'zoomout'
  1115. zoomFactor, view = self.ComputeZoom(wx.Rect(0, 0, 0, 0))
  1116. self.Zoom(zoomFactor, view)
  1117. self.mouse['use'] = oldUse
  1118. def OnMouseMoving(self, event):
  1119. """Mouse cursor moving.
  1120. Change cursor when moving over resize marker.
  1121. """
  1122. if self.preview:
  1123. return
  1124. if self.mouse['use'] in ('pointer', 'resize'):
  1125. pos = event.GetPosition()
  1126. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1127. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1128. self.SetCursor(self.cursors["sizenwse"])
  1129. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  1130. self.showResizeHelp = True
  1131. else:
  1132. if self.showResizeHelp:
  1133. self.parent.SetStatusText('', 0)
  1134. self.SetCursor(self.cursors["default"])
  1135. self.showResizeHelp = False
  1136. def OnLeftDown(self, event):
  1137. """Left mouse button pressed.
  1138. Select objects, redraw, prepare for moving/resizing.
  1139. """
  1140. self.mouse['begin'] = event.GetPosition()
  1141. self.begin = self.mouse['begin']
  1142. # select
  1143. if self.mouse['use'] == 'pointer':
  1144. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1145. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1146. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1147. self.mouse['use'] = 'resize'
  1148. # when resizing, proportions match region
  1149. if self.instruction[self.dragId].type == 'map':
  1150. self.constraint = False
  1151. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1152. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1153. self.constraint = True
  1154. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1155. if self.instruction[self.dragId].type == 'line':
  1156. self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
  1157. elif found:
  1158. self.dragId = found[0]
  1159. self.RedrawSelectBox(self.dragId)
  1160. if self.instruction[self.dragId].type not in ('map', 'rectangle'):
  1161. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1162. self.Refresh()
  1163. if self.instruction[self.dragId].type != 'line':
  1164. for id in self.idLinePointsTmp:
  1165. self.pdcTmp.RemoveId(id)
  1166. self.Refresh()
  1167. else:
  1168. self.dragId = -1
  1169. self.pdcTmp.RemoveId(self.idBoxTmp)
  1170. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1171. for id in self.idLinePointsTmp:
  1172. self.pdcTmp.RemoveId(id)
  1173. self.Refresh()
  1174. def OnLeftUp(self, event):
  1175. """Left mouse button released.
  1176. Recalculate zooming/resizing/moving and redraw.
  1177. """
  1178. # zoom in, zoom out
  1179. if self.mouse['use'] in ('zoomin','zoomout'):
  1180. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1181. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1182. self.Refresh()
  1183. zoomFactor, view = self.ComputeZoom(zoomR)
  1184. self.Zoom(zoomFactor, view)
  1185. # draw map frame
  1186. if self.mouse['use'] == 'addMap':
  1187. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1188. # too small rectangle, it's usually some mistake
  1189. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1190. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1191. self.Refresh()
  1192. return
  1193. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1194. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1195. rect = rectPaper)
  1196. self.openDialogs['map'] = dlg
  1197. self.openDialogs['map'].Show()
  1198. self.parent.toolbar.SelectDefault()
  1199. return
  1200. # resize resizable objects (map, line, rectangle)
  1201. if self.mouse['use'] == 'resize':
  1202. mapObj = self.instruction.FindInstructionByType('map')
  1203. if not mapObj:
  1204. mapObj = self.instruction.FindInstructionByType('initMap')
  1205. mapId = mapObj.id
  1206. if self.dragId == mapId:
  1207. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1208. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1209. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1210. self.instruction[mapId]['rect'] = newRectPaper
  1211. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1212. if self.instruction[mapId]['scaleType'] == 0:
  1213. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1214. map = self.instruction[mapId]['map'],
  1215. mapType = self.instruction[mapId]['mapType'],
  1216. rect = self.instruction[mapId]['rect'])
  1217. elif self.instruction[mapId]['scaleType'] == 1:
  1218. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1219. region = self.instruction[mapId]['region'],
  1220. rect = self.instruction[mapId]['rect'])
  1221. else:
  1222. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1223. rect = self.instruction[mapId]['rect'])
  1224. self.instruction[mapId]['rect'] = rect
  1225. self.instruction[mapId]['scale'] = scale
  1226. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1227. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1228. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1229. elif self.instruction[mapId]['scaleType'] == 3:
  1230. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1231. #check resolution
  1232. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1233. width = self.instruction[mapId]['rect'].width,
  1234. height = self.instruction[mapId]['rect'].height)
  1235. self.RedrawSelectBox(mapId)
  1236. self.Zoom(zoomFactor = 1, view = (0, 0))
  1237. elif self.instruction[self.dragId].type == 'line':
  1238. points = self.instruction[self.dragId]['where']
  1239. self.instruction[self.dragId]['rect'] = Rect2DPP(points[0], points[1])
  1240. self.RecalculatePosition(ids = [self.dragId])
  1241. elif self.instruction[self.dragId].type == 'rectangle':
  1242. self.RecalculatePosition(ids = [self.dragId])
  1243. self.mouse['use'] = 'pointer'
  1244. # recalculate the position of objects after dragging
  1245. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1246. if self.mouse['begin'] != event.GetPosition(): #for double click
  1247. self.RecalculatePosition(ids = [self.dragId])
  1248. if self.instruction[self.dragId].type in self.openDialogs:
  1249. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1250. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1251. endCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(event.GetX(), event.GetY(), 0, 0),
  1252. canvasToPaper = True)[:2]
  1253. diffX = event.GetX() - self.mouse['begin'][0]
  1254. diffY = event.GetY() - self.mouse['begin'][1]
  1255. if self.mouse['use'] == 'addPoint':
  1256. self.parent.AddPoint(coordinates = endCoordinates)
  1257. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1258. # not too small lines/rectangles
  1259. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1260. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1261. self.Refresh()
  1262. return
  1263. beginCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(self.mouse['begin'][0],
  1264. self.mouse['begin'][1], 0, 0),
  1265. canvasToPaper = True)[:2]
  1266. if self.mouse['use'] == 'addLine':
  1267. self.parent.AddLine(coordinates = [beginCoordinates, endCoordinates])
  1268. else:
  1269. self.parent.AddRectangle(coordinates = [beginCoordinates, endCoordinates])
  1270. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1271. self.Refresh()
  1272. def OnButtonDClick(self, event):
  1273. """Open object dialog for editing."""
  1274. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1275. itemCall = {'text':self.parent.OnAddText,
  1276. 'mapinfo': self.parent.OnAddMapinfo,
  1277. 'scalebar': self.parent.OnAddScalebar,
  1278. 'image': self.parent.OnAddImage,
  1279. 'northArrow' : self.parent.OnAddNorthArrow,
  1280. 'point': self.parent.AddPoint,
  1281. 'line': self.parent.AddLine,
  1282. 'rectangle': self.parent.AddRectangle,
  1283. 'rasterLegend': self.parent.OnAddLegend,
  1284. 'vectorLegend': self.parent.OnAddLegend,
  1285. 'map': self.parent.OnAddMap}
  1286. itemArg = { 'text': dict(event = None, id = self.dragId),
  1287. 'mapinfo': dict(event = None),
  1288. 'scalebar': dict(event = None),
  1289. 'image': dict(event = None, id = self.dragId),
  1290. 'northArrow': dict(event = None, id = self.dragId),
  1291. 'point': dict(id = self.dragId),
  1292. 'line': dict(id = self.dragId),
  1293. 'rectangle': dict(id = self.dragId),
  1294. 'rasterLegend': dict(event = None),
  1295. 'vectorLegend': dict(event = None, page = 1),
  1296. 'map': dict(event = None, notebook = True)}
  1297. type = self.instruction[self.dragId].type
  1298. itemCall[type](**itemArg[type])
  1299. def OnDragging(self, event):
  1300. """Process panning/resizing/drawing/moving."""
  1301. if event.MiddleIsDown():
  1302. # panning
  1303. self.mouse['end'] = event.GetPosition()
  1304. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1305. self.mouse['begin'] = event.GetPosition()
  1306. elif event.LeftIsDown():
  1307. # draw box when zooming, creating map
  1308. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1309. self.mouse['end'] = event.GetPosition()
  1310. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1311. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1312. r = self.modifyRectangle(r)
  1313. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1314. if self.mouse['use'] == 'addLine':
  1315. pdcType = 'line'
  1316. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1317. else:
  1318. pdcType = 'rect'
  1319. lineCoords = None
  1320. if r[2] < 2 or r[3] < 2:
  1321. # to avoid strange behavoiur
  1322. return
  1323. self.Draw(pen = self.pen['line'], brush = self.brush['line'],
  1324. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1325. pdctype = pdcType, bb = r, lineCoords = lineCoords)
  1326. else:
  1327. self.Draw(pen = self.pen['box'], brush = self.brush['box'],
  1328. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1329. pdctype = 'rect', bb = r)
  1330. # panning
  1331. if self.mouse["use"] == 'pan':
  1332. self.mouse['end'] = event.GetPosition()
  1333. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1334. self.mouse['begin'] = event.GetPosition()
  1335. # move object
  1336. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1337. self.mouse['end'] = event.GetPosition()
  1338. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1339. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1340. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1341. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1342. for id in self.idLinePointsTmp:
  1343. self.pdcTmp.TranslateId(id, dx, dy)
  1344. if self.instruction[self.dragId].type == 'text':
  1345. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1346. self.instruction[self.dragId]['coords'][1] + dy
  1347. self.begin = event.GetPosition()
  1348. self.Refresh()
  1349. # resize object
  1350. if self.mouse['use'] == 'resize':
  1351. pos = event.GetPosition()
  1352. diffX = pos[0] - self.mouse['begin'][0]
  1353. diffY = pos[1] - self.mouse['begin'][1]
  1354. if self.instruction[self.dragId].type == 'map':
  1355. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1356. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1357. # match given region
  1358. if self.constraint:
  1359. if width > height:
  1360. newWidth = width + diffX
  1361. newHeight = height + diffX * (float(height) / width)
  1362. else:
  1363. newWidth = width + diffY * (float(width) / height)
  1364. newHeight = height + diffY
  1365. else:
  1366. newWidth = width + diffX
  1367. newHeight = height + diffY
  1368. if newWidth < 10 or newHeight < 10:
  1369. return
  1370. bounds = wx.Rect(x, y, newWidth, newHeight)
  1371. self.Draw(pen = self.pen['map'], brush = self.brush['map'], pdc = self.pdcObj, drawid = self.dragId,
  1372. pdctype = 'rectText', bb = bounds)
  1373. elif self.instruction[self.dragId].type == 'rectangle':
  1374. instr = self.instruction[self.dragId]
  1375. rect = self.CanvasPaperCoordinates(rect = instr['rect'], canvasToPaper = False)
  1376. rect.SetWidth(rect.GetWidth() + diffX)
  1377. rect.SetHeight(rect.GetHeight() + diffY)
  1378. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1379. return
  1380. self.DrawGraphics(drawid = self.dragId, shape = 'rectangle', color = instr['color'],
  1381. fcolor = instr['fcolor'], width = instr['width'], bb = rect)
  1382. elif self.instruction[self.dragId].type == 'line':
  1383. instr = self.instruction[self.dragId]
  1384. points = instr['where']
  1385. # moving point
  1386. if self.currentLinePoint == 0:
  1387. pPaper = points[1]
  1388. else:
  1389. pPaper = points[0]
  1390. pCanvas = self.CanvasPaperCoordinates(rect = Rect2DPS(pPaper, (0, 0)),
  1391. canvasToPaper = False)[:2]
  1392. bounds = wx.RectPP(pCanvas, pos)
  1393. self.DrawGraphics(drawid = self.dragId, shape = 'line', color = instr['color'],
  1394. width = instr['width'], bb = bounds, lineCoords = (pos, pCanvas))
  1395. # update paper coordinates
  1396. points[self.currentLinePoint] = self.CanvasPaperCoordinates(rect = wx.RectPS(pos, (0, 0)),
  1397. canvasToPaper = True)[:2]
  1398. self.RedrawSelectBox(self.dragId)
  1399. def OnMiddleDown(self, event):
  1400. """Middle mouse button pressed."""
  1401. self.mouse['begin'] = event.GetPosition()
  1402. def Pan(self, begin, end):
  1403. """Move canvas while dragging.
  1404. :param begin: x,y coordinates of first point
  1405. :param end: x,y coordinates of second point
  1406. """
  1407. view = begin[0] - end[0], begin[1] - end[1]
  1408. zoomFactor = 1
  1409. self.Zoom(zoomFactor, view)
  1410. def RecalculatePosition(self, ids):
  1411. for id in ids:
  1412. itype = self.instruction[id].type
  1413. if itype in ('map', 'rectangle'):
  1414. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1415. canvasToPaper = True)
  1416. self.RecalculateEN()
  1417. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1418. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1419. canvasToPaper = True)
  1420. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1421. canvasToPaper = True)[:2]
  1422. if itype in ('image', 'northArrow'):
  1423. self.RecalculateEN()
  1424. elif itype == 'point':
  1425. rect = self.pdcObj.GetIdBounds(id)
  1426. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = rect,
  1427. canvasToPaper = True)
  1428. rect.OffsetXY(rect.GetWidth()/2, rect.GetHeight()/2)
  1429. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = rect,
  1430. canvasToPaper = True)[:2]
  1431. self.RecalculateEN()
  1432. elif itype == 'line':
  1433. rect = self.pdcObj.GetIdBounds(id)
  1434. oldRect = self.instruction[id]['rect']
  1435. newRect = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = True)
  1436. xDiff = newRect[0] - oldRect[0]
  1437. yDiff = newRect[1] - oldRect[1]
  1438. self.instruction[id]['rect'] = newRect
  1439. point1 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][0]
  1440. point2 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][1]
  1441. self.instruction[id]['where'] = [point1, point2]
  1442. self.RecalculateEN()
  1443. elif itype == 'scalebar':
  1444. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1445. canvasToPaper = True)
  1446. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1447. elif itype == 'text':
  1448. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1449. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1450. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1451. if self.instruction[id]['rotate'] is not None:
  1452. rot = float(self.instruction[id]['rotate'])/180*pi
  1453. else:
  1454. rot = 0
  1455. if self.instruction[id]['ref'].split()[0] == 'lower':
  1456. y += extent[1]
  1457. elif self.instruction[id]['ref'].split()[0] == 'center':
  1458. y += extent[1]/2
  1459. if self.instruction[id]['ref'].split()[1] == 'right':
  1460. x += extent[0] * cos(rot)
  1461. y -= extent[0] * sin(rot)
  1462. elif self.instruction[id]['ref'].split()[1] == 'center':
  1463. x += extent[0]/2 * cos(rot)
  1464. y -= extent[0]/2 * sin(rot)
  1465. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = Rect2D(x, y, 0, 0),
  1466. canvasToPaper = True)[:2]
  1467. self.RecalculateEN()
  1468. def ComputeZoom(self, rect):
  1469. """Computes zoom factor and scroll view"""
  1470. zoomFactor = 1
  1471. cW, cH = self.GetClientSize()
  1472. cW = float(cW)
  1473. if rect.IsEmpty(): # clicked on canvas
  1474. zoomFactor = 1.5
  1475. if self.mouse['use'] == 'zoomout':
  1476. zoomFactor = 1./zoomFactor
  1477. x,y = self.mouse['begin']
  1478. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1479. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1480. else: #dragging
  1481. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1482. try:
  1483. zoomFactor = 1/max(rW/cW, rH/cH)
  1484. except ZeroDivisionError:
  1485. zoomFactor = 1
  1486. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1487. if abs(zoomFactor - 1) > 0.01:
  1488. zoomFactor = zoomFactor
  1489. else:
  1490. zoomFactor = 1.
  1491. if self.mouse['use'] == 'zoomout':
  1492. zoomFactor = min(rW/cW, rH/cH)
  1493. try:
  1494. if rW/rH > cW/cH:
  1495. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1496. xView = rect.GetX()
  1497. if self.mouse['use'] == 'zoomout':
  1498. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1499. xView, yView = -x, -y
  1500. else:
  1501. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1502. yView = rect.GetY()
  1503. if self.mouse['use'] == 'zoomout':
  1504. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1505. xView, yView = -x, -y
  1506. except ZeroDivisionError:
  1507. xView, yView = rect.GetX(), rect.GetY()
  1508. return zoomFactor, (int(xView), int(yView))
  1509. def Zoom(self, zoomFactor, view):
  1510. """Zoom to specified region, scroll view, redraw"""
  1511. if not self.currScale:
  1512. return
  1513. self.currScale = self.currScale*zoomFactor
  1514. if self.currScale > 10 or self.currScale < 0.1:
  1515. self.currScale = self.currScale/zoomFactor
  1516. return
  1517. if not self.preview:
  1518. # redraw paper
  1519. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1520. pRect.OffsetXY(-view[0], -view[1])
  1521. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1522. self.DrawPaper(pRect)
  1523. #redraw objects
  1524. for id in self.objectId:
  1525. type = self.instruction[id].type
  1526. if type == 'labels': # why it's here? it should not
  1527. continue
  1528. oRect = self.CanvasPaperCoordinates(
  1529. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1530. if type == 'text':
  1531. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1532. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1533. for i, coord in enumerate(coords)]
  1534. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1535. if self.instruction[id]['rotate']:
  1536. rot = float(self.instruction[id]['rotate'])
  1537. else:
  1538. rot = 0
  1539. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1540. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1541. coords = coords, bounds = bounds )
  1542. self.pdcObj.SetIdBounds(id, bounds)
  1543. elif type == 'northArrow':
  1544. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1545. drawid = id, pdctype = 'bitmap', bb = oRect)
  1546. elif type in ('point', 'line', 'rectangle'):
  1547. instr = self.instruction[id]
  1548. color = self.instruction[id]['color']
  1549. width = fcolor = coords = None
  1550. if type in ('point', 'rectangle'):
  1551. fcolor = self.instruction[id]['fcolor']
  1552. if type in ('line', 'rectangle'):
  1553. width = self.instruction[id]['width']
  1554. if type in ('line'):
  1555. point1, point2 = instr['where'][0], instr['where'][1]
  1556. point1 = self.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)),
  1557. canvasToPaper = False)[:2]
  1558. point2 = self.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)),
  1559. canvasToPaper = False)[:2]
  1560. coords = (point1, point2)
  1561. self.DrawGraphics(drawid = id, shape = type, bb = oRect, lineCoords = coords,
  1562. color = color, fcolor = fcolor, width = width)
  1563. else:
  1564. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1565. drawid = id, pdctype = 'rectText', bb = oRect)
  1566. #redraw tmp objects
  1567. if self.dragId != -1:
  1568. self.RedrawSelectBox(self.dragId)
  1569. #redraw preview
  1570. else: # preview mode
  1571. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1572. imageRect.OffsetXY(-view[0], -view[1])
  1573. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1574. self.DrawImage(imageRect)
  1575. def ZoomAll(self):
  1576. """Zoom to full extent"""
  1577. if not self.preview:
  1578. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1579. else:
  1580. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1581. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1582. zoomFactor, view = self.ComputeZoom(zoomP)
  1583. self.Zoom(zoomFactor, view)
  1584. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0), lineCoords = None):
  1585. """Draw object with given pen and brush.
  1586. :param pdc: PseudoDC
  1587. :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
  1588. :param bb: bounding box
  1589. :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
  1590. """
  1591. if drawid is None:
  1592. drawid = wx.NewId()
  1593. bb = bb.Get()
  1594. pdc.BeginDrawing()
  1595. pdc.RemoveId(drawid)
  1596. pdc.SetId(drawid)
  1597. pdc.SetPen(pen)
  1598. pdc.SetBrush(brush)
  1599. if pdctype == 'bitmap':
  1600. if havePILImage:
  1601. file = self.instruction[drawid]['epsfile']
  1602. rotation = self.instruction[drawid]['rotate']
  1603. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1604. else: # draw only rectangle with label
  1605. pdctype = 'rectText'
  1606. if pdctype in ('rect', 'rectText'):
  1607. pdc.DrawRectangle(*bb)
  1608. if pdctype == 'rectText':
  1609. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1610. font = dc.GetFont()
  1611. size = 10
  1612. font.SetPointSize(size)
  1613. font.SetStyle(wx.ITALIC)
  1614. dc.SetFont(font)
  1615. pdc.SetFont(font)
  1616. text = '\n'.join(self.itemLabels[drawid])
  1617. w,h,lh = dc.GetMultiLineTextExtent(text)
  1618. textExtent = (w,h)
  1619. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1620. r = map(int, bb)
  1621. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1622. size -= 2
  1623. font.SetPointSize(size)
  1624. dc.SetFont(font)
  1625. pdc.SetFont(font)
  1626. textExtent = dc.GetTextExtent(text)
  1627. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1628. pdc.SetTextForeground(wx.Colour(100,100,100,200))
  1629. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1630. pdc.DrawLabel(text = text, rect = textRect)
  1631. elif pdctype == 'point':
  1632. pdc.DrawCircle(x = bb[0] + bb[2] / 2,
  1633. y = bb[1] + bb[3] / 2,
  1634. radius = bb[2] / 2)
  1635. elif pdctype == 'line':
  1636. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  1637. pdc.SetIdBounds(drawid, bb)
  1638. pdc.EndDrawing()
  1639. self.Refresh()
  1640. return drawid
  1641. def DrawGraphics(self, drawid, shape, color, bb, width = None, fcolor = None, lineCoords = None):
  1642. """Draw point/line/rectangle with given color and width
  1643. :param drawid: id of drawn object
  1644. :param shape: drawn shape 'point'/'line'/'rectangle'
  1645. :param color: pen outline color ('RRR:GGG:BBB')
  1646. :param fcolor: brush fill color, if meaningful ('RRR:GGG:BBB')
  1647. :param width: pen width
  1648. :param bb: bounding box
  1649. :param lineCoords: line coordinates (for line only)
  1650. """
  1651. pdctype = {'point' : 'point',
  1652. 'line' : 'line',
  1653. 'rectangle' : 'rect'}
  1654. if color == 'none':
  1655. pen = wx.TRANSPARENT_PEN
  1656. else:
  1657. if width is not None:
  1658. units = UnitConversion(self)
  1659. width = int(units.convert(value = width, fromUnit = 'point', toUnit = 'pixel') * self.currScale)
  1660. else:
  1661. width = 2
  1662. pen = wx.Pen(colour = convertRGB(color), width = width)
  1663. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  1664. brush = wx.TRANSPARENT_BRUSH
  1665. if fcolor and fcolor != 'none':
  1666. brush = wx.Brush(colour = convertRGB(fcolor))
  1667. self.Draw(pen = pen, brush = brush, pdc = self.pdcObj, pdctype = pdctype[shape],
  1668. drawid = drawid, bb = bb, lineCoords = lineCoords)
  1669. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1670. """Draw bitmap using PIL"""
  1671. pImg = PILImage.open(filePath)
  1672. if sys.platform == 'win32' and \
  1673. 'eps' in os.path.splitext(filePath)[1].lower():
  1674. import types
  1675. pImg.load = types.MethodType(loadPSForWindows, pImg)
  1676. if rotation:
  1677. # get rid of black background
  1678. pImg = pImg.convert("RGBA")
  1679. rot = pImg.rotate(rotation, expand = 1)
  1680. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1681. pImg = PILImage.composite(rot, new, rot)
  1682. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1683. img = PilImageToWxImage(pImg)
  1684. bitmap = img.ConvertToBitmap()
  1685. mask = wx.Mask(bitmap, wx.WHITE)
  1686. bitmap.SetMask(mask)
  1687. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1688. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1689. if textDict['rotate']:
  1690. rot = float(textDict['rotate'])
  1691. else:
  1692. rot = 0
  1693. if textDict['background'] != 'none':
  1694. background = textDict['background']
  1695. else:
  1696. background = None
  1697. pdc.RemoveId(drawId)
  1698. pdc.SetId(drawId)
  1699. pdc.BeginDrawing()
  1700. # border is not redrawn when zoom changes, why?
  1701. ## if textDict['border'] != 'none' and not rot:
  1702. ## units = UnitConversion(self)
  1703. ## borderWidth = units.convert(value = textDict['width'],
  1704. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1705. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1706. ## pdc.DrawRectangle(*bounds)
  1707. if background:
  1708. pdc.SetTextBackground(convertRGB(background))
  1709. pdc.SetBackgroundMode(wx.SOLID)
  1710. else:
  1711. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1712. fn = self.parent.makePSFont(textDict)
  1713. pdc.SetFont(fn)
  1714. pdc.SetTextForeground(convertRGB(textDict['color']))
  1715. if rot == 0:
  1716. pdc.DrawLabel(text=textDict['text'], rect=bounds)
  1717. else:
  1718. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1719. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1720. self.Refresh()
  1721. pdc.EndDrawing()
  1722. def DrawImage(self, rect):
  1723. """Draw preview image to pseudoDC"""
  1724. self.pdcImage.ClearId(self.imageId)
  1725. self.pdcImage.SetId(self.imageId)
  1726. img = self.image
  1727. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1728. img = img.Scale(rect.width, rect.height)
  1729. bitmap = img.ConvertToBitmap()
  1730. self.pdcImage.BeginDrawing()
  1731. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1732. self.pdcImage.SetIdBounds(self.imageId, rect)
  1733. self.pdcImage.EndDrawing()
  1734. self.Refresh()
  1735. def DrawPaper(self, rect):
  1736. """Draw paper and margins"""
  1737. page = self.instruction[self.pageId]
  1738. scale = page['Width'] / rect.GetWidth()
  1739. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1740. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1741. x = page['Left'] / scale + rect.GetX()
  1742. y = page['Top'] / scale + rect.GetY()
  1743. self.pdcPaper.BeginDrawing()
  1744. self.pdcPaper.RemoveId(self.pageId)
  1745. self.pdcPaper.SetId(self.pageId)
  1746. self.pdcPaper.SetPen(self.pen['paper'])
  1747. self.pdcPaper.SetBrush(self.brush['paper'])
  1748. self.pdcPaper.DrawRectangleRect(rect)
  1749. self.pdcPaper.SetPen(self.pen['margins'])
  1750. self.pdcPaper.SetBrush(self.brush['margins'])
  1751. self.pdcPaper.DrawRectangle(x, y, w, h)
  1752. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1753. self.pdcPaper.EndDrawing()
  1754. self.Refresh()
  1755. def ImageRect(self):
  1756. """Returns image centered in canvas, computes scale"""
  1757. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1758. cW, cH = self.GetClientSize()
  1759. iW, iH = img.GetWidth(), img.GetHeight()
  1760. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1761. iW = iW * self.currScale
  1762. iH = iH * self.currScale
  1763. x = cW/2 - iW/2
  1764. y = cH/2 - iH/2
  1765. imageRect = wx.Rect(x, y, iW, iH)
  1766. return imageRect
  1767. def RedrawSelectBox(self, id):
  1768. """Redraws select box when selected object changes its size"""
  1769. if self.dragId == id:
  1770. rect = self.pdcObj.GetIdBounds(id)
  1771. if self.instruction[id].type != 'line':
  1772. rect = rect.Inflate(3,3)
  1773. # draw select box around object
  1774. self.Draw(pen = self.pen['select'], brush = self.brush['select'], pdc = self.pdcTmp,
  1775. drawid = self.idBoxTmp, pdctype = 'rect', bb = rect)
  1776. # draw small marks signalizing resizing
  1777. if self.instruction[id].type in ('map', 'rectangle'):
  1778. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1779. rect = wx.RectPS(controlP, self.resizeBoxSize)
  1780. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1781. drawid = self.idResizeBoxTmp, pdctype = 'rect', bb = rect)
  1782. elif self.instruction[id].type == 'line':
  1783. p1Paper = self.instruction[id]['where'][0]
  1784. p2Paper = self.instruction[id]['where'][1]
  1785. p1Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p1Paper, (0, 0)), canvasToPaper = False)[:2]
  1786. p2Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p2Paper, (0, 0)), canvasToPaper = False)[:2]
  1787. rect = []
  1788. box = wx.RectS(self.resizeBoxSize)
  1789. rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
  1790. rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
  1791. for i, point in enumerate((p1Canvas, p2Canvas)):
  1792. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1793. drawid = self.idLinePointsTmp[i], pdctype = 'rect', bb = rect[i])
  1794. def UpdateMapLabel(self):
  1795. """Updates map frame label"""
  1796. vector = self.instruction.FindInstructionByType('vector')
  1797. if vector:
  1798. vectorId = vector.id
  1799. else:
  1800. vectorId = None
  1801. raster = self.instruction.FindInstructionByType('raster')
  1802. if raster:
  1803. rasterId = raster.id
  1804. else:
  1805. rasterId = None
  1806. rasterName = 'None'
  1807. if rasterId:
  1808. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1809. mapId = self.instruction.FindInstructionByType('map').id
  1810. self.itemLabels[mapId] = []
  1811. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1812. self.itemLabels[mapId].append("raster: " + rasterName)
  1813. if vectorId:
  1814. for map in self.instruction[vectorId]['list']:
  1815. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1816. labels = self.instruction.FindInstructionByType('labels')
  1817. if labels:
  1818. labelFiles = self.instruction[labels.id]['labels']
  1819. if not labelFiles:
  1820. return
  1821. labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
  1822. self.itemLabels[mapId].append(_("labels: ") + ', '.join(labelFiles))
  1823. def UpdateLabel(self, itype, id):
  1824. self.itemLabels[id] = []
  1825. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1826. if itype == 'image':
  1827. file = os.path.basename(self.instruction[id]['epsfile'])
  1828. self.itemLabels[id].append(file)
  1829. def OnSize(self, event):
  1830. """Init image size to match window size
  1831. """
  1832. # not zoom all when notebook page is changed
  1833. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1834. self.ZoomAll()
  1835. self.OnIdle(None)
  1836. event.Skip()
  1837. def OnIdle(self, event):
  1838. """Only re-render a image during idle time instead of
  1839. multiple times during resizing.
  1840. """
  1841. width, height = self.GetClientSize()
  1842. # Make new off screen bitmap: this bitmap will always have the
  1843. # current drawing in it, so it can be used to save the image
  1844. # to a file, or whatever.
  1845. self._buffer = wx.EmptyBitmap(width, height)
  1846. # re-render image on idle
  1847. self.resize = True
  1848. def ScaleRect(self, rect, scale):
  1849. """Scale rectangle"""
  1850. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1851. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)