frame.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581
  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=_("GRASS GIS 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', '30000000', 'setvmthreshold',
  349. '-f', 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 = round(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 = (
  1198. units.convert(value=-pRect.x, fromUnit="pixel", toUnit="inch") / scale
  1199. ) # inch, real, negative
  1200. pRecty = (
  1201. units.convert(value=-pRect.y, fromUnit="pixel", toUnit="inch") / scale
  1202. )
  1203. Width = units.convert(value=rect.GetWidth(), fromUnit=fromU, toUnit=toU) * scale
  1204. Height = (
  1205. units.convert(value=rect.GetHeight(), fromUnit=fromU, toUnit=toU) * scale
  1206. )
  1207. X = (
  1208. units.convert(value=(rect.GetX() - pRectx), fromUnit=fromU, toUnit=toU)
  1209. * scale
  1210. )
  1211. Y = (
  1212. units.convert(value=(rect.GetY() - pRecty), fromUnit=fromU, toUnit=toU)
  1213. * scale
  1214. )
  1215. if canvasToPaper:
  1216. return Rect2D(X, Y, Width, Height)
  1217. return Rect2D(int(X), int(Y), int(Width), int(Height))
  1218. def SetPage(self):
  1219. """Sets and changes page, redraws paper"""
  1220. page = self.instruction[self.pageId]
  1221. if not page:
  1222. page = PageSetup(id=self.pageId, env=self.env)
  1223. self.instruction.AddInstruction(page)
  1224. ppi = wx.ClientDC(self).GetPPI()
  1225. cW, cH = self.GetClientSize()
  1226. pW, pH = page['Width'] * ppi[0], page['Height'] * ppi[1]
  1227. if self.currScale is None:
  1228. self.currScale = min(cW / pW, cH / pH)
  1229. pW = pW * self.currScale
  1230. pH = pH * self.currScale
  1231. x = cW / 2 - pW / 2
  1232. y = cH / 2 - pH / 2
  1233. self.DrawPaper(Rect(int(x), int(y), int(pW), int(pH)))
  1234. def modifyRectangle(self, r):
  1235. """Recalculates rectangle not to have negative size"""
  1236. if r.GetWidth() < 0:
  1237. r.SetX(r.GetX() + r.GetWidth())
  1238. if r.GetHeight() < 0:
  1239. r.SetY(r.GetY() + r.GetHeight())
  1240. r.SetWidth(abs(r.GetWidth()))
  1241. r.SetHeight(abs(r.GetHeight()))
  1242. return r
  1243. def RecalculateEN(self):
  1244. """Recalculate east and north for texts (eps, points) after their or map's movement"""
  1245. try:
  1246. mapId = self.instruction.FindInstructionByType('map').id
  1247. except AttributeError:
  1248. mapId = self.instruction.FindInstructionByType('initMap').id
  1249. for itemType in ('text', 'image', 'northArrow',
  1250. 'point', 'line', 'rectangle'):
  1251. items = self.instruction.FindInstructionByType(itemType, list=True)
  1252. for item in items:
  1253. instr = self.instruction[item.id]
  1254. if itemType in ('line', 'rectangle'):
  1255. if itemType == 'line':
  1256. e1, n1 = PaperMapCoordinates(
  1257. mapInstr=self.instruction[mapId],
  1258. x=instr['where'][0][0],
  1259. y=instr['where'][0][1],
  1260. paperToMap=True,
  1261. env=self.env)
  1262. e2, n2 = PaperMapCoordinates(
  1263. mapInstr=self.instruction[mapId],
  1264. x=instr['where'][1][0],
  1265. y=instr['where'][1][1],
  1266. paperToMap=True,
  1267. env=self.env)
  1268. else:
  1269. e1, n1 = PaperMapCoordinates(
  1270. mapInstr=self.instruction[mapId],
  1271. x=instr['rect'].GetLeft(),
  1272. y=instr['rect'].GetTop(),
  1273. paperToMap=True,
  1274. env=self.env)
  1275. e2, n2 = PaperMapCoordinates(
  1276. mapInstr=self.instruction[mapId],
  1277. x=instr['rect'].GetRight(),
  1278. y=instr['rect'].GetBottom(),
  1279. paperToMap=True,
  1280. env=self.env)
  1281. instr['east1'] = e1
  1282. instr['north1'] = n1
  1283. instr['east2'] = e2
  1284. instr['north2'] = n2
  1285. else:
  1286. e, n = PaperMapCoordinates(
  1287. mapInstr=self.instruction[mapId],
  1288. x=instr['where'][0],
  1289. y=instr['where'][1],
  1290. paperToMap=True,
  1291. env=self.env)
  1292. instr['east'], instr['north'] = e, n
  1293. def OnPaint(self, event):
  1294. """Draw pseudo DC to buffer
  1295. """
  1296. if not self._buffer:
  1297. return
  1298. dc = wx.BufferedPaintDC(self, self._buffer)
  1299. # use PrepareDC to set position correctly
  1300. # probably does nothing, removed from wxPython 2.9
  1301. # self.PrepareDC(dc)
  1302. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1303. dc.Clear()
  1304. # draw paper
  1305. if not self.preview:
  1306. self.pdcPaper.DrawToDC(dc)
  1307. # draw to the DC using the calculated clipping rect
  1308. rgn = self.GetUpdateRegion()
  1309. if not self.preview:
  1310. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1311. else:
  1312. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1313. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1314. def MouseActions(self, event):
  1315. """Mouse motion and button click notifier
  1316. """
  1317. disable = self.preview and self.mouse['use'] in ('pointer', 'resize',
  1318. 'addMap', 'addPoint',
  1319. 'addLine', 'addRectangle')
  1320. # zoom with mouse wheel
  1321. if event.GetWheelRotation() != 0:
  1322. self.OnMouseWheel(event)
  1323. # left mouse button pressed
  1324. elif event.LeftDown() and not disable:
  1325. self.OnLeftDown(event)
  1326. # left mouse button released
  1327. elif event.LeftUp() and not disable:
  1328. self.OnLeftUp(event)
  1329. # dragging
  1330. elif event.Dragging() and not disable:
  1331. self.OnDragging(event)
  1332. # double click
  1333. elif event.ButtonDClick() and not disable:
  1334. self.OnButtonDClick(event)
  1335. # middle mouse button pressed
  1336. elif event.MiddleDown():
  1337. self.OnMiddleDown(event)
  1338. elif event.Moving():
  1339. self.OnMouseMoving(event)
  1340. def OnMouseWheel(self, event):
  1341. """Mouse wheel scrolled.
  1342. Changes zoom."""
  1343. if UserSettings.Get(group='display',
  1344. key='mouseWheelZoom',
  1345. subkey='selection') == 2:
  1346. event.Skip()
  1347. return
  1348. zoom = event.GetWheelRotation()
  1349. oldUse = self.mouse['use']
  1350. self.mouse['begin'] = event.GetPosition()
  1351. if UserSettings.Get(group='display',
  1352. key='scrollDirection',
  1353. subkey='selection'):
  1354. zoom *= -1
  1355. if zoom > 0:
  1356. self.mouse['use'] = 'zoomin'
  1357. else:
  1358. self.mouse['use'] = 'zoomout'
  1359. zoomFactor, view = self.ComputeZoom(Rect(0, 0, 0, 0))
  1360. self.Zoom(zoomFactor, view)
  1361. self.mouse['use'] = oldUse
  1362. def OnMouseMoving(self, event):
  1363. """Mouse cursor moving.
  1364. Change cursor when moving over resize marker.
  1365. """
  1366. if self.preview:
  1367. return
  1368. if self.mouse['use'] in ('pointer', 'resize'):
  1369. pos = event.GetPosition()
  1370. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1371. if foundResize and foundResize[0] in (
  1372. self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1373. self.SetCursor(self.cursors["sizenwse"])
  1374. self.parent.SetStatusText(
  1375. _('Click and drag to resize object'), 0)
  1376. self.showResizeHelp = True
  1377. else:
  1378. if self.showResizeHelp:
  1379. self.parent.SetStatusText('', 0)
  1380. self.SetCursor(self.cursors["default"])
  1381. self.showResizeHelp = False
  1382. def OnLeftDown(self, event):
  1383. """Left mouse button pressed.
  1384. Select objects, redraw, prepare for moving/resizing.
  1385. """
  1386. self.mouse['begin'] = event.GetPosition()
  1387. self.begin = self.mouse['begin']
  1388. # select
  1389. if self.mouse['use'] == 'pointer':
  1390. found = self.pdcObj.FindObjects(
  1391. self.mouse['begin'][0],
  1392. self.mouse['begin'][1])
  1393. foundResize = self.pdcTmp.FindObjects(
  1394. self.mouse['begin'][0], self.mouse['begin'][1])
  1395. if foundResize and foundResize[0] in (
  1396. self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1397. self.mouse['use'] = 'resize'
  1398. # when resizing, proportions match region
  1399. if self.instruction[self.dragId].type == 'map':
  1400. self.constraint = False
  1401. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1402. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1403. self.constraint = True
  1404. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1405. if self.instruction[self.dragId].type == 'line':
  1406. self.currentLinePoint = self.idLinePointsTmp.index(
  1407. foundResize
  1408. [0])
  1409. elif found:
  1410. self.dragId = found[0]
  1411. self.RedrawSelectBox(self.dragId)
  1412. if self.instruction[
  1413. self.dragId].type not in (
  1414. 'map', 'rectangle'):
  1415. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1416. self.Refresh()
  1417. if self.instruction[self.dragId].type != 'line':
  1418. for id in self.idLinePointsTmp:
  1419. self.pdcTmp.RemoveId(id)
  1420. self.Refresh()
  1421. else:
  1422. self.dragId = -1
  1423. self.pdcTmp.RemoveId(self.idBoxTmp)
  1424. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1425. for id in self.idLinePointsTmp:
  1426. self.pdcTmp.RemoveId(id)
  1427. self.Refresh()
  1428. def OnLeftUp(self, event):
  1429. """Left mouse button released.
  1430. Recalculate zooming/resizing/moving and redraw.
  1431. """
  1432. # zoom in, zoom out
  1433. if self.mouse['use'] in ('zoomin', 'zoomout'):
  1434. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1435. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1436. self.Refresh()
  1437. zoomFactor, view = self.ComputeZoom(zoomR)
  1438. self.Zoom(zoomFactor, view)
  1439. # draw map frame
  1440. if self.mouse['use'] == 'addMap':
  1441. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1442. # too small rectangle, it's usually some mistake
  1443. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1444. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1445. self.Refresh()
  1446. return
  1447. rectPaper = self.CanvasPaperCoordinates(
  1448. rect=rectTmp, canvasToPaper=True)
  1449. dlg = MapDialog(
  1450. parent=self.parent, id=[None, None, None],
  1451. settings=self.instruction, env=self.env, rect=rectPaper)
  1452. self.openDialogs['map'] = dlg
  1453. self.openDialogs['map'].Show()
  1454. self.parent.toolbar.SelectDefault()
  1455. return
  1456. # resize resizable objects (map, line, rectangle)
  1457. if self.mouse['use'] == 'resize':
  1458. mapObj = self.instruction.FindInstructionByType('map')
  1459. if not mapObj:
  1460. mapObj = self.instruction.FindInstructionByType('initMap')
  1461. mapId = mapObj.id
  1462. if self.dragId == mapId:
  1463. # necessary to change either map frame (scaleType 0,1,2) or
  1464. # region (scaletype 3)
  1465. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1466. newRectPaper = self.CanvasPaperCoordinates(
  1467. rect=newRectCanvas, canvasToPaper=True)
  1468. self.instruction[mapId]['rect'] = newRectPaper
  1469. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1470. if self.instruction[mapId]['scaleType'] == 0:
  1471. scale, foo, rect = AutoAdjust(
  1472. self, scaleType=0, map=self.instruction[mapId]
  1473. ['map'], env=self.env,
  1474. mapType=self.instruction[mapId]['mapType'],
  1475. rect=self.instruction[mapId]['rect'])
  1476. elif self.instruction[mapId]['scaleType'] == 1:
  1477. scale, foo, rect = AutoAdjust(
  1478. self, scaleType=1, env=self.env,
  1479. region=self.instruction[mapId]['region'],
  1480. rect=self.instruction[mapId]['rect'])
  1481. else:
  1482. scale, foo, rect = AutoAdjust(
  1483. self, scaleType=2, rect=self.instruction[mapId]['rect'],
  1484. env=self.env)
  1485. self.instruction[mapId]['rect'] = rect
  1486. self.instruction[mapId]['scale'] = scale
  1487. rectCanvas = self.CanvasPaperCoordinates(
  1488. rect=rect, canvasToPaper=False)
  1489. self.Draw(
  1490. pen=self.pen['map'],
  1491. brush=self.brush['map'],
  1492. pdc=self.pdcObj,
  1493. drawid=mapId,
  1494. pdctype='rectText',
  1495. bb=rectCanvas)
  1496. elif self.instruction[mapId]['scaleType'] == 3:
  1497. ComputeSetRegion(
  1498. self, mapDict=self.instruction[mapId].GetInstruction(), env=self.env)
  1499. # check resolution
  1500. SetResolution(dpi=self.instruction[mapId]['resolution'],
  1501. width=self.instruction[mapId]['rect'].width,
  1502. height=self.instruction[mapId]['rect'].height,
  1503. env=self.env)
  1504. self.RedrawSelectBox(mapId)
  1505. self.Zoom(zoomFactor=1, view=(0, 0))
  1506. elif self.instruction[self.dragId].type == 'line':
  1507. points = self.instruction[self.dragId]['where']
  1508. self.instruction[
  1509. self.dragId]['rect'] = Rect2DPP(
  1510. points[0], points[1])
  1511. self.RecalculatePosition(ids=[self.dragId])
  1512. elif self.instruction[self.dragId].type == 'rectangle':
  1513. self.RecalculatePosition(ids=[self.dragId])
  1514. self.mouse['use'] = 'pointer'
  1515. # recalculate the position of objects after dragging
  1516. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1517. if self.mouse['begin'] != event.GetPosition(): # for double click
  1518. self.RecalculatePosition(ids=[self.dragId])
  1519. if self.instruction[self.dragId].type in self.openDialogs:
  1520. self.openDialogs[
  1521. self.instruction[
  1522. self.dragId].type].updateDialog()
  1523. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1524. endCoordinates = self.CanvasPaperCoordinates(rect=Rect(
  1525. event.GetX(), event.GetY(), 0, 0), canvasToPaper=True)[:2]
  1526. diffX = event.GetX() - self.mouse['begin'][0]
  1527. diffY = event.GetY() - self.mouse['begin'][1]
  1528. if self.mouse['use'] == 'addPoint':
  1529. self.parent.AddPoint(coordinates=endCoordinates)
  1530. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1531. # not too small lines/rectangles
  1532. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1533. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1534. self.Refresh()
  1535. return
  1536. beginCoordinates = self.CanvasPaperCoordinates(
  1537. rect=Rect(
  1538. self.mouse['begin'][0],
  1539. self.mouse['begin'][1],
  1540. 0, 0),
  1541. canvasToPaper=True)[
  1542. : 2]
  1543. if self.mouse['use'] == 'addLine':
  1544. self.parent.AddLine(
  1545. coordinates=[
  1546. beginCoordinates,
  1547. endCoordinates])
  1548. else:
  1549. self.parent.AddRectangle(
  1550. coordinates=[
  1551. beginCoordinates,
  1552. endCoordinates])
  1553. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1554. self.Refresh()
  1555. def OnButtonDClick(self, event):
  1556. """Open object dialog for editing."""
  1557. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1558. itemCall = {'text': self.parent.OnAddText,
  1559. 'mapinfo': self.parent.OnAddMapinfo,
  1560. 'scalebar': self.parent.OnAddScalebar,
  1561. 'image': self.parent.OnAddImage,
  1562. 'northArrow': self.parent.OnAddNorthArrow,
  1563. 'point': self.parent.AddPoint,
  1564. 'line': self.parent.AddLine,
  1565. 'rectangle': self.parent.AddRectangle,
  1566. 'rasterLegend': self.parent.OnAddLegend,
  1567. 'vectorLegend': self.parent.OnAddLegend,
  1568. 'map': self.parent.OnAddMap}
  1569. itemArg = {'text': dict(event=None, id=self.dragId),
  1570. 'mapinfo': dict(event=None),
  1571. 'scalebar': dict(event=None),
  1572. 'image': dict(event=None, id=self.dragId),
  1573. 'northArrow': dict(event=None, id=self.dragId),
  1574. 'point': dict(id=self.dragId),
  1575. 'line': dict(id=self.dragId),
  1576. 'rectangle': dict(id=self.dragId),
  1577. 'rasterLegend': dict(event=None),
  1578. 'vectorLegend': dict(event=None, page=1),
  1579. 'map': dict(event=None, notebook=True)}
  1580. type = self.instruction[self.dragId].type
  1581. itemCall[type](**itemArg[type])
  1582. def OnDragging(self, event):
  1583. """Process panning/resizing/drawing/moving."""
  1584. if event.MiddleIsDown():
  1585. # panning
  1586. self.mouse['end'] = event.GetPosition()
  1587. self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
  1588. self.mouse['begin'] = event.GetPosition()
  1589. elif event.LeftIsDown():
  1590. # draw box when zooming, creating map
  1591. if self.mouse['use'] in (
  1592. 'zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1593. self.mouse['end'] = event.GetPosition()
  1594. r = Rect(
  1595. self.mouse['begin'][0],
  1596. self.mouse['begin'][1],
  1597. self.mouse['end'][0] -
  1598. self.mouse['begin'][0],
  1599. self.mouse['end'][1] -
  1600. self.mouse['begin'][1])
  1601. r = self.modifyRectangle(r)
  1602. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1603. if self.mouse['use'] == 'addLine':
  1604. pdcType = 'line'
  1605. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1606. else:
  1607. pdcType = 'rect'
  1608. lineCoords = None
  1609. if r[2] < 2 or r[3] < 2:
  1610. # to avoid strange behavoiur
  1611. return
  1612. self.Draw(pen=self.pen['line'], brush=self.brush['line'],
  1613. pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
  1614. pdctype=pdcType, bb=r, lineCoords=lineCoords)
  1615. else:
  1616. self.Draw(pen=self.pen['box'], brush=self.brush['box'],
  1617. pdc=self.pdcTmp, drawid=self.idZoomBoxTmp,
  1618. pdctype='rect', bb=r)
  1619. # panning
  1620. if self.mouse["use"] == 'pan':
  1621. self.mouse['end'] = event.GetPosition()
  1622. self.Pan(begin=self.mouse['begin'], end=self.mouse['end'])
  1623. self.mouse['begin'] = event.GetPosition()
  1624. # move object
  1625. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1626. self.mouse['end'] = event.GetPosition()
  1627. dx, dy = self.mouse['end'][
  1628. 0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1629. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1630. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1631. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1632. for id in self.idLinePointsTmp:
  1633. self.pdcTmp.TranslateId(id, dx, dy)
  1634. if self.instruction[self.dragId].type == 'text':
  1635. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId][
  1636. 'coords'][0] + dx, self.instruction[self.dragId]['coords'][1] + dy
  1637. self.begin = event.GetPosition()
  1638. self.Refresh()
  1639. # resize object
  1640. if self.mouse['use'] == 'resize':
  1641. pos = event.GetPosition()
  1642. diffX = pos[0] - self.mouse['begin'][0]
  1643. diffY = pos[1] - self.mouse['begin'][1]
  1644. if self.instruction[self.dragId].type == 'map':
  1645. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1646. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1647. # match given region
  1648. if self.constraint:
  1649. if width > height:
  1650. newWidth = width + diffX
  1651. newHeight = height + diffX * \
  1652. (float(height) / width)
  1653. else:
  1654. newWidth = width + diffY * (float(width) / height)
  1655. newHeight = height + diffY
  1656. else:
  1657. newWidth = width + diffX
  1658. newHeight = height + diffY
  1659. if newWidth < 10 or newHeight < 10:
  1660. return
  1661. bounds = Rect(x, y, newWidth, newHeight)
  1662. self.Draw(
  1663. pen=self.pen['map'],
  1664. brush=self.brush['map'],
  1665. pdc=self.pdcObj,
  1666. drawid=self.dragId,
  1667. pdctype='rectText',
  1668. bb=bounds)
  1669. elif self.instruction[self.dragId].type == 'rectangle':
  1670. instr = self.instruction[self.dragId]
  1671. rect = self.CanvasPaperCoordinates(
  1672. rect=instr['rect'], canvasToPaper=False)
  1673. rect.SetWidth(rect.GetWidth() + diffX)
  1674. rect.SetHeight(rect.GetHeight() + diffY)
  1675. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1676. return
  1677. self.DrawGraphics(
  1678. drawid=self.dragId,
  1679. shape='rectangle',
  1680. color=instr['color'],
  1681. fcolor=instr['fcolor'],
  1682. width=instr['width'],
  1683. bb=rect)
  1684. elif self.instruction[self.dragId].type == 'line':
  1685. instr = self.instruction[self.dragId]
  1686. points = instr['where']
  1687. # moving point
  1688. if self.currentLinePoint == 0:
  1689. pPaper = points[1]
  1690. else:
  1691. pPaper = points[0]
  1692. pCanvas = self.CanvasPaperCoordinates(
  1693. rect=Rect2DPS(pPaper, (0, 0)), canvasToPaper=False)[:2]
  1694. bounds = wx.Rect(pCanvas, pos)
  1695. self.DrawGraphics(
  1696. drawid=self.dragId,
  1697. shape='line',
  1698. color=instr['color'],
  1699. width=instr['width'],
  1700. bb=bounds,
  1701. lineCoords=(
  1702. pos,
  1703. pCanvas))
  1704. # update paper coordinates
  1705. points[self.currentLinePoint] = self.CanvasPaperCoordinates(
  1706. rect=Rect(pos[0], pos[1], 0, 0), canvasToPaper=True)[:2]
  1707. self.RedrawSelectBox(self.dragId)
  1708. def OnMiddleDown(self, event):
  1709. """Middle mouse button pressed."""
  1710. self.mouse['begin'] = event.GetPosition()
  1711. def Pan(self, begin, end):
  1712. """Move canvas while dragging.
  1713. :param begin: x,y coordinates of first point
  1714. :param end: x,y coordinates of second point
  1715. """
  1716. view = begin[0] - end[0], begin[1] - end[1]
  1717. zoomFactor = 1
  1718. self.Zoom(zoomFactor, view)
  1719. def RecalculatePosition(self, ids):
  1720. for id in ids:
  1721. itype = self.instruction[id].type
  1722. if itype in ('map', 'rectangle'):
  1723. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1724. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1725. self.RecalculateEN()
  1726. elif itype in ('mapinfo', 'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1727. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1728. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1729. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1730. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)[:2]
  1731. if itype in ('image', 'northArrow'):
  1732. self.RecalculateEN()
  1733. elif itype == 'point':
  1734. rect = self.pdcObj.GetIdBounds(id)
  1735. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1736. rect=rect, canvasToPaper=True)
  1737. rect.Offset(
  1738. dx=rect.GetWidth() / 2, dy=rect.GetHeight() / 2,
  1739. )
  1740. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1741. rect=rect, canvasToPaper=True)[: 2]
  1742. self.RecalculateEN()
  1743. elif itype == 'line':
  1744. rect = self.pdcObj.GetIdBounds(id)
  1745. oldRect = self.instruction[id]['rect']
  1746. newRect = self.CanvasPaperCoordinates(
  1747. rect=rect, canvasToPaper=True)
  1748. xDiff = newRect[0] - oldRect[0]
  1749. yDiff = newRect[1] - oldRect[1]
  1750. self.instruction[id]['rect'] = newRect
  1751. point1 = wx.Point2D(*self.instruction[id]['where'][0])
  1752. point2 = wx.Point2D(*self.instruction[id]['where'][1])
  1753. point1 += wx.Point2D(xDiff, yDiff)
  1754. point2 += wx.Point2D(xDiff, yDiff)
  1755. self.instruction[id]['where'] = [point1, point2]
  1756. self.RecalculateEN()
  1757. elif itype == 'scalebar':
  1758. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(
  1759. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True)
  1760. self.instruction[id]['where'] = self.instruction[
  1761. id]['rect'].GetCentre()
  1762. elif itype == 'text':
  1763. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1764. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1765. extent = self.parent.getTextExtent(
  1766. textDict=self.instruction[id])
  1767. if self.instruction[id]['rotate'] is not None:
  1768. rot = float(self.instruction[id]['rotate']) / 180 * pi
  1769. else:
  1770. rot = 0
  1771. if self.instruction[id]['ref'].split()[0] == 'lower':
  1772. y += extent[1]
  1773. elif self.instruction[id]['ref'].split()[0] == 'center':
  1774. y += extent[1] / 2
  1775. if self.instruction[id]['ref'].split()[1] == 'right':
  1776. x += extent[0] * cos(rot)
  1777. y -= extent[0] * sin(rot)
  1778. elif self.instruction[id]['ref'].split()[1] == 'center':
  1779. x += extent[0] / 2 * cos(rot)
  1780. y -= extent[0] / 2 * sin(rot)
  1781. self.instruction[id]['where'] = self.CanvasPaperCoordinates(
  1782. rect=Rect2D(x, y, 0, 0), canvasToPaper=True)[:2]
  1783. self.RecalculateEN()
  1784. def ComputeZoom(self, rect):
  1785. """Computes zoom factor and scroll view"""
  1786. zoomFactor = 1
  1787. cW, cH = self.GetClientSize()
  1788. cW = float(cW)
  1789. if rect.IsEmpty(): # clicked on canvas
  1790. zoomFactor = 1.5
  1791. if self.mouse['use'] == 'zoomout':
  1792. zoomFactor = 1. / zoomFactor
  1793. x, y = self.mouse['begin']
  1794. xView = x - x / zoomFactor # x - cW/(zoomFactor * 2)
  1795. yView = y - y / zoomFactor # y - cH/(zoomFactor * 2)
  1796. else: # dragging
  1797. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1798. try:
  1799. zoomFactor = 1 / max(rW / cW, rH / cH)
  1800. except ZeroDivisionError:
  1801. zoomFactor = 1
  1802. # when zooming to full extent, in some cases, there was zoom
  1803. # 1.01..., which causes problem
  1804. if abs(zoomFactor - 1) > 0.01:
  1805. zoomFactor = zoomFactor
  1806. else:
  1807. zoomFactor = 1.
  1808. if self.mouse['use'] == 'zoomout':
  1809. zoomFactor = min(rW / cW, rH / cH)
  1810. try:
  1811. if rW / rH > cW / cH:
  1812. yView = rect.GetY() - (rW * (cH / cW) - rH) / 2
  1813. xView = rect.GetX()
  1814. if self.mouse['use'] == 'zoomout':
  1815. x, y = rect.GetX() + (rW - (cW / cH) * rH) / 2, rect.GetY()
  1816. xView, yView = -x, -y
  1817. else:
  1818. xView = rect.GetX() - (rH * (cW / cH) - rW) / 2
  1819. yView = rect.GetY()
  1820. if self.mouse['use'] == 'zoomout':
  1821. x, y = rect.GetX(), rect.GetY() + (rH - (cH / cW) * rW) / 2
  1822. xView, yView = -x, -y
  1823. except ZeroDivisionError:
  1824. xView, yView = rect.GetX(), rect.GetY()
  1825. return zoomFactor, (int(xView), int(yView))
  1826. def Zoom(self, zoomFactor, view):
  1827. """Zoom to specified region, scroll view, redraw"""
  1828. if not self.currScale:
  1829. return
  1830. self.currScale = self.currScale * zoomFactor
  1831. if self.currScale > 10 or self.currScale < 0.1:
  1832. self.currScale = self.currScale / zoomFactor
  1833. return
  1834. if not self.preview:
  1835. # redraw paper
  1836. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1837. if globalvar.wxPythonPhoenix:
  1838. pRect.Offset(-view[0], -view[1])
  1839. else:
  1840. pRect.OffsetXY(-view[0], -view[1])
  1841. pRect = self.ScaleRect(rect=pRect, scale=zoomFactor)
  1842. self.DrawPaper(pRect)
  1843. # redraw objects
  1844. for id in self.objectId:
  1845. type = self.instruction[id].type
  1846. if type == 'labels': # why it's here? it should not
  1847. continue
  1848. oRect = self.CanvasPaperCoordinates(
  1849. rect=self.instruction[id]['rect'], canvasToPaper=False)
  1850. if type == 'text':
  1851. # recalculate coordinates, they are not equal to BB
  1852. coords = self.instruction[id]['coords']
  1853. self.instruction[id]['coords'] = coords = [
  1854. (int(coord) - view[i]) * zoomFactor for i, coord in enumerate(coords)]
  1855. extent = self.parent.getTextExtent(
  1856. textDict=self.instruction[id])
  1857. if self.instruction[id]['rotate']:
  1858. rot = float(self.instruction[id]['rotate'])
  1859. else:
  1860. rot = 0
  1861. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(
  1862. coords[0], coords[1], extent, rot)
  1863. self.DrawRotText(
  1864. pdc=self.pdcObj,
  1865. drawId=id,
  1866. textDict=self.instruction[id],
  1867. coords=coords,
  1868. bounds=bounds)
  1869. self.pdcObj.SetIdBounds(id, bounds)
  1870. elif type == 'northArrow':
  1871. self.Draw(
  1872. pen=self.pen[type],
  1873. brush=self.brush[type],
  1874. pdc=self.pdcObj,
  1875. drawid=id,
  1876. pdctype='bitmap',
  1877. bb=oRect)
  1878. elif type in ('point', 'line', 'rectangle'):
  1879. instr = self.instruction[id]
  1880. color = self.instruction[id]['color']
  1881. width = fcolor = coords = None
  1882. if type in ('point', 'rectangle'):
  1883. fcolor = self.instruction[id]['fcolor']
  1884. if type in ('line', 'rectangle'):
  1885. width = self.instruction[id]['width']
  1886. if type in ('line'):
  1887. point1, point2 = instr['where'][0], instr['where'][1]
  1888. point1 = self.CanvasPaperCoordinates(
  1889. rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False)[:2]
  1890. point2 = self.CanvasPaperCoordinates(
  1891. rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False)[:2]
  1892. coords = (point1, point2)
  1893. self.DrawGraphics(
  1894. drawid=id,
  1895. shape=type,
  1896. bb=oRect,
  1897. lineCoords=coords,
  1898. color=color,
  1899. fcolor=fcolor,
  1900. width=width)
  1901. else:
  1902. self.Draw(
  1903. pen=self.pen[type],
  1904. brush=self.brush[type],
  1905. pdc=self.pdcObj,
  1906. drawid=id,
  1907. pdctype='rectText',
  1908. bb=oRect)
  1909. # redraw tmp objects
  1910. if self.dragId != -1:
  1911. self.RedrawSelectBox(self.dragId)
  1912. # redraw preview
  1913. else: # preview mode
  1914. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1915. if globalvar.wxPythonPhoenix:
  1916. imageRect.Offset(-view[0], -view[1])
  1917. else:
  1918. imageRect.OffsetXY(-view[0], -view[1])
  1919. imageRect = self.ScaleRect(rect=imageRect, scale=zoomFactor)
  1920. self.DrawImage(imageRect)
  1921. def ZoomAll(self):
  1922. """Zoom to full extent"""
  1923. if not self.preview:
  1924. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1925. else:
  1926. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1927. zoomP = bounds.Inflate(round(bounds.width / 20), round(bounds.height / 20))
  1928. zoomFactor, view = self.ComputeZoom(zoomP)
  1929. self.Zoom(zoomFactor, view)
  1930. def Draw(self, pen, brush, pdc, drawid=None, pdctype='rect',
  1931. bb=Rect(0, 0, 0, 0), lineCoords=None):
  1932. """Draw object with given pen and brush.
  1933. :param pdc: PseudoDC
  1934. :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
  1935. :param bb: bounding box
  1936. :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
  1937. """
  1938. if drawid is None:
  1939. drawid = NewId()
  1940. bb = bb.Get()
  1941. pdc.BeginDrawing()
  1942. pdc.RemoveId(drawid)
  1943. pdc.SetId(drawid)
  1944. pdc.SetPen(pen)
  1945. pdc.SetBrush(brush)
  1946. if pdctype == 'bitmap':
  1947. if havePILImage:
  1948. file = self.instruction[drawid]['epsfile']
  1949. rotation = self.instruction[drawid]['rotate']
  1950. self.DrawBitmap(
  1951. pdc=pdc,
  1952. filePath=file,
  1953. rotation=rotation,
  1954. bbox=bb)
  1955. else: # draw only rectangle with label
  1956. pdctype = 'rectText'
  1957. if pdctype in ('rect', 'rectText'):
  1958. pdc.DrawRectangle(*bb)
  1959. if pdctype == 'rectText':
  1960. # dc created because of method GetTextExtent, which pseudoDC lacks
  1961. dc = ClientDC(self)
  1962. font = dc.GetFont()
  1963. size = 10
  1964. font.SetPointSize(size)
  1965. font.SetStyle(wx.ITALIC)
  1966. dc.SetFont(font)
  1967. pdc.SetFont(font)
  1968. text = '\n'.join(self.itemLabels[drawid])
  1969. w, h, lh = dc.GetFullMultiLineTextExtent(text)
  1970. textExtent = (w, h)
  1971. textRect = Rect(0, 0, *textExtent).CenterIn(Rect(*bb))
  1972. r = map(int, bb)
  1973. while not Rect(*r).ContainsRect(textRect) and size >= 8:
  1974. size -= 2
  1975. font.SetPointSize(size)
  1976. dc.SetFont(font)
  1977. pdc.SetFont(font)
  1978. textExtent = dc.GetTextExtent(text)
  1979. textRect = Rect(0, 0, *textExtent).CenterIn(Rect(*bb))
  1980. pdc.SetTextForeground(wx.Colour(100, 100, 100, 200))
  1981. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1982. pdc.DrawLabel(text=text, rect=textRect)
  1983. elif pdctype == 'point':
  1984. pdc.DrawCircle(x=bb[0] + bb[2] / 2,
  1985. y=bb[1] + bb[3] / 2,
  1986. radius=bb[2] / 2)
  1987. elif pdctype == "line":
  1988. pdc.DrawLinePoint(*lineCoords[0], *lineCoords[1])
  1989. pdc.SetIdBounds(drawid, Rect(*bb))
  1990. pdc.EndDrawing()
  1991. self.Refresh()
  1992. return drawid
  1993. def DrawGraphics(self, drawid, shape, color, bb,
  1994. width=None, fcolor=None, lineCoords=None):
  1995. """Draw point/line/rectangle with given color and width
  1996. :param drawid: id of drawn object
  1997. :param shape: drawn shape 'point'/'line'/'rectangle'
  1998. :param color: pen outline color ('RRR:GGG:BBB')
  1999. :param fcolor: brush fill color, if meaningful ('RRR:GGG:BBB')
  2000. :param width: pen width
  2001. :param bb: bounding box
  2002. :param lineCoords: line coordinates (for line only)
  2003. """
  2004. pdctype = {'point': 'point',
  2005. 'line': 'line',
  2006. 'rectangle': 'rect'}
  2007. if color == 'none':
  2008. pen = wx.TRANSPARENT_PEN
  2009. else:
  2010. if width is not None:
  2011. units = UnitConversion(self)
  2012. width = int(
  2013. units.convert(
  2014. value=width,
  2015. fromUnit='point',
  2016. toUnit='pixel') *
  2017. self.currScale)
  2018. else:
  2019. width = 2
  2020. pen = wx.Pen(colour=convertRGB(color), width=width)
  2021. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  2022. brush = wx.TRANSPARENT_BRUSH
  2023. if fcolor and fcolor != 'none':
  2024. brush = wx.Brush(colour=convertRGB(fcolor))
  2025. self.Draw(
  2026. pen=pen,
  2027. brush=brush,
  2028. pdc=self.pdcObj,
  2029. pdctype=pdctype[shape],
  2030. drawid=drawid,
  2031. bb=bb,
  2032. lineCoords=lineCoords)
  2033. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  2034. """Draw bitmap using PIL"""
  2035. pImg = PILImage.open(filePath)
  2036. if sys.platform == 'win32' and \
  2037. 'eps' in os.path.splitext(filePath)[1].lower():
  2038. import types
  2039. pImg.load = types.MethodType(loadPSForWindows, pImg)
  2040. if rotation:
  2041. # get rid of black background
  2042. pImg = pImg.convert("RGBA")
  2043. rot = pImg.rotate(rotation, expand=1)
  2044. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  2045. pImg = PILImage.composite(rot, new, rot)
  2046. pImg = pImg.resize(
  2047. (int(
  2048. bbox[2]), int(
  2049. bbox[3])), resample=PILImage.BICUBIC)
  2050. img = PilImageToWxImage(pImg)
  2051. bitmap = img.ConvertToBitmap()
  2052. mask = wx.Mask(bitmap, wx.WHITE)
  2053. bitmap.SetMask(mask)
  2054. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask=True)
  2055. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  2056. if textDict['rotate']:
  2057. rot = float(textDict['rotate'])
  2058. else:
  2059. rot = 0
  2060. if textDict['background'] != 'none':
  2061. background = textDict['background']
  2062. else:
  2063. background = None
  2064. pdc.RemoveId(drawId)
  2065. pdc.SetId(drawId)
  2066. pdc.BeginDrawing()
  2067. # border is not redrawn when zoom changes, why?
  2068. # if textDict['border'] != 'none' and not rot:
  2069. ## units = UnitConversion(self)
  2070. # borderWidth = units.convert(value = textDict['width'],
  2071. # fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  2072. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  2073. # pdc.DrawRectangle(*bounds)
  2074. if background:
  2075. pdc.SetTextBackground(convertRGB(background))
  2076. pdc.SetBackgroundMode(wx.SOLID)
  2077. else:
  2078. pdc.SetBackgroundMode(wx.TRANSPARENT)
  2079. fn = self.parent.makePSFont(textDict)
  2080. pdc.SetFont(fn)
  2081. pdc.SetTextForeground(convertRGB(textDict['color']))
  2082. if rot == 0:
  2083. pdc.DrawLabel(text=textDict['text'], rect=bounds)
  2084. else:
  2085. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  2086. pdc.SetIdBounds(drawId, Rect(*bounds))
  2087. self.Refresh()
  2088. pdc.EndDrawing()
  2089. def DrawImage(self, rect):
  2090. """Draw preview image to pseudoDC"""
  2091. self.pdcImage.ClearId(self.imageId)
  2092. self.pdcImage.SetId(self.imageId)
  2093. img = self.image
  2094. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  2095. img = img.Scale(rect.width, rect.height)
  2096. bitmap = img.ConvertToBitmap()
  2097. self.pdcImage.BeginDrawing()
  2098. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  2099. self.pdcImage.SetIdBounds(self.imageId, rect)
  2100. self.pdcImage.EndDrawing()
  2101. self.Refresh()
  2102. def DrawPaper(self, rect):
  2103. """Draw paper and margins"""
  2104. page = self.instruction[self.pageId]
  2105. scale = page['Width'] / rect.GetWidth()
  2106. w = (page['Width'] - page['Right'] - page['Left']) / scale
  2107. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  2108. x = page['Left'] / scale + rect.GetX()
  2109. y = page['Top'] / scale + rect.GetY()
  2110. self.pdcPaper.BeginDrawing()
  2111. self.pdcPaper.RemoveId(self.pageId)
  2112. self.pdcPaper.SetId(self.pageId)
  2113. self.pdcPaper.SetPen(self.pen['paper'])
  2114. self.pdcPaper.SetBrush(self.brush['paper'])
  2115. self.pdcPaper.DrawRectangleRect(rect)
  2116. self.pdcPaper.SetPen(self.pen["margins"])
  2117. self.pdcPaper.SetBrush(self.brush["margins"])
  2118. self.pdcPaper.DrawRectangle(int(x), int(y), int(w), int(h))
  2119. self.pdcPaper.SetIdBounds(self.pageId, rect)
  2120. self.pdcPaper.EndDrawing()
  2121. self.Refresh()
  2122. def ImageRect(self):
  2123. """Returns image centered in canvas, computes scale"""
  2124. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  2125. cW, cH = self.GetClientSize()
  2126. iW, iH = img.GetWidth(), img.GetHeight()
  2127. self.currScale = min(float(cW) / iW, float(cH) / iH)
  2128. iW = iW * self.currScale
  2129. iH = iH * self.currScale
  2130. x = cW / 2 - iW / 2
  2131. y = cH / 2 - iH / 2
  2132. imageRect = Rect(int(x), int(y), int(iW), int(iH))
  2133. return imageRect
  2134. def RedrawSelectBox(self, id):
  2135. """Redraws select box when selected object changes its size"""
  2136. if self.dragId == id:
  2137. rect = self.pdcObj.GetIdBounds(id)
  2138. if self.instruction[id].type != 'line':
  2139. rect = rect.Inflate(3, 3)
  2140. # draw select box around object
  2141. self.Draw(
  2142. pen=self.pen['select'],
  2143. brush=self.brush['select'],
  2144. pdc=self.pdcTmp,
  2145. drawid=self.idBoxTmp,
  2146. pdctype='rect',
  2147. bb=rect)
  2148. # draw small marks signalizing resizing
  2149. if self.instruction[id].type in ('map', 'rectangle'):
  2150. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  2151. rect = Rect(controlP[0], controlP[1], self.resizeBoxSize[0], self.resizeBoxSize[1])
  2152. self.Draw(
  2153. pen=self.pen['resize'],
  2154. brush=self.brush['resize'],
  2155. pdc=self.pdcTmp,
  2156. drawid=self.idResizeBoxTmp,
  2157. pdctype='rect',
  2158. bb=rect)
  2159. elif self.instruction[id].type == 'line':
  2160. p1Paper = self.instruction[id]['where'][0]
  2161. p2Paper = self.instruction[id]['where'][1]
  2162. p1Canvas = self.CanvasPaperCoordinates(
  2163. rect=Rect2DPS(p1Paper, (0, 0)), canvasToPaper=False)[:2]
  2164. p2Canvas = self.CanvasPaperCoordinates(
  2165. rect=Rect2DPS(p2Paper, (0, 0)), canvasToPaper=False)[:2]
  2166. rect = []
  2167. box = Rect(0, 0, self.resizeBoxSize[0], self.resizeBoxSize[1])
  2168. rect.append(box.CenterIn(Rect(p1Canvas[0], p1Canvas[1], 0, 0)))
  2169. rect.append(box.CenterIn(Rect(p2Canvas[0], p2Canvas[1], 0, 0)))
  2170. for i, point in enumerate((p1Canvas, p2Canvas)):
  2171. self.Draw(
  2172. pen=self.pen['resize'],
  2173. brush=self.brush['resize'],
  2174. pdc=self.pdcTmp,
  2175. drawid=self.idLinePointsTmp[i],
  2176. pdctype='rect',
  2177. bb=rect[i])
  2178. def UpdateMapLabel(self):
  2179. """Updates map frame label"""
  2180. vector = self.instruction.FindInstructionByType('vector')
  2181. if vector:
  2182. vectorId = vector.id
  2183. else:
  2184. vectorId = None
  2185. raster = self.instruction.FindInstructionByType('raster')
  2186. if raster:
  2187. rasterId = raster.id
  2188. else:
  2189. rasterId = None
  2190. rasterName = 'None'
  2191. if rasterId:
  2192. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  2193. mapId = self.instruction.FindInstructionByType('map').id
  2194. self.itemLabels[mapId] = []
  2195. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  2196. self.itemLabels[mapId].append("raster: " + rasterName)
  2197. if vectorId:
  2198. for map in self.instruction[vectorId]['list']:
  2199. self.itemLabels[mapId].append(
  2200. 'vector: ' + map[0].split('@')[0])
  2201. labels = self.instruction.FindInstructionByType('labels')
  2202. if labels:
  2203. labelFiles = self.instruction[labels.id]['labels']
  2204. if not labelFiles:
  2205. return
  2206. labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
  2207. self.itemLabels[mapId].append(
  2208. _("labels: ") + ', '.join(labelFiles))
  2209. def UpdateLabel(self, itype, id):
  2210. self.itemLabels[id] = []
  2211. self.itemLabels[id].append(self.itemLabelsDict[itype])
  2212. if itype == 'image':
  2213. file = os.path.basename(self.instruction[id]['epsfile'])
  2214. self.itemLabels[id].append(file)
  2215. def OnSize(self, event):
  2216. """Init image size to match window size
  2217. """
  2218. # not zoom all when notebook page is changed
  2219. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  2220. self.ZoomAll()
  2221. self.OnIdle(None)
  2222. event.Skip()
  2223. def OnIdle(self, event):
  2224. """Only re-render a image during idle time instead of
  2225. multiple times during resizing.
  2226. """
  2227. width, height = self.GetClientSize()
  2228. # Make new off screen bitmap: this bitmap will always have the
  2229. # current drawing in it, so it can be used to save the image
  2230. # to a file, or whatever.
  2231. width = max(width, 20)
  2232. height = max(height, 20)
  2233. self._buffer = EmptyBitmap(width, height)
  2234. # re-render image on idle
  2235. self.resize = True
  2236. def ScaleRect(self, rect, scale):
  2237. """Scale rectangle"""
  2238. return Rect(
  2239. int(rect.GetLeft() * scale),
  2240. int(rect.GetTop() * scale),
  2241. int(rect.GetSize()[0] * scale),
  2242. int(rect.GetSize()[1] * scale),
  2243. )