[GRASS-SVN] r45682 - in grass-addons/gui/wxpython/psmap: gui_modules xml

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Mar 16 16:55:05 EDT 2011


Author: annakrat
Date: 2011-03-16 13:55:05 -0700 (Wed, 16 Mar 2011)
New Revision: 45682

Modified:
   grass-addons/gui/wxpython/psmap/gui_modules/psmap.py
   grass-addons/gui/wxpython/psmap/gui_modules/psmap_dialogs.py
   grass-addons/gui/wxpython/psmap/xml/menudata_psmap.xml
Log:
instruction file reading, needs testing

Modified: grass-addons/gui/wxpython/psmap/gui_modules/psmap.py
===================================================================
--- grass-addons/gui/wxpython/psmap/gui_modules/psmap.py	2011-03-16 19:09:47 UTC (rev 45681)
+++ grass-addons/gui/wxpython/psmap/gui_modules/psmap.py	2011-03-16 20:55:05 UTC (rev 45682)
@@ -59,6 +59,9 @@
                             label = _('Generate instruction file')),
     'export'     : MetaIcon(img = iconSet['ps-export'],
                             label = _('Generate PostScript output')),
+    'loadFile'     : MetaIcon(img = iconSet['open'],
+                            label = _('Load file'), 
+                            desc = _('Load file with mapping instructions')),                           
     'pageSetup'  : MetaIcon(img = iconSet['settings'],
                             label = _('Page setup'),
                             desc = _('Specify paper size, margins and orientation')),
@@ -138,6 +141,7 @@
         self.preview = wx.NewId()
         self.instructionFile = wx.NewId()
         self.generatePS = wx.NewId()
+        self.loadFile = wx.NewId()
         self.pan = wx.NewId()
 
         icons = Icons['psMap']
@@ -172,6 +176,8 @@
                                       self.parent.OnInstructionFile),
                                      (self.generatePS, 'generatePS', icons['export'],
                                       self.parent.OnPSFile),
+                                     (self.loadFile, 'loadFile', icons['loadFile'],
+                                      self.parent.OnLoadFile),                                    
                                      (None, ),
                                      (self.quit, 'quit', icons['quit'],
                                       self.parent.OnCloseWindow))
@@ -295,11 +301,7 @@
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
         self.Bind(EVT_CMD_DONE, self.OnCmdDone)
         
