frame.py 96 KB

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