frame.py 96 KB

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