-##        # load instructions
-##        self.readObjectId = []
-##        self.readInstruction = Instruction(parent = self, objectsToDraw = self.readObjectId)
-##        self.readInstruction.Read('/home/anna/Desktop/reading.txt')
-##        print '%%%%%%%%%%%%%%%%%%%\n',self.readInstruction
+        
     
     def _layout(self):
         """!Do layout
@@ -430,8 +432,38 @@
         if filename:    
             instrFile = open(filename, "w")
             instrFile.write(self.InstructionFile())
-            instrFile.close()            
-        
+            instrFile.close()   
+                     
+    def OnLoadFile(self, event):
+        """!Load file and read instructions"""
+        #find file
+        filename = ''
+        dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "", 
+                            defaultFile = '', wildcard = "All files (*.*)|*.*",
+                            style = wx.CHANGE_DIR|wx.OPEN)
+        if dlg.ShowModal() == wx.ID_OK:
+            filename = dlg.GetPath()
+        dlg.Destroy()
+        if not filename:
+            return
+        # load instructions
+        #filename = '/home/anna/Desktop/reading.txt'
+        readObjectId = []
+        readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
+        ok = readInstruction.Read(filename)
+        if not ok:
+            GMessage(_("Failed to read file {0}.").format(filename))
+        else:
+            self.instruction = self.canvas.instruction = readInstruction
+            self.objectId = self.canvas.objectId = readObjectId
+            self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
+            self.canvas.UpdateMapLabel()
+            self.canvas.dragId = -1
+            self.canvas.Clear()
+            #self.canvas.ZoomAll()
+            
+            self.DialogDataChanged(self.objectId)
+                        
     def OnPageSetup(self, event = None):
         """!Specify paper size, margins and orientation"""
         id = self.instruction.FindInstructionByType('page').id
@@ -504,7 +536,10 @@
             self.toolbar.ToggleTool(self.actionOld, True)
             self.toolbar.ToggleTool(self.toolbar.action['id'], False)
             self.toolbar.action['id'] = self.actionOld
-            self.canvas.SetCursor(self.cursorOld) 
+            try:
+                self.canvas.SetCursor(self.cursorOld) 
+            except AttributeError:
+                pass
    
             dlg = MapDialog(parent = self, id  = id, settings = self.instruction,
                             notebook = notebook)
@@ -910,9 +945,14 @@
         self.pdcPaper.SetBackground(bg)
         self.pdcPaper.Clear()
         self.pdcPaper.EndDrawing()
+        
+        self.pdcObj.RemoveAll()
+        self.pdcTmp.RemoveAll()
+        
+
+
         if not self.preview:
             self.SetPage()
-        
 
     
     def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
@@ -981,7 +1021,7 @@
             
         texts = self.instruction.FindInstructionByType('text', list = True)
         for text in texts:
-            e, n = PaperMapCoordinates(self, mapId = mapId, x = self.instruction[text.id]['where'][0],
+            e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[text.id]['where'][0],
                                                 y = self.instruction[text.id]['where'][1], paperToMap = True)
             self.instruction[text.id]['east'], self.instruction[text.id]['north'] = e, n
             
@@ -1480,6 +1520,7 @@
         
     def UpdateMapLabel(self):
         """!Updates map frame label"""
+
         mapId = self.instruction.FindInstructionByType('map').id
         vector = self.instruction.FindInstructionByType('vector')
         vectorId = vector.id if vector else None

Modified: grass-addons/gui/wxpython/psmap/gui_modules/psmap_dialogs.py
===================================================================
--- grass-addons/gui/wxpython/psmap/gui_modules/psmap_dialogs.py	2011-03-16 19:09:47 UTC (rev 45681)
+++ grass-addons/gui/wxpython/psmap/gui_modules/psmap_dialogs.py	2011-03-16 20:55:05 UTC (rev 45682)
@@ -32,9 +32,9 @@
                                  'gui_modules'))
 import globalvar
 import dbm_base
-from   utils      import CmdToTuple
+from   utils      import CmdToTuple, GetCmdString
 from   gselect    import Select
-from   gcmd       import RunCommand, GError, GMessage
+from   gcmd       import RunCommand, GError, GMessage, GWarning
 
 import wx
 import wx.lib.scrolledpanel as scrolled
@@ -49,11 +49,14 @@
 
 grass.set_raise_on_error(True)
 
-class UnitConversion():
+class UnitConversion:
     """! Class for converting units"""
-    def __init__(self, parent):
+    def __init__(self, parent = None):
         self.parent = parent
-        ppi = wx.PaintDC(self.parent).GetPPI()
+        if self.parent:
+            ppi = wx.PaintDC(self.parent).GetPPI()
+        else: 
+            ppi = (72, 72)
         self._unitsPage = { 'inch' : 1.0,
                             'point' : 72.0,
                             'centimeter' : 2.54,
@@ -243,7 +246,10 @@
             
     def AddInstruction(self, instruction):
         """!Add instruction"""
-        self.instruction.append(instruction)
+        if instruction.type == 'map':
+            self.instruction.insert(0, instruction)
+        else:
+            self.instruction.append(instruction)
         if instruction.type not in ('page', 'raster', 'vector', 'vProperties', 'initMap'):
             self.objectsToDraw.append(instruction.id)    
                 
@@ -261,101 +267,188 @@
         
     def Read(self, filename):
         """!Reads instruction file and creates instruction objects"""
-        print 'Starts to read...'
+        self.filename = filename
         # open file
         try:
             file = open(filename, 'r')
         except IOError:
             GError(message = _("Unable to open file\n{0}").format(filename))
             return
-        # read lines
+        # first read file to get information about region and scaletype
+        isRegionComment = False
+        for line in file:
+            if '# g.region' in line:
+                self.SetRegion(regionInstruction = line)
+                isRegionComment = True
+                break
+        if not isRegionComment:
+            self.SetRegion(regionInstruction = None)
+        # then run ps.map -b to get information for maploc
+        # compute scale and center 
+        map = self.FindInstructionByType('map')
+        region = grass.region()
+        map['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2
+        mapRect = GetMapBounds(self.filename)
+        map['rect'] = mapRect
+        proj = projInfo()
+        toM = 1.0
+        if proj['units']:
+            toM = float(proj['meters'])
+        units = UnitConversion(self.parent)
+        w = units.convert(value = mapRect.Get()[2], fromUnit = 'inch', toUnit = 'meter') / toM
+        map['scale'] = w / abs((region['w'] - region['e']))
+        
+        # read file again, now with information about map bounds
         isBuffer = False
         buffer = []
         instruction = None
-        isRegionComment = False
+        vectorMapNumber = 1
+        file.seek(0)
         for line in file:
+
             line = line.strip()
             if isBuffer:
                 buffer.append(line)
                 if line.startswith('end'):
                     isBuffer = False
-                    self.SendToRead(instruction, buffer)
+                    kwargs = {}
+                    if instruction == 'scalebar':
+                        kwargs['scale'] = map['scale']
+                    elif instruction == 'text':
+                        kwargs['mapInstruction'] = map
+                    elif instruction in ('vpoints', 'vlines', 'vareas'):
+                        kwargs['id'] = wx.NewId()
+                        kwargs['vectorMapNumber'] = vectorMapNumber
+                        vectorMapNumber += 1
+                    ok = self.SendToRead(instruction, buffer, **kwargs)
+                    if not ok: return False
                     buffer = []
-                continue
-
-            if line.startswith('#'):
-                if 'g.region' in line:
-                    instruction = 'gregion'
-                    self.SendToRead(instruction, line)
-                    isRegionComment = True
-                else:
-                    continue  
+                continue 
             
-            if line.startswith('paper'):
+            elif line.startswith('paper'):
                 instruction = 'paper'
                 isBuffer = True
                 buffer.append(line)
-                continue
             
-            if line.startswith('border'):
-                if line == 'border n':
-                    self.SendToRead('border', [line])
-                    continue
-                elif line == 'border y':
+            elif line.startswith('border'):
+                if line.split()[1].lower() in ('n', 'no', 'none'):
+                    ok = self.SendToRead('border', [line])
+                    if not ok: return False
+                elif line.split()[1].lower() in ('y', 'yes'):
                     instruction = 'border'
                     isBuffer = True
                     buffer.append(line)
-                    continue
             
-            if line.startswith('scale'):
-                self.SendToRead('scale', line)
-                continue
+            elif line.startswith('scale '):
+                ok = self.SendToRead('scale', line, isRegionComment = isRegionComment)
+                if not ok: return False
             
-            if line.startswith('maploc'):
-                self.SendToRead(instruction = 'maploc', text = line, filename = filename)
-                continue
+            elif line.startswith('maploc'):
+                ok = self.SendToRead(instruction = 'maploc', text = line)
+                if not ok: return False
                 
-            if line.startswith('raster'):
-                self.SendToRead(instruction = 'raster', text = line)
-                continue
+            elif line.startswith('raster'):
+                ok = self.SendToRead(instruction = 'raster', text = line)
+                if not ok: return False
             
+            elif line.startswith('mapinfo'):
+                instruction = 'mapinfo'
+                isBuffer = True
+                buffer.append(line)
+            
             if line.startswith('mapinfo'):
                 instruction = 'mapinfo'
                 isBuffer = True
                 buffer.append(line)
-                continue
+
+            if line.startswith('scalebar'):
+                instruction = 'scalebar'
+                isBuffer = True
+                buffer.append(line) 
             
+            if line.startswith('text'):
+                instruction = 'text'
+                isBuffer = True
+                buffer.append(line) 
+            
+            if line.startswith('colortable'):
+                if len(line.split()) == 2 and line.split()[1].lower() in ('n', 'no', 'none'):
+                    break
+                instruction = 'colortable'
+                isBuffer = True
+                buffer.append(line) 
         
-        # check at the end
-        if not isRegionComment:
-            map = self.FindInstructionByType('map')
-            if map:
-                map['scaleType'] = 2 # current region
-                if not map['rect']:
-                    map['rect'] = GetMapBounds(filename)
-                    if map['rect']:
-                        region = grass.region()
-                        units = UnitConversion(self.parent)
-                        realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
-                        scale = map['rect'].Get()[2]/realWidth
-                        map['scale'] = scale
+            if line.startswith('vlegend'):
+                instruction = 'vlegend'
+                isBuffer = True
+                buffer.append(line) 
+                
+            if line.startswith('vpoints'):
+                instruction = 'vpoints'
+                isBuffer = True
+                buffer.append(line) 
+                
+            if line.startswith('vlines'):
+                instruction = 'vlines'
+                isBuffer = True
+                buffer.append(line)
+                
+            if line.startswith('vareas'):
+                instruction = 'vareas'
+                isBuffer = True
+                buffer.append(line)                
+        # rasterLegend
+        rasterLegend = self.FindInstructionByType('rasterLegend')
+        raster = self.FindInstructionByType('raster')
+        page = self.FindInstructionByType('page')
+        if rasterLegend:
+            if rasterLegend['rasterDefault'] and raster['raster']:
+                rasterLegend['raster'] = raster['raster']
+                if not rasterLegend['discrete']:
+                    rasterType = getRasterType(map = rasterLegend['raster'])
+                    if rasterType == 'CELL':
+                        rasterLegend['discrete'] = 'y'
+                    else:
+                        rasterLegend['discrete'] = 'n'
+            
+            #estimate size
+            height = rasterLegend.EstimateHeight(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], 
+                                        fontsize = rasterLegend['fontsize'],
+                                        cols = rasterLegend['cols'], 
+                                        height = rasterLegend['height'])
+            width = rasterLegend.EstimateWidth(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], 
+                                        fontsize = rasterLegend['fontsize'],
+                                        cols = rasterLegend['cols'] , 
+                                        width = rasterLegend['width'],
+                                        paperInstr = page)
+            rasterLegend['rect'] = wx.Rect2D(x = float(rasterLegend['where'][0]), y = float(rasterLegend['where'][1]),
+                                                w = width, h = height)
+                
+        # vectors, vlegend        
+        vector = self.FindInstructionByType('vector')
+        vectorLegend = self.FindInstructionByType('vectorLegend')
+        vectorMaps = self.FindInstructionByType('vProperties', list = True)
+        if vector:
+            for vmap in vectorMaps:
+                for i, each in enumerate(vector['list']):
+                    if each[2] == vmap.id:
                         
-                    
-            else:
-                rect = GetMapBounds(filename)
-                if rect:
-                    initMap = InitMap(wx.NewId())
-                    self.instruction.AddInstruction(initMap)
-                    initMap['rect'] = rect
-                    region = grass.region()
-                    units = UnitConversion(self.parent)
-                    realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
-                    scale = rect.Get()[2]/realWidth 
-                    initMap['scale'] = scale 
-                
-        print 'end of reading'
+                        vector['list'][i][4] = vmap['label']
+                        vector['list'][i][3] = vmap['lpos']
+            if vectorLegend:
+                size = vectorLegend.EstimateSize(vectorInstr = vector, fontsize = vectorLegend['fontsize'],
+                                            width = vectorLegend['width'], cols = vectorLegend['cols'])                            
+                vectorLegend['rect'] = wx.Rect2D(x = float(vectorLegend['where'][0]), y = float(vectorLegend['where'][1]),
+                                                    w = size[0], h = size[1])
         
         
+        page = self.FindInstructionByType('page')
+        if not page:
+            page = PageSetup(wx.NewId())
+            self.AddInstruction(page)
+
+        return True
+        
     def SendToRead(self, instruction, text, **kwargs):
         #print 'send to read', instruction, text
         psmapInstrDict = dict(  paper = ['page'],
@@ -370,9 +463,7 @@
                                 vlines = ['vector', 'vProperties'],
                                 vareas = ['vector', 'vProperties'],
                                 colortable = ['rasterLegend'],
-                                vlegend = ['vectorLegend'],
-                                # not a real instruction, just help in commentary
-                                gregion = ['map']
+                                vlegend = ['vectorLegend']
                             )
         
         myInstrDict = dict( page = PageSetup,
@@ -392,23 +483,65 @@
         for i in myInstruction:
             instr = self.FindInstructionByType(i)
             if i in ('text', 'vProperties') or not instr:
+                
                 id = wx.NewId() #!vProperties expect subtype
-                newInstr = myInstrDict[i](id)
+                if i == 'vProperties':
+                    id = kwargs['id']
+                    newInstr = myInstrDict[i](id, subType = instruction[1:])
+                else:
+                    newInstr = myInstrDict[i](id)
                 ok = newInstr.Read(instruction, text, **kwargs)
                 if ok:
                     self.AddInstruction(newInstr)
                 else:
-                    GMessage(_("Failed to read"))
-                    
+                    return False
+
             else:
                 ok = instr.Read(instruction, text, **kwargs)
 
                 if not ok:
-                    GMessage(_("Failed to read"))
+                    return False
+        return True
+          
+    def SetRegion(self, regionInstruction):
+        """!Sets region from file comment or sets current region in case of no comment"""
+        map = MapFrame(wx.NewId())
+        self.AddInstruction(map)
+        if regionInstruction:
+            cmd = CmdToTuple(regionInstruction.strip('# ').split())
             
-              
-                            
-        
+            # define scaleType
+            if len(cmd[1]) == 1:
+                if 'rast' in cmd[1]:
+                    map['scaleType'] = 0
+                    map['mapType'] = 'raster'   
+                    map['map'] = cmd[1]['rast']  
+                elif 'vect' in cmd[1]:
+                    map['scaleType'] = 0
+                    map['mapType'] = 'vector' 
+                    map['map'] = cmd[1]['vect']  
+                elif 'region' in cmd[1]:
+                    map['scaleType'] = 1  
+                    map['region'] = cmd[1]['region']
+                    
+            else:
+                map['scaleType'] = 2  
+        else:
+            map['scaleType'] = 2
+            grass.del_temp_region()
+            region = grass.region()
+            grass.use_temp_region()    
+            cmd = ['g.region', region]
+        cmdString = GetCmdString(cmd).replace('g.region', '')
+        GMessage(_("Instruction file will be loaded with following region: {0}\n").format(cmdString))
+        try:
+            RunCommand(cmd[0], **cmd[1])
+            
+        except ScriptError, e:
+            GError(_("Region cannot be set\n{0}").format(e))
+            return False
+          
+
 class InstructionObject:
     """!Abtract class representing single instruction"""
     def __init__(self, id): 
@@ -417,7 +550,9 @@
         # default values
         self.defaultInstruction = dict()
         # current values
-        self.instruction = self.defaultInstruction    
+        self.instruction = self.defaultInstruction   
+        # converting units
+        self.unitConv = UnitConversion() 
     
     def __str__(self):
         """!Returns particular part of text instruction"""
@@ -475,13 +610,13 @@
         if self.instruction['scaleType'] == 0: #match map
             map = self.instruction['map']
             mapType = 'rast' if self.instruction['mapType'] == 'raster' else 'vect'
-            comment = "# set region: g.region {0}={1}\n".format(mapType, map)
+            comment = "# g.region {0}={1}\n".format(mapType, map)
         elif self.instruction['scaleType'] == 1:# saved region
             region = self.instruction['region']
-            comment = "# set region: g.region region={0}\n".format(region)                
-        elif self.instruction['scaleType'] == 3: #fixed scale
+            comment = "# g.region region={0}\n".format(region)                
+        elif self.instruction['scaleType'] in (2, 3): #current region, fixed scale
             region = grass.region()
-            comment = "# set region: g.region n={n} s={s} e={e} w={w}\n".format(**region)
+            comment = "# g.region n={n} s={s} e={e} w={w} rows={rows} cols={cols}\n".format(**region)
         instr += comment
         instr += '\n'
         # maploc
@@ -511,40 +646,19 @@
      
     def Read(self, instruction, text, **kwargs):
         """!Read instruction and save information"""
-        
+        if 'isRegionComment' in kwargs:
+            isRegionComment = kwargs['isRegionComment']
         instr = {}
-        if instruction == 'gregion':
-            start = text.find('g.region')
-            cmd = text[start:].split()
-            if len(cmd) == 2:
-                if cmd[1].split('=')[0] == 'rast':
-                    instr['scaleType'] = 0
-                    instr['mapType'] = 'raster'   
-                    instr['map'] = cmd[1].split('=')[1]  
-                elif cmd[1].split('=')[0] == 'vect':
-                    instr['scaleType'] = 0
-                    instr['mapType'] = 'vector' 
-                    instr['map'] = cmd[1].split('=')[1]  
-                elif cmd[1].split('=')[0] == 'region':
-                    instr['scaleType'] = 1  
-                    instr['region'] = cmd[1].split('=')[1]
-                    
-            elif len(text[start:].split()[1:]) == 4:
-                instr['scaleType'] = 3  
-                region = grass.parse_key_val(text[start:].split(' ',1)[1], val_type = float, vsep = ' ')
-                instr['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2
-
-            cmd = CmdToTuple(cmd)
-            RunCommand(cmd[0], **cmd[1])
-
             
-        elif instruction == 'border':
+        if instruction == 'border':
             for line in text:
+                if line.startswith('end'):
+                    break
                 try:
-                    if line == 'border n':
+                    if line.split()[1].lower() in ('n', 'no', 'none'):
                         instr['border'] = 'n'
                         break
-                    elif line == 'border y':
+                    elif line.split()[1].lower() in ('y', 'yes'):
                         instr['border'] = 'y'
                     elif line.startswith('width'):
                         instr['width'] = line.split()[1]
@@ -556,17 +670,31 @@
                     
         elif instruction == 'scale':
             try:
-                scale = text.strip('scale ').split(':')[1]
-                instr['scale'] = 1/float(scale)
+                scaleText = text.strip('scale ').split(':')[1]
+                # when scale instruction given and region comment also, then scaletype is fixed scale
+                instr['scaleType'] = 2 if not isRegionComment else 3
+                scale = 1/float(scaleText)
+                if abs(scale - self.instruction['scale']) > (0.01 * scale):
+                    GWarning(_("Scale has changed, old value: {0}\nnew value: {1}").format(scale, self.instruction['scale']))
             except (ValueError, IndexError):
                 GError(_("Failed to read instruction {0}.\nUse 1:25000 notation.").format(instruction))
                 return False
         
         elif instruction == 'maploc':
-            #TODO: run psmap -b always?
-            instr['rect'] = GetMapBounds(kwargs['filename'])
-            
-
+            maploc = text.strip('maploc ').split()
+            if len(maploc) >= 2:
+                if  abs(self.instruction['rect'].Get()[0] - float(maploc[0])) > 0.5 or \
+                    abs(self.instruction['rect'].Get()[1] - float(maploc[1])) > 0.5:
+                    GWarning(_("Map frame position changed, old value: {0} {1}\nnew value: {2} {3}").format(
+                                             maploc[0], maploc[1], *self.instruction['rect'].Get()[0:2]))
+                    
+                #instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3])
+            if len(maploc) == 4:
+                if  abs(self.instruction['rect'].Get()[2] - float(maploc[2])) > 0.5 or \
+                    abs(self.instruction['rect'].Get()[3] - float(maploc[3])) > 0.5:
+                    GWarning(_("Map frame size changed, old value: {0} {1}\nnew value: {2} {3}").format(
+                                            maploc[2], maploc[3], *self.instruction['rect'].Get()[2:]))
+                #instr['rect'] = wx.Rect2D(*map(float, maploc))
         self.instruction.update(instr)   
         return True 
     
@@ -664,7 +792,7 @@
         instr = {}
         try:
             for line in text:
-                sub = line.split(' ',1)
+                sub = line.split(None,1)
                 if sub[0] == 'font':
                     instr['font'] = sub[1]
                 elif sub[0] == 'fontsize':
@@ -676,13 +804,22 @@
                 elif sub[0] == 'border':
                     instr['border'] = sub[1]
                 elif sub[0] == 'where':
-                    instr['where'] = tuple(sub[2].split())
+                    instr['where'] = tuple(sub[1].split())
         except (ValueError, IndexError):
             GError(_("Failed to read instruction {0}").format(instruction))
-        
+            return False
         self.instruction.update(instr)
+        self.instruction['rect'] = self.EstimateRect(mapinfoDict = self.instruction)
         return True
     
+    def EstimateRect(self, mapinfoDict):
+        """!Estimate size to draw mapinfo"""
+        w = mapinfoDict['fontsize'] * 20 # any better estimation? 
+        h = mapinfoDict['fontsize'] * 7
+        width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch')
+        height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch')
+        return wx.Rect2D(x = float(mapinfoDict['where'][0]), y = float(mapinfoDict['where'][1]), w = width, h = height)
+        
 class Text(InstructionObject):
     """!Class representing text instruction"""
     def __init__(self, id):
@@ -717,14 +854,75 @@
         instr += "end"
         return instr
     
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        map = kwargs['mapInstruction']
+        instr = {}
+        for line in text:
+            try:
+                sub = line.split(None, 1)[0]
+                if sub == 'text':
+                    e, n = line.split(None, 3)[1:3]
+                    if '%' in e and '%' in n:
+                        instr['XY'] = True
+                        instr['east'], instr['north'] = self.PercentToReal(e, n)
+                    else:
+                        instr['XY'] = False
+                        instr['east'], instr['north'] = float(e), float(n)
+                        
+                    instr['text'] = line.split(None, 3)[3]
+                
+                elif sub == 'font':
+                    instr['font'] = line.split(None, 1)[1]
+                elif sub == 'fontsize':
+                    instr['fontsize'] = float(line.split(None, 1)[1])
+                elif sub == 'color':
+                    instr['color'] = line.split(None, 1)[1]
+                elif sub == 'width':
+                    instr['width'] = line.split(None, 1)[1]
+                elif sub == 'hcolor':
+                    instr['hcolor'] = line.split(None, 1)[1]
+                elif sub == 'hwidth':
+                    instr['hwidth'] = line.split(None, 1)[1]
+                elif sub == 'background':
+                    instr['background'] = line.split(None, 1)[1]
+                elif sub == 'border':
+                    instr['border'] = line.split(None, 1)[1]
+                elif sub == 'ref':
+                    instr['ref'] = line.split(None, 1)[1]
+                elif sub == 'rotate':
+                    instr['rotate'] = float(line.split(None, 1)[1])
+                elif sub == 'xoffset':
+                    instr['xoffset'] = float(line.split(None, 1)[1])
+                elif sub == 'yoffset':
+                    instr['yoffset'] = float(line.split(None, 1)[1])
+                elif sub == 'opaque':
+                    if line.split(None, 1)[1].lower() in ('n', 'none'):
+                        instr['background'] = 'none'
+         
+            except(IndexError, ValueError):
+                GError(_("Failed to read instruction {0}").format(instruction))
+                return False
+        instr['where'] = PaperMapCoordinates(map = map, x = instr['east'], y = instr['north'], paperToMap = False)       
+        self.instruction.update(instr)
+
+        return True 
     
+    def PercentToReal(self, e, n):
+        """!Converts text coordinates from percent of region to map coordinates"""
+        e, n = float(e.strip('%')), float(n.strip('%'))
+        region = grass.region()
+        N = region['s'] + (region['n'] - region['s']) / 100 * n
+        E = region['w'] + (region['e'] - region['w']) / 100 * e
+        return E, N
+    
 class Scalebar(InstructionObject):
     """!Class representing scalebar instruction"""
     def __init__(self, id):
         InstructionObject.__init__(self, id = id)
         self.type = 'scalebar'
         # default values
-        self.defaultInstruction = dict( unit = 'inch', where = (0,0),
+        self.defaultInstruction = dict( unit = 'inch', where = (1,1),
                                             unitsLength = 'auto', unitsHeight = 'inch',
                                             length = None, height = 0.1, rect = None,
                                             fontsize = 10, background = 'y',
@@ -741,7 +939,64 @@
         instr += "    fontsize {fontsize}\n    background {background}\n".format(**self.instruction)
         instr += "end"
         return instr
-        
+    
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        scale = kwargs['scale']
+        instr = {}
+        for line in text:
+            try:
+                if line.startswith('scalebar'):
+                    if 'scalebar s' in line:
+                        instr['scalebar'] = 's'
+                    else:
+                        instr['scalebar'] = 'f'
+                elif line.startswith('where'):
+                    instr['where'] = line.split()[1:3]
+                elif line.startswith('length'):
+                    instr['length'] = float(line.split()[1])
+                elif line.startswith('units'):
+                    if line.split()[1] in ['auto', 'meters', 'kilometers', 'feet', 'miles', 'nautmiles']:
+                        instr['unitsLength'] = line.split()[1]
+                elif line.startswith('height'):
+                    instr['height'] = float(line.split()[1])
+                elif line.startswith('fontsize'):
+                    instr['fontsize'] = float(line.split()[1])
+                elif line.startswith('numbers'):
+                    instr['numbers'] = int(line.split()[1])
+                elif line.startswith('segment'):
+                    instr['segment'] = int(line.split()[1])
+                elif line.startswith('background'):
+                    if line.split()[1].strip().lower() in ('y','yes'):
+                        instr['background'] = 'y'
+                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                        instr['background'] = 'n'
+            except(IndexError, ValueError):
+                GError(_("Failed to read instruction {0}").format(instruction))
+                return False
+                
+        self.instruction.update(instr)
+        w, h = self.EstimateSize(scalebarDict = self.instruction, scale = scale)
+        x = float(self.instruction['where'][0]) - w / 2 
+        y = float(self.instruction['where'][1]) - h / 2
+        self.instruction['rect'] = wx.Rect2D(x, y, w, h)
+        return True 
+    
+    def EstimateSize(self, scalebarDict, scale):
+        """!Estimate size to draw scalebar"""
+        units = projInfo()['units']
+        if not units or units not in self.unitConv.getAllUnits():
+            units = 'meters'
+        if scalebarDict['unitsLength'] != 'auto':
+            length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = scalebarDict['unitsLength'], toUnit = 'inch')
+        else:
+            length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = units, toUnit = 'inch')
+            
+        length *= scale
+        length *= 1.1 #for numbers on the edge
+        height = scalebarDict['height'] + 2 * self.unitConv.convert(value = scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch')     
+        return (length, height)
+    
 class RasterLegend(InstructionObject):
     """!Class representing colortable instruction"""
     def __init__(self, id):
@@ -750,11 +1005,11 @@
         # default values
         self.defaultInstruction = dict(rLegend = False, unit = 'inch', rasterDefault = True, raster = None,
                                                 discrete = None, type = None,
-                                                where = (0, 0), defaultSize = True,
-                                                width = 0, height = 0, cols = 1, font = "Serif", fontsize = 10,
+                                                where = (0, 0),
+                                                width = None, height = None, cols = 1, font = "Helvetica", fontsize = 10,
                                                 #color = '0:0:0', tickbar = False, range = False, min = 0, max = 0,
-                                                color = 'black', tickbar = False, range = False, min = 0, max = 0,
-                                                nodata = False)
+                                                color = 'black', tickbar = 'n', range = False, min = 0, max = 0,
+                                                nodata = 'n')
         # current values
         self.instruction = dict(self.defaultInstruction)
         
@@ -762,11 +1017,11 @@
         instr = "colortable y\n"
         instr += "    raster {raster}\n".format(**self.instruction)
         instr += "    where {where[0]} {where[1]}\n".format(**self.instruction)
-        if not self.instruction['defaultSize']:
+        if self.instruction['width']:
             instr += "    width {width}\n".format(**self.instruction)
         instr += "    discrete {discrete}\n".format(**self.instruction)
         if self.instruction['discrete'] == 'n':
-            if not self.instruction['defaultSize']:
+            if self.instruction['height']:
                 instr += "    height {height}\n".format(**self.instruction)
             instr += "    tickbar {tickbar}\n".format(**self.instruction)
             if self.instruction['range']:
@@ -778,8 +1033,122 @@
                                 .format(**self.instruction)
         instr += "end"
         return instr    
-  
+    
+    
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        instr = {}
+        instr['rLegend'] = True
+        for line in text:
+            try:
+                if line.startswith('where'):
+                    instr['where'] = line.split()[1:3]
+                elif line.startswith('font '):
+                    instr['font'] = line.split()[1]
+                elif line.startswith('fontsize'):
+                    instr['fontsize'] = float(line.split()[1])
+                elif line.startswith('color '):
+                    instr['color'] = line.split()[1]
+                elif line.startswith('raster'):
+                    instr['raster'] = line.split()[1]
+                elif line.startswith('width'):
+                    instr['width'] = float(line.split()[1])
+                elif line.startswith('height'):
+                    instr['height'] = float(line.split()[1])
+                elif line.startswith('cols'):
+                    instr['cols'] = int(line.split()[1])                    
+                elif line.startswith('range'):
+                    instr['range'] = True
+                    instr['min'] = float(line.split()[1])
+                    instr['max'] = float(line.split()[2])
+                elif line.startswith('nodata'):
+                    if line.split()[1].strip().lower() in ('y','yes'):
+                        instr['nodata'] = 'y'
+                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                        instr['nodata'] = 'n'
+                elif line.startswith('tickbar'):
+                    if line.split()[1].strip().lower() in ('y','yes'):
+                        instr['tickbar'] = 'y'
+                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                        instr['tickbar'] = 'n'
+                elif line.startswith('discrete'):
+                    if line.split()[1].strip().lower() in ('y','yes'):
+                        instr['discrete'] = 'y'
+                    elif line.split()[1].strip().lower() in ('n','no', 'none'):
+                        instr['discrete'] = 'n'            
 
+            except(IndexError, ValueError):
+                GError(_("Failed to read instruction {0}").format(instruction))
+                return False
+            
+        if 'raster' in instr:
+            instr['rasterDefault'] = False
+            if 'discrete' not in instr:
+                rasterType = getRasterType(map = instr['raster'])
+                instr['type'] = rasterType
+                if rasterType == 'CELL':
+                    instr['discrete'] = 'y'
+                else:
+                    instr['discrete'] = 'n'
+            
+        else:
+            instr['rasterDefault'] = True
+        self.instruction.update(instr)
+        # add 'rect' in the end
+            
+        return True 
+    
+    def EstimateHeight(self, raster, discrete, fontsize, cols = None,  height = None):
+        """!Estimate height to draw raster legend"""
+        if discrete == 'n':
+            if height:
+                height = height
+            else:
+                height = self.unitConv.convert(value = fontsize * 10,
+                                                    fromUnit = 'point', toUnit = 'inch')
+                                                    
+        if discrete == 'y':
+            cols = cols if cols else 1 
+            try:
+                cat = grass.read_command('r.category', map = raster,
+                                        fs = ':').strip().split('\n')
+                rows = ceil( float(len(cat)) / cols )
+            except grass.ScriptError:
+                range = grass.read_command('r.info', flags = 'r', map = raster).strip().split('\n')
+                minim, maxim = range[0].split('=')[1], range[1].split('=')[1]
+                rows = ceil( float(maxim) / cols )
+                            
+                
+            height = self.unitConv.convert(value =  1.5 * rows * fontsize, fromUnit = 'point', toUnit = 'inch')
+            
+        return height
+        
+    def EstimateWidth(self, raster, discrete, fontsize, cols = None, width = None, paperInstr = None):
+        """!Estimate size to draw raster legend"""
+        
+        if discrete == 'n':
+            range = grass.read_command('r.info', flags = 'r', map = raster).strip().split('\n')
+            minim, maxim = range[0].split('=')[1], range[1].split('=')[1]
+            if width:
+                width = width
+            else:
+                width = self.unitConv.convert(value = fontsize * 2,
+                                                    fromUnit = 'point', toUnit = 'inch')
+            text = len(max(minim, maxim, key = len))
+            textPart = self.unitConv.convert(value = text * fontsize / 2,
+                                                    fromUnit = 'point', toUnit = 'inch')
+            width += textPart
+                                                    
+        elif discrete == 'y':
+            cols = cols if cols else 1    
+            if width:
+                width = width
+            else:
+                paperWidth = paperInstr['Width'] - paperInstr['Right'] - paperInstr['Left']
+                width = (paperWidth / cols) * (cols - 1) + 1
+                
+        return width    
+             
 class VectorLegend(InstructionObject):
     """!Class representing colortable instruction"""
     def __init__(self, id):
@@ -787,7 +1156,8 @@
         self.type = 'vectorLegend'
         # default values
         self.defaultInstruction = dict(vLegend = False, unit = 'inch', where = (0, 0),
-                                                defaultSize = True, width = 0.4, cols = 1, span = None, font = "Serif", fontsize = 10,
+                                                defaultSize = True, width = 0.4, cols = 1, span = None,
+                                                font = "Helvetica", fontsize = 10,
                                                 border = 'none')
         # current values
         self.instruction = dict(self.defaultInstruction)
@@ -802,7 +1172,51 @@
         instr += "    border {border}\n".format(**self.instruction)  
         instr += "end"  
         return instr
-          
+
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        instr = {}
+        instr['vLegend'] = True
+        for line in text:
+            try:
+                if line.startswith('where'):
+                    instr['where'] = line.split()[1:3]
+                elif line.startswith('font '):
+                    instr['font'] = line.split()[1]
+                elif line.startswith('fontsize'):
+                    instr['fontsize'] = float(line.split()[1])
+                elif line.startswith('width'):
+                    instr['width'] = float(line.split()[1])
+                elif line.startswith('cols'):
+                    instr['cols'] = int(line.split()[1]) 
+                elif line.startswith('span'):
+                    instr['span'] = float(line.split()[1])
+                elif line.startswith('border'):
+                    instr['border'] = line.split()[1]
+                    
+            except(IndexError, ValueError):
+                GError(_("Failed to read instruction {0}").format(instruction))
+                return False
+            
+        self.instruction.update(instr)
+            
+        return True 
+    
+    def EstimateSize(self, vectorInstr, fontsize, width = None, cols = None):
+        """!Estimate size to draw vector legend"""
+        width = width if width else fontsize/24.0
+        cols = cols if cols else 1
+        vectors = vectorInstr['list']
+        labels = [vector[4] for vector in vectors if vector[3] != 0]
+        extent = (len(max(labels, key = len)) * fontsize / 2, fontsize)
+        wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'point', toUnit = 'inch')
+        hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'point', toUnit = 'inch')
+        w = (width + wExtent) * cols
+        h = len(labels) * hExtent / cols
+        h *= 1.1
+        return (w, h)
+            
+   
 class Raster(InstructionObject):
     """!Class representing raster instruction"""
     def __init__(self, id):
@@ -843,12 +1257,47 @@
         InstructionObject.__init__(self, id = id)
         self.type = 'vector'
         # default values
-        self.defaultInstruction = dict(list = None)
+        self.defaultInstruction = dict(list = None)# [vmap, type, id, lpos, label] 
         # current values
         self.instruction = dict(self.defaultInstruction)
     def __str__(self):
         return ''
+    
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        instr = {}
         
+        for line in text:
+            if line.startswith('vpoints') or line.startswith('vlines') or line.startswith('vareas'):
+                # subtype
+                if line.startswith('vpoints'):
+                    subType = 'points'
+                elif line.startswith('vlines'):
+                    subType = 'lines'
+                elif line.startswith('vareas'):
+                    subType = 'areas'
+                # name of vector map
+                vmap = line.split()[1]
+                try:
+                    info = grass.find_file(vmap, element = 'vector')
+                except grass.ScriptError, e:
+                    GError(message = e.value)
+                    return False
+                vmap = info['fullname']
+                # id
+                id = kwargs['id']
+                # lpos
+                lpos = kwargs['vectorMapNumber']
+                #label
+                label = '('.join(vmap.split('@')) + ')'
+                break
+        instr = [vmap, subType, id, lpos, label] 
+        if not self.instruction['list']:
+            self.instruction['list'] = []
+        self.instruction['list'].append(instr)
+        
+        return True    
+    
 class VProperties(InstructionObject):
     """!Class represents instructions vareas, vlines, vpoints"""
     def __init__(self, id, subType):
@@ -857,17 +1306,20 @@
         self.subType = subType
         # default values
         if self.subType == 'points':
-            dd = dict(subType  = 'points', name = None, type = 'point or centroid', connection = False, layer = '1', masked = 'n', color = '0:0:0', width = 1,
+            dd = dict(subType  = 'points', name = None, type = 'point or centroid', connection = False, layer = '1',
+                        masked = 'n', color = '0:0:0', width = 1,
                         fcolor = '255:0:0', rgbcolumn = None, symbol = os.path.join('basic', 'x'), eps = None,
                         size = 5, sizecolumn = None, scale = None,
                         rotation = False, rotate = 0, rotatecolumn = None, label = None, lpos = None)
         elif self.subType == 'lines':
-            dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1', masked = 'n', color = '0:0:0', hwidth = 1,
+            dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1',
+                        masked = 'n', color = '0:0:0', hwidth = 1,
                         hcolor = 'none', rgbcolumn = None,
                         width = 1, cwidth = None,
                         style = 'solid', linecap = 'butt', label = None, lpos = None)
         else: # areas
-            dd = dict(subType = 'areas', name = None, type = 'point or centroid', connection = False, layer = '1', masked = 'n', color = '0:0:0', width = 1,
+            dd = dict(subType = 'areas', name = None, connection = False, layer = '1',    
+                        masked = 'n', color = '0:0:0', width = 1,
                         fcolor = 'none', rgbcolumn = None,
                         pat = None, pwidth = 1, scale = 1, label = None, lpos = None)
         self.defaultInstruction = dd
@@ -938,6 +1390,119 @@
         vInstruction += "end"
         return vInstruction
     
+    def Read(self, instruction, text, **kwargs):
+        """!Read instruction and save information"""
+        instr = {}
+        try:
+            info = grass.find_file(name = text[0].split()[1], element = 'vector')
+        except grass.ScriptError, e:
+            GError(message = e.value)
+            return False
+        instr['name'] = info['fullname']
+        #connection
+        instr['connection'] = True
+        try:
+            self.mapDBInfo = dbm_base.VectorDBInfo(instr['name'])
+        except grass.ScriptError:
+            instr['connection'] = False
+            
+        # points
+        if text[0].startswith('vpoints'):
+            for line in text[1:]:
+                if line.startswith('type'):
+                    tp = []
+                    if line.find('point') != -1:
+                        tp.append('point')
+                    if line.find('centroid') != -1:
+                        tp.append('centroid')
+                    instr['type'] = ' or '.join(tp)
+                elif line.startswith('fcolor'):
+                    instr['fcolor'] = line.split()[1]
+                elif line.startswith('rgbcolumn'):
+                    instr['rgbcolumn'] = line.split()[1]
+                elif line.startswith('symbol'):
+                    instr['symbol'] = line.split()[1]
+                elif line.startswith('eps'):
+                    instr['eps'] = line.split()[1]
+                elif line.startswith('size '):
+                    instr['size'] = line.split()[1]
+                elif line.startswith('sizecolumn'):
+                    instr['size'] = None
+                    instr['sizecolumn'] = line.split()[1]
+                elif line.startswith('scale '):
+                    instr['scale'] = float(line.split()[1])
+                elif line.startswith('rotate '):
+                    instr['rotation'] = True
+                    instr['rotate'] = line.split()[1]
+                elif line.startswith('rotatecolumn'):
+                    instr['rotatecolumn'] = line.split()[1]
+                    instr['rotation'] = True
+                    instr['rotate'] = None
+                    
+        # lines            
+        elif text[0].startswith('vlines'):
+            for line in text[1:]:
+                if line.startswith('type'):
+                    tp = []
+                    if line.find('line') != -1:
+                        tp.append('line')
+                    if line.find('boundary') != -1:
+                        tp.append('boundary')
+                    instr['type'] = ' or '.join(tp)
+                elif line.startswith('hwidth'):
+                    instr['hwidth'] = float(line.split()[1])
+                elif line.startswith('hcolor'):
+                    instr['hcolor'] = line.split()[1]
+                elif line.startswith('rgbcolumn'):
+                    instr['rgbcolumn'] = line.split()[1]                    
+                elif line.startswith('cwidth'):
+                    instr['cwidth'] = float(line.split()[1])
+                    instr['width'] = None
+                elif line.startswith('style'):
+                    instr['style'] = line.split()[1]       
+                elif line.startswith('linecap'):
+                    instr['linecap'] = line.split()[1]
+         
+        elif text[0].startswith('vareas'):
+            for line in text[1:]:
+                if line.startswith('fcolor'):
+                    instr['fcolor'] = line.split()[1]    
+                elif line.startswith('pat'):
+                    instr['pat'] = line.split()[1]
+                elif line.startswith('pwidth'):
+                    instr['pwidth'] = float(line.split()[1])
+                elif line.startswith('scale'):
+                    instr['scale'] = float(line.split()[1])
+            
+            
+        # same properties for all    
+        for line in text[1:]:
+            if line.startswith('lpos'):
+                instr['lpos'] = int(line.split()[1])
+            elif line.startswith('label'):
+                instr['label'] = line.split()[1]
+            elif line.startswith('layer'):
+                instr['layer'] = int(line.split()[1])
+            elif line.startswith('masked'):
+                if line.split()[1].lower() in ('y', 'yes'):
+                    instr['masked'] = 'y'
+                else:
+                    instr['masked'] = 'n'
+            elif line.startswith('color'):
+                instr['color'] = line.split()[1]
+            elif line.startswith('rgbcolumn'):
+                instr['rgbcolumn'] = line.split()[1] 
+            elif line.startswith('width'):
+                instr['width'] = float(line.split()[1])
+                
+        if 'label' not in instr:
+            instr['label'] = '('.join(instr['name'].split('@')) + ')'
+        if 'lpos' not in instr:
+            instr['lpos'] = kwargs['vectorMapNumber']
+        self.instruction.update(instr)
+        
+        return True
+        
 class PsmapDialog(wx.Dialog):
     def __init__(self, parent, id,  title, settings, apply = True):
         wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, 
@@ -994,8 +1559,11 @@
                         'Helvetica-Oblique', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Courier',\
                         'Courier-Oblique', 'Courier-Bold', 'Courier-BoldOblique'] 
         parent.font['fontCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = fontChoices)
-        parent.font['fontCtrl'].SetStringSelection(dialogDict['font'])
-        parent.font['fontSizeCtrl']= wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10)
+        if dialogDict['font'] in fontChoices:
+            parent.font['fontCtrl'].SetStringSelection(dialogDict['font'])
+        else:
+            parent.font['fontCtrl'].SetStringSelection('Helvetica')
+        parent.font['fontSizeCtrl'] = wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10)
         parent.font['fontSizeCtrl'].SetValue(dialogDict['fontsize'])
          
         if color:
@@ -1880,7 +2448,6 @@
             self.listbox.InsertItems([record], 0)
             
             vector = VProperties(id, type)
-            #self.instruction.AddInstruction(vector)
             self.tmpDialogDict[id] = vector.GetInstruction()
             self.tmpDialogDict[id]['name'] = vmap
 
@@ -2776,11 +3343,12 @@
         currPage = self.instruction[self.pageId].GetInstruction()
         #raster legend
         if self.id[0] is not None:
-            self.rLegendDict = self.instruction[self.id[0]].GetInstruction()
+            self.rasterLegend = self.instruction[self.id[0]]
+            self.rLegendDict = self.rasterLegend.GetInstruction()
         else:
             self.id[0] = wx.NewId()
-            rasterLegend = RasterLegend(self.id[0])
-            self.rLegendDict = rasterLegend.GetInstruction()
+            self.rasterLegend = RasterLegend(self.id[0])
+            self.rLegendDict = self.rasterLegend.GetInstruction()
             self.rLegendDict['where'] = currPage['Left'], currPage['Top']
             
             
@@ -2801,7 +3369,7 @@
         self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
         self.panelRaster = self._rasterLegend(self.notebook)
         self.panelVector = self._vectorLegend(self.notebook)  
-        self.OnDefaultSize(None)
+##        self.OnDefaultSize(None)
         self.OnRaster(None)
         self.OnRange(None)
         self.OnIsLegend(None)
@@ -2835,7 +3403,7 @@
         self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])#
         self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])#
 
-        rasterType = self.getRasterType(map = self.currRaster)
+        rasterType = getRasterType(map = self.currRaster)
 
         self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY, label = _("{0}: type {1}").format(self.currRaster, str(rasterType)))
         self.rasterSelect = Select( panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
@@ -2913,7 +3481,7 @@
         self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isRLegend)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.discrete)
         self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.continuous)
-        self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
+##        self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize)
         self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range)
         self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster)
         
@@ -3044,23 +3612,29 @@
         
         #size
         width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:"))
-        w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
+        if legendDict['width']:
+            w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit'])
+        else: 
+            w = ''
         panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY"))
         
         if legendType == 'raster':
-            panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
-            panel.defaultSize.SetValue(legendDict['defaultSize'])
+##            panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size"))
+##            panel.defaultSize.SetValue(legendDict['defaultSize'])
             
             panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:"))
-            h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
+            if legendDict['height']:
+                h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit'])
+            else:
+                h = ''
             panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY"))
             
             self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
-            self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(width, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.widthCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
-            self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+##            self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+            self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
             sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
             
         if legendType == 'vector':
@@ -3137,7 +3711,6 @@
                 for i,widget in enumerate(children):
                         widget.Enable()
                 self.OnRaster(None)
-                self.OnDefaultSize(None)
                 self.OnRange(None)
                 self.OnDiscrete(None)
             else:
@@ -3159,11 +3732,11 @@
     def OnRaster(self, event):
         if self.rasterDefault.GetValue():#default
             self.rasterSelect.Disable()
-            type = self.getRasterType(self.currRaster)
+            type = getRasterType(self.currRaster)
         else:#select raster
             self.rasterSelect.Enable()
             map = self.rasterSelect.GetValue()
-            type = self.getRasterType(map)
+            type = getRasterType(map)
   
         if type == 'CELL':
             self.discrete.SetValue(True)
@@ -3193,7 +3766,10 @@
             self.ticks.Disable()
         else:
             self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:"))
-            h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
+            if self.rLegendDict['height']:
+                h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit'])
+            else:
+                h = ''
             self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY,
                                                     value = str(h), validator = TCValidator("DIGIT_ONLY"))
             self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize)
@@ -3206,18 +3782,18 @@
                 self.max.Enable()
             self.ticks.Enable()
         
-        self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
+        self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0)
         self.panelRaster.Layout()
         self.panelRaster.Fit()
         
         
-    def OnDefaultSize(self, event):
-        if self.panelRaster.defaultSize.GetValue():
-            self.panelRaster.widthCtrl.Disable()
-            self.panelRaster.heightOrColumnsCtrl.Disable()        
-        else:    
-            self.panelRaster.widthCtrl.Enable()
-            self.panelRaster.heightOrColumnsCtrl.Enable()
+##    def OnDefaultSize(self, event):
+##        if self.panelRaster.defaultSize.GetValue():
+##            self.panelRaster.widthCtrl.Disable()
+##            self.panelRaster.heightOrColumnsCtrl.Disable()        
+##        else:    
+##            self.panelRaster.widthCtrl.Enable()
+##            self.panelRaster.heightOrColumnsCtrl.Enable()
         
     def OnRange(self, event):
         if not self.range.GetValue():
@@ -3309,7 +3885,7 @@
             
         if self.rLegendDict['raster']:
             # type and range of map
-            rasterType = self.getRasterType(self.rLegendDict['raster'])
+            rasterType = getRasterType(self.rLegendDict['raster'])
             self.rLegendDict['type'] = rasterType
             
             range = RunCommand('r.info', flags = 'r', read = True, map = self.rLegendDict['raster']).strip().split('\n')
@@ -3328,64 +3904,88 @@
 ##            self.rLegendDict['font'] = font.GetFaceName()
 ##            self.rLegendDict['fontsize'] = font.GetPointSize()
             self.rLegendDict['color'] = self.panelRaster.font['colorCtrl'].GetColour().GetAsString(wx.C2S_NAME)
-            dc = wx.PaintDC(self)
-            font = dc.GetFont()
-            dc.SetFont(wx.Font(   pointSize = self.rLegendDict['fontsize'], family = font.GetFamily(),
-                                                style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL))
+##            dc = wx.PaintDC(self)
+##            font = dc.GetFont()
+##            dc.SetFont(wx.Font(   pointSize = self.rLegendDict['fontsize'], family = font.GetFamily(),
+##                                                style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL))
             # position
             x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
             y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
             self.rLegendDict['where'] = (x, y)
             # estimated size
-            if not self.panelRaster.defaultSize.GetValue():
-                self.rLegendDict['defaultSize'] = False
+##            if not self.panelRaster.defaultSize.GetValue():
+##                self.rLegendDict['defaultSize'] = False
+            width = self.panelRaster.widthCtrl.GetValue()
+            try:
+                width = float(width)
+                width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch')
+            except ValueError:
+                width = None
+            self.rLegendDict['width'] = width
+            if self.rLegendDict['discrete'] == 'n':
+                height = self.panelRaster.heightOrColumnsCtrl.GetValue()    
+                try:
+                    height = float(height)
+                    height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch')
+                except ValueError:
+                    height = None
+                self.rLegendDict['height'] = height
+            else:
+                cols = self.panelRaster.heightOrColumnsCtrl.GetValue()
+                self.rLegendDict['cols'] = cols
+            drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
+                                            fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
+                                            height = self.rLegendDict['height'])
+            drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'],
+                                            fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'],
+                                            width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId])
+            self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
+                
             
-                width = self.unitConv.convert(value = float(self.panelRaster.widthCtrl.GetValue()), fromUnit = currUnit, toUnit = 'inch')
-                height = self.unitConv.convert(value = float(self.panelRaster.heightOrColumnsCtrl.GetValue()), fromUnit = currUnit, toUnit = 'inch')
-            
-                if self.rLegendDict['discrete'] == 'n':  #rasterType in ('FCELL', 'DCELL'):
-                    self.rLegendDict['width'] = width 
-                    self.rLegendDict['height'] = height
-                    textPart = self.unitConv.convert(value = dc.GetTextExtent(maxim)[0], fromUnit = 'pixel', toUnit = 'inch')
-                    drawWidth = width + textPart
-                    drawHeight = height
-                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
-                else: #categorical map
-                    self.rLegendDict['width'] = width 
-                    self.rLegendDict['cols'] = self.panelRaster.heightOrColumnsCtrl.GetValue() 
-                    cat = RunCommand(   'r.category', read = True, map = self.rLegendDict['raster'],
-                                        fs = ':').strip().split('\n')
-                    rows = ceil(float(len(cat))/self.rLegendDict['cols'])
+##                if self.rLegendDict['discrete'] == 'n':  #rasterType in ('FCELL', 'DCELL'):
+##                    self.rLegendDict['width'] = width 
+##                    self.rLegendDict['height'] = height
+##                    textPart = self.unitConv.convert(value = dc.GetTextExtent(maxim)[0], fromUnit = 'pixel', toUnit = 'inch')
+##                    drawWidth = width + textPart
+##                    drawHeight = height
+##                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
+##                else: #categorical map
+##                    self.rLegendDict['width'] = width 
+##                    self.rLegendDict['cols'] = self.panelRaster.heightOrColumnsCtrl.GetValue() 
+##                    cat = RunCommand(   'r.category', read = True, map = self.rLegendDict['raster'],
+##                                        fs = ':').strip().split('\n')
+##                    
+##                    rows = ceil(float(len(cat))/self.rLegendDict['cols'])
+##
+##                    drawHeight = self.unitConv.convert(value =  1.5 *rows * self.rLegendDict['fontsize'], fromUnit = 'point', toUnit = 'inch')
+##                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = width, h = drawHeight)
+##
+##            else:
+##                self.rLegendDict['defaultSize'] = True
+##                if self.rLegendDict['discrete'] == 'n':  #rasterType in ('FCELL', 'DCELL'):
+##                    textPart = self.unitConv.convert(value = dc.GetTextExtent(maxim)[0], fromUnit = 'pixel', toUnit = 'inch')
+##                    drawWidth = self.unitConv.convert( value = self.rLegendDict['fontsize'] * 2, 
+##                                                    fromUnit = 'point', toUnit = 'inch') + textPart
+##                                
+##                    drawHeight = self.unitConv.convert(value = self.rLegendDict['fontsize'] * 10,
+##                                                    fromUnit = 'point', toUnit = 'inch')
+##                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
+##                else:#categorical map
+##                    self.rLegendDict['cols'] = self.panelRaster.heightOrColumnsCtrl.GetValue()
+##                    cat = RunCommand(   'r.category', read = True, map = self.rLegendDict['raster'],
+##                                        fs = ':').strip().split('\n')
+##                    if len(cat) == 1:# for discrete FCELL
+##                        rows = float(maxim)
+##                    else:
+##                        rows = ceil(float(len(cat))/self.rLegendDict['cols'])
+##                    drawHeight = self.unitConv.convert(value =  1.5 *rows * self.rLegendDict['fontsize'],
+##                                                    fromUnit = 'point', toUnit = 'inch')
+##                    paperWidth = self.instruction[self.pageId]['Width']- self.instruction[self.pageId]['Right']\
+##                                                                        - self.instruction[self.pageId]['Left']
+##                    drawWidth = (paperWidth / self.rLegendDict['cols']) * (self.rLegendDict['cols'] - 1) + 1
+##                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
 
-                    drawHeight = self.unitConv.convert(value =  1.5 *rows * self.rLegendDict['fontsize'], fromUnit = 'point', toUnit = 'inch')
-                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = width, h = drawHeight)
 
-            else:
-                self.rLegendDict['defaultSize'] = True
-                if self.rLegendDict['discrete'] == 'n':  #rasterType in ('FCELL', 'DCELL'):
-                    textPart = self.unitConv.convert(value = dc.GetTextExtent(maxim)[0], fromUnit = 'pixel', toUnit = 'inch')
-                    drawWidth = self.unitConv.convert( value = self.rLegendDict['fontsize'] * 2, 
-                                                    fromUnit = 'point', toUnit = 'inch') + textPart
-                                
-                    drawHeight = self.unitConv.convert(value = self.rLegendDict['fontsize'] * 10,
-                                                    fromUnit = 'point', toUnit = 'inch')
-                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
-                else:#categorical map
-                    self.rLegendDict['cols'] = self.panelRaster.heightOrColumnsCtrl.GetValue()
-                    cat = RunCommand(   'r.category', read = True, map = self.rLegendDict['raster'],
-                                        fs = ':').strip().split('\n')
-                    if len(cat) == 1:# for discrete FCELL
-                        rows = float(maxim)
-                    else:
-                        rows = ceil(float(len(cat))/self.rLegendDict['cols'])
-                    drawHeight = self.unitConv.convert(value =  1.5 *rows * self.rLegendDict['fontsize'],
-                                                    fromUnit = 'point', toUnit = 'inch')
-                    paperWidth = self.instruction[self.pageId]['Width']- self.instruction[self.pageId]['Right']\
-                                                                        - self.instruction[self.pageId]['Left']
-                    drawWidth = (paperWidth / self.rLegendDict['cols']) * (self.rLegendDict['cols'] - 1) + 1
-                    self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight)
-
-
                          
             # no data
             if self.rLegendDict['discrete'] == 'y':
@@ -3415,7 +4015,8 @@
         if self.id[0] not in self.parent.objectId:
             self.parent.objectId.append(self.id[0])
         return True
-                    
+    
+
     def updateVectorLegend(self):
         """!Save information from vector legend dialog to dictionary"""
 
@@ -3507,10 +4108,7 @@
             return True
         return False
         
-    def getRasterType(self, map):
-        rasterType = RunCommand('r.info', flags = 't', read = True, 
-                                map = map).strip().split('=')
-        return (rasterType[1] if rasterType[0] else None)
+    
         
 
              
@@ -3519,12 +4117,13 @@
         PsmapDialog.__init__(self, parent = parent, id = id, title = "Mapinfo settings", settings = settings)
         self.instruction = settings
         if self.id is not None:
-            self.mapinfoDict = self.instruction[id].GetInstruction()
+            self.mapinfo = self.instruction[self.id]
+            self.mapinfoDict = self.mapinfo.GetInstruction()
         else:
             self.id = wx.NewId()
-            mapinfo = Mapinfo(self.id)
+            self.mapinfo = Mapinfo(self.id)
 
-            self.mapinfoDict = mapinfo.GetInstruction()
+            self.mapinfoDict = self.mapinfo.GetInstruction()
             page = self.instruction.FindInstructionByType('page').GetInstruction()
             self.mapinfoDict['where'] = page['Left'], page['Top']
 
@@ -3665,11 +4264,8 @@
 ##                                        if self.colors['borderCtrl'].GetValue() else 'none')
         
         # estimation of size
-        w = self.mapinfoDict['fontsize'] * 20 # any better estimation? 
-        h = self.mapinfoDict['fontsize'] * 7
-        width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch')
-        height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch')
-        self.mapinfoDict['rect'] = wx.Rect2D(x = x, y = y, w = width, h = height)
+        self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict)
+
         
         if self.id not in self.instruction:
             mapinfo = Mapinfo(self.id)
@@ -3688,11 +4284,12 @@
         PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings)
         self.instruction = settings
         if self.id is not None:
-            self.scalebarDict = self.instruction[id].GetInstruction()
+            self.scalebar = self.instruction[id]
+            self.scalebarDict = self.scalebar.GetInstruction()
         else:
             self.id = wx.NewId()
-            scalebar = Scalebar(self.id)
-            self.scalebarDict = scalebar.GetInstruction()
+            self.scalebar = Scalebar(self.id)
+            self.scalebarDict = self.scalebar.GetInstruction()
             page = self.instruction.FindInstructionByType('page').GetInstruction()
             self.scalebarDict['where'] = page['Left'], page['Top']
 
@@ -3870,7 +4467,14 @@
         x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
         y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch')
         
+        #style
         
+        self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
+        self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
+        self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
+        self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
+        self.scalebarDict['background'] = 'n' if self.backgroundCheck.GetValue() else 'y'
+        
         # size
         
         # height
@@ -3897,31 +4501,28 @@
             return False
         self.scalebarDict['length'] = length
         
-        if self.scalebarDict['unitsLength'] != 'auto':
-            length = self.unitConv.convert(value = length, fromUnit = self.unitsLength.GetStringSelection(), toUnit = 'inch')
-        else:
-            length = self.unitConv.convert(value = length, fromUnit = self.mapUnit, toUnit = 'inch')
+##        if self.scalebarDict['unitsLength'] != 'auto':
+##            length = self.unitConv.convert(value = length, fromUnit = self.unitsLength.GetStringSelection(), toUnit = 'inch')
+##        else:
+##            length = self.unitConv.convert(value = length, fromUnit = self.mapUnit, toUnit = 'inch')
+            
         # estimation of size
         map = self.instruction.FindInstructionByType('map')
         if not map:
             map = self.instruction.FindInstructionByType('initMap')
         mapId = map.id
-
-        length *= self.instruction[mapId]['scale']
-        length *= 1.1 #for numbers on the edge
-        fontsize = 10
-        height = height + 2 * self.unitConv.convert(value = fontsize, fromUnit = 'point', toUnit = 'inch') 
-        self.scalebarDict['rect'] = wx.Rect2D(x, y, length, height)
+##
+##        length *= self.instruction[mapId]['scale']
+##        length *= 1.1 #for numbers on the edge
+##        height = height + 2 * self.unitConv.convert(value = self.scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch') 
+##        self.scalebarDict['rect'] = wx.Rect2D(x, y, length, height)
           
-        
-        self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre()  
+         
+        rectSize = self.scalebar.EstimateSize( scalebarDict = self.scalebarDict,
+                                                                scale = self.instruction[mapId]['scale'])
+        self.scalebarDict['rect'] = wx.Rect2D(x = x, y = y, w = rectSize[0], h = rectSize[1])
+        self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre() 
 
-        #style
-        self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection())
-        self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue()
-        self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue()
-        self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue()
-        self.scalebarDict['background'] = 'n' if self.backgroundCheck.GetValue() else 'y'
 
 
         if self.id not in self.instruction:
@@ -3953,7 +4554,7 @@
         self.mapId = map.id
 
 
-        self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self, mapId = self.mapId, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
+        self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(map = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
         
         notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)     
         self.textPanel = self._textPanel(notebook)
@@ -4016,12 +4617,12 @@
         
         self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight"))
         self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, value = 'pts',min = 0, max = 5, initial = 1)
+        self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1)
         self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
         
         self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border"))
         self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY)
-        self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, value = 'pts',min = 1, max = 25, initial = 1)
+        self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1)
         self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):"))
         #set values
         self.effect['backgroundCtrl'].SetValue(True if self.textDict['background'] != 'none' else False)
@@ -4116,7 +4717,7 @@
         self.northingLabel  = wx.StaticText(panel, id = wx.ID_ANY, label = "N:")
         self.eastingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
         self.northingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "")
-        east, north = PaperMapCoordinates(self, mapId = self.mapId, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
+        east, north = PaperMapCoordinates(map = self.instruction[self.mapId], x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True)
         self.eastingCtrl.SetValue(str(east))
         self.northingCtrl.SetValue(str(north))
         
@@ -4283,12 +4884,12 @@
             x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch')
             y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch')
             self.textDict['where'] = x, y
-            self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self, self.mapId, x, y, paperToMap = True)
+            self.textDict['east'], self.textDict['north'] = PaperMapCoordinates( self.instruction[self.mapId], x, y, paperToMap = True)
         else:
             self.textDict['XY'] = False
             self.textDict['east'] = self.eastingCtrl.GetValue() if self.eastingCtrl.GetValue() else self.textDict['east']
             self.textDict['north'] = self.northingCtrl.GetValue() if self.northingCtrl.GetValue() else self.textDict['north']
-            self.textDict['where'] = PaperMapCoordinates(self, mapId = self.mapId, x = float(self.textDict['east']),
+            self.textDict['where'] = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.textDict['east']),
                                                             y = float(self.textDict['north']), paperToMap = False)
         #rotation
         if self.rotCtrl.GetValue():
@@ -4311,13 +4912,6 @@
         return True
     
     
-    
-def find_key(dic, val, multiple = False):
-    """!Return the key of dictionary given the value"""
-    result = [k for k, v in dic.iteritems() if v == val]
-    if len(result) == 0 and not multiple:
-        return None
-    return sorted(result) if multiple else result[0]
 
 def convertRGB(rgb):
     """!Converts wx.Colour(255,255,255,255) and string '255:255:255',
