frame.py 98 KB

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