frame.py 96 KB

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