@@ -4328,15 +4922,15 @@
         return wx.Colour(*map(int, rgb.split(':')))
         
         
-def PaperMapCoordinates(self, mapId, x, y, paperToMap = True):
+def PaperMapCoordinates(map, x, y, paperToMap = True):
     """!Converts paper (inch) coordinates -> map coordinates"""
-    unitConv = UnitConversion(self)
+    unitConv = UnitConversion()
     currRegionDict = grass.region()
     cornerEasting, cornerNorthing = currRegionDict['w'], currRegionDict['n']
-    xMap = self.instruction[mapId]['rect'][0]
-    yMap = self.instruction[mapId]['rect'][1]
-    widthMap = self.instruction[mapId]['rect'][2] * 0.0254 # to meter
-    heightMap = self.instruction[mapId]['rect'][3] * 0.0254
+    xMap = map['rect'][0]
+    yMap = map['rect'][1]
+    widthMap = map['rect'][2] * 0.0254 # to meter
+    heightMap = map['rect'][3] * 0.0254
     xScale = widthMap / abs(currRegionDict['w'] - currRegionDict['e'])
     yScale = heightMap / abs(currRegionDict['n'] - currRegionDict['s'])
     currScale = (xScale + yScale) / 2
@@ -4365,7 +4959,10 @@
     if scaleType == 0 and map:# automatic, region from raster or vector
         res = ''
         if mapType == 'raster': 
-            res = grass.read_command("g.region", flags = 'gu', rast = map)
+            try:
+                res = grass.read_command("g.region", flags = 'gu', rast = map)
+            except grass.ScriptError:
+                pass
         elif mapType == 'vector':
             res = grass.read_command("g.region", flags = 'gu', vect = map)
         currRegionDict = grass.parse_key_val(res, val_type = float)
@@ -4388,7 +4985,7 @@
         return None, None, None
     
     if not currRegionDict:
-        return None, None
+        return None, None, None
     rX = rect.x
     rY = rect.y
     rW = rect.width
@@ -4479,10 +5076,20 @@
 def GetMapBounds(filename):
     """!Run ps.map -b to get information about map bounding box"""
     try:
-        bb = map(float, RunCommand('ps.map', read = True,
+        bb = map(float, grass.read_command('ps.map',
                                         flags = 'b',
                                         input = filename).strip().split('=')[1].split(','))
     except (grass.ScriptError, IndexError):
         GError(message = _("Unable to run ps.map -b "))
         return None
     return wx.Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
+
+def getRasterType(map):
+    """!Returns type of raster map (CELL, FCELL, DCELL)"""
+    try:
+        rasterType = RunCommand('r.info', flags = 't', read = True, 
+                                map = map).strip().split('=')
+    except ScriptError:
+        GError(_("Unable to get type of raster map"))
+        return None
+    return (rasterType[1] if rasterType[0] else None)
\ No newline at end of file

Modified: grass-addons/gui/wxpython/psmap/xml/menudata_psmap.xml
===================================================================
--- grass-addons/gui/wxpython/psmap/xml/menudata_psmap.xml	2011-03-16 19:09:47 UTC (rev 45681)
+++ grass-addons/gui/wxpython/psmap/xml/menudata_psmap.xml	2011-03-16 20:55:05 UTC (rev 45682)
@@ -9,7 +9,14 @@
 		  <handler>OnPageSetup</handler>
 		  <shortcut>Ctrl+P</shortcut>
 		</menuitem>
+		<separator/>
 		<menuitem>
+		  <label>Load file</label>
+		  <help>Load text file with mapping instructions</help>
+		  <handler>OnLoadFile</handler>
+		  <shortcut>Ctrl+O</shortcut>
+		</menuitem>
+		<menuitem>
 		  <label>Export to text file</label>
 		  <help>Generate text file with mapping instructions</help>
 		  <handler>OnInstructionFile</handler>



More information about the grass-commit mailing list