コード例 #1
0
    def LoadOverlay(self, cmd):
        """Creates raster legend with d.legend

        :param cmd: d.legend command as a list

        :return: bitmap with legend
        """
        Debug.msg(5, "BitmapProvider.LoadOverlay: cmd={c}".format(c=cmd))

        fileHandler, filename = tempfile.mkstemp(suffix=".png")
        os.close(fileHandler)
        # Set the environment variables for this process
        _setEnvironment(
            self.imageWidth,
            self.imageHeight,
            filename,
            transparent=True,
            bgcolor=(0, 0, 0),
        )

        Debug.msg(1, "Render raster legend " + str(filename))
        cmdTuple = cmdlist_to_tuple(cmd)
        returncode, stdout, messages = read2_command(cmdTuple[0],
                                                     **cmdTuple[1])

        if returncode == 0:
            return BitmapFromImage(autoCropImageFromFile(filename))
        else:
            os.remove(filename)
            raise GException(messages)
コード例 #2
0
ファイル: histogram.py プロジェクト: neteler/grass
    def Draw(self,
             pdc,
             img=None,
             drawid=None,
             pdctype="image",
             coords=[0, 0, 0, 0]):
        """Draws histogram or clears window"""
        if drawid is None:
            if pdctype == "image":
                drawid = self.imagedict[img]
            elif pdctype == "clear":
                drawid is None
            else:
                drawid = NewId()
        else:
            pdc.SetId(drawid)

        pdc.BeginDrawing()

        Debug.msg(
            3,
            "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" %
            (drawid, pdctype, coords),
        )

        if pdctype == "clear":  # erase the display
            bg = wx.WHITE_BRUSH
            pdc.SetBackground(bg)
            pdc.Clear()
            self.Refresh()
            pdc.EndDrawing()
            return

        if pdctype == "image":
            bg = wx.TRANSPARENT_BRUSH
            pdc.SetBackground(bg)
            bitmap = BitmapFromImage(img)
            w, h = bitmap.GetSize()
            pdc.DrawBitmap(bitmap, coords[0], coords[1],
                           True)  # draw the composite map
            pdc.SetIdBounds(drawid, (coords[0], coords[1], w, h))

        pdc.EndDrawing()
        self.Refresh()
コード例 #3
0
ファイル: wxpyimgview_gui.py プロジェクト: hellik/grass
 def draw(self):
     app = self.app
     size = self.GetSize()
     x0 = (size.GetWidth() - app.i_width) / 2
     y0 = (size.GetHeight() - app.i_height) / 2
     dc = wx.PaintDC(self)
     data = app.imgbuf.reshape((app.i_height, app.i_width, 4))
     data = data[::, ::, 2::-1]
     fn = getattr(data, "tobytes", getattr(data, "tostring"))
     image = wx.Image(app.i_width, app.i_height, fn())
     dc.DrawBitmap(BitmapFromImage(image), x0, y0, False)
コード例 #4
0
ファイル: mapwindow.py プロジェクト: mohamedfarid556/grass
 def _rescaleIfNeeded(self, bitmap):
     """!If the bitmap has different size than the window, rescale it."""
     bW, bH = bitmap.GetSize()
     wW, wH = self.GetClientSize()
     if abs(bW - wW) > 5 or abs(bH - wH) > 5:
         params = ComputeScaledRect((bW, bH), (wW, wH))
         im = wx.ImageFromBitmap(bitmap)
         im.Rescale(params['width'], params['height'])
         self.x = params['x']
         self.y = params['y']
         bitmap = BitmapFromImage(im)
         if self._overlay:
             im = wx.ImageFromBitmap(self.bitmap_overlay)
             im.Rescale(im.GetWidth() * params['scale'],
                        im.GetHeight() * params['scale'])
             self._setOverlay(BitmapFromImage(im),
                              xperc=self.perc[0],
                              yperc=self.perc[1])
     else:
         self.x = 0
         self.y = 0
     return bitmap
コード例 #5
0
    def Compose(self, cmdLists, regions, opacityList, bgcolor, force, nprocs):
        """Performs the composition of ppm/pgm files.

        :param cmdLists: lists of rendering commands lists to compose
        :param regions: regions for 2D rendering assigned to commands
        :param opacityList: list of lists of opacity values
        :param bgcolor: background color as a tuple of 3 values 0 to 255
        :param force: if True reload all data, otherwise only missing data
        :param nprocs: number of procs to be used for rendering
        """
        Debug.msg(3, "BitmapComposer.Compose")

        count = 0

        # Variables for parallel rendering
        proc_count = 0
        proc_list = []
        queue_list = []
        cmd_lists = []

        filteredCmdLists = []
        for cmdList, region in zip(cmdLists, regions):
            if (not force and HashCmds(cmdList, region) in self._bitmapPool
                    and self._bitmapPool[HashCmds(cmdList, region)].GetSize()
                    == (self.imageWidth, self.imageHeight)):
                # TODO: find a better way than to assign the same to increase
                # the reference
                self._bitmapPool[HashCmds(cmdList,
                                          region)] = self._bitmapPool[HashCmds(
                                              cmdList, region)]
                continue
            filteredCmdLists.append((cmdList, region))

        num = len(filteredCmdLists)

        self._isComposing = True
        for cmdList, region in filteredCmdLists:
            count += 1
            # Queue object for interprocess communication
            q = Queue()
            # The separate render process
            p = Process(
                target=CompositeProcess,
                args=(
                    self.imageWidth,
                    self.imageHeight,
                    self._tempDir,
                    cmdList,
                    region,
                    opacityList,
                    bgcolor,
                    q,
                ),
            )
            p.start()

            queue_list.append(q)
            proc_list.append(p)
            cmd_lists.append((cmdList, region))

            proc_count += 1

            # Wait for all running processes and read/store the created images
            if proc_count == nprocs or count == num:
                for i in range(len(cmd_lists)):
                    proc_list[i].join()
                    filename = queue_list[i].get()
                    if filename is None:
                        self._bitmapPool[HashCmds(
                            cmd_lists[i][0],
                            cmd_lists[i][1])] = createNoDataBitmap(
                                self.imageWidth,
                                self.imageHeight,
                                text="Failed to render")
                    else:
                        self._bitmapPool[HashCmds(
                            cmd_lists[i][0],
                            cmd_lists[i][1])] = BitmapFromImage(
                                wx.Image(filename))
                        os.remove(filename)
                proc_count = 0
                proc_list = []
                queue_list = []
                cmd_lists = []

            self.compositionContinues.emit(current=count,
                                           text=_("Overlaying map layers"))
            if self._stopComposing:
                self._stopComposing = False
                break

        self._isComposing = False
コード例 #6
0
ファイル: widgets.py プロジェクト: petrasovaa/grass
    def __init__(self, parent, cols, id=wx.ID_ANY,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
                 wx.LC_SINGLE_SEL):
        """Creates list for points.

        PointsList class was created from GCPList class in GCP manager. It is possible
        to be shared by GCP and VNET front end.

        Important parameters:
        :param cols: is list containing list items. which represents columns.
                This columns will be added in order as they are in list.
                Class will add as first column "use" with number of point and checkbox.
                Structure of list item must be this:
               -1. item: column name
               -2. item: column label
               -3. item: If column is editable by user, it must contain convert function to convert
                         inserted string to it's type for sorting. Use None for not editable
                         columns. Values for insertion can be in list. This allows insert
                         just values in the list.
               -4. item: Default value for column cell. Value should be given in it's  type
                         in order to sorting would work properly. If 3. item is list, it must be index
                         of some item in the list.

        Example of cols parameter:
                 column name, column label, convert function, default val
        @code
         cols =   [
                   ['E', _('source E'), float, 0.0],
                   ['N', _('source N'), float, 0.0],
                   ['E', _('target E'), float, 0.0],
                   ['N', _('target N'), float, 0.0],
                   ['F_Err', _('Forward error'), None, 0],
                   ['B_Err', _(Backward error'), None, 0]
                   ['type', _('type'), [_(""), _("Start point"), _("End point")], 0] # Select from 3 choices ("Start point", "End point"),
                                                                                     # Choice with index 0 ("") is default.
                  ]
        @endcode
        """

        ListCtrl.__init__(self, parent, id, pos, size, style)

        # Mixin settings
        CheckListCtrlMixin.__init__(self)
        ListCtrlAutoWidthMixin.__init__(self)
        # TextEditMixin.__init__(self)

        # inserts first column with points numbers and checkboxes
        cols.insert(0, ['use', _('use'), False, 0])

        self.colsData = cols
        self.dataTypes = {
            "colName": 0,
            "colLabel": 1,
            "colEditable": 2,
            "itemDefaultValue": 3}  # just for better understanding

        # information whether list items are checked or not
        self.CheckList = []

        self._createCols()
        self.hiddenCols = {}

        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)

        self.selected = wx.NOT_FOUND
        self.selectedkey = -1

        # CheckListCtrlMixin must set an ImageList first
        self.il = self.GetImageList(wx.IMAGE_LIST_SMALL)

        # images for column sorting
        SmallUpArrow = BitmapFromImage(self.getSmallUpArrowImage())
        SmallDnArrow = BitmapFromImage(self.getSmallDnArrowImage())
        self.sm_dn = self.il.Add(SmallDnArrow)
        self.sm_up = self.il.Add(SmallUpArrow)

        # initialize column sorter
        self.itemDataMap = []
        ncols = self.GetColumnCount()
        ColumnSorterMixin.__init__(self, ncols)

        # init to ascending sort on first click
        self._colSortFlag = [1] * ncols

        # same structure as itemDataMap, information about choice index selected
        # if cell is in column without values to choose then is -1
        self.selIdxs = []

        self.ResizeColumns()
        self.SetColumnWidth(0, 50)
コード例 #7
0
ファイル: gis_set.py プロジェクト: snakeice/grass
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_FRAME_STYLE):

        #
        # GRASS variables
        #
        self.gisbase = os.getenv("GISBASE")
        self.grassrc = sgui.read_gisrc()
        self.gisdbase = self.GetRCValue("GISDBASE")

        #
        # list of locations/mapsets
        #
        self.listOfLocations = []
        self.listOfMapsets = []
        self.listOfMapsetsSelectable = []

        wx.Frame.__init__(self, parent=parent, id=id, style=style)

        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)

        # scroll panel was used here but not properly and is probably not need
        # as long as it is not high too much
        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        # i18N

        #
        # graphical elements
        #
        # image
        try:
            if os.getenv('ISISROOT'):
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner_isis.png")
            else:
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner.png")
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY,
                wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG))
        except:
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY, BitmapFromImage(wx.EmptyImage(530,
                                                                     150)))

        # labels
        # crashes when LOCATION doesn't exist
        # get version & revision
        grassVersion, grassRevisionStr = sgui.GetVersion()

        self.gisdbase_box = StaticBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=" %s " % _("1. Select GRASS GIS database directory"))
        self.location_box = StaticBox(parent=self.panel,
                                      id=wx.ID_ANY,
                                      label=" %s " %
                                      _("2. Select GRASS Location"))
        self.mapset_box = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _("3. Select GRASS Mapset"))

        self.lmessage = StaticText(parent=self.panel)
        # It is not clear if all wx versions supports color, so try-except.
        # The color itself may not be correct for all platforms/system settings
        # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
        # there is no 'warning' color.
        try:
            self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
        except AttributeError:
            pass

        self.gisdbase_panel = wx.Panel(parent=self.panel)
        self.location_panel = wx.Panel(parent=self.panel)
        self.mapset_panel = wx.Panel(parent=self.panel)

        self.ldbase = StaticText(
            parent=self.gisdbase_panel,
            id=wx.ID_ANY,
            label=_("GRASS GIS database directory contains Locations."))

        self.llocation = StaticWrapText(
            parent=self.location_panel,
            id=wx.ID_ANY,
            label=_("All data in one Location is in the same "
                    " coordinate reference system (projection)."
                    " One Location can be one project."
                    " Location contains Mapsets."),
            style=wx.ALIGN_LEFT)

        self.lmapset = StaticWrapText(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            label=_("Mapset contains GIS data related"
                    " to one project, task within one project,"
                    " subregion or user."),
            style=wx.ALIGN_LEFT)

        try:
            for label in [self.ldbase, self.llocation, self.lmapset]:
                label.SetForegroundColour(
                    wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        except AttributeError:
            # for explanation of try-except see above
            pass

        # buttons
        self.bstart = Button(parent=self.panel,
                             id=wx.ID_ANY,
                             label=_("Start &GRASS session"))
        self.bstart.SetDefault()
        self.bexit = Button(parent=self.panel, id=wx.ID_EXIT)
        self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
        self.bhelp = Button(parent=self.panel, id=wx.ID_HELP)
        self.bbrowse = Button(parent=self.gisdbase_panel,
                              id=wx.ID_ANY,
                              label=_("&Browse"))
        self.bmapset = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC New mapset
            label=_("&New"))
        self.bmapset.SetToolTip(_("Create a new Mapset in selected Location"))
        self.bwizard = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC New location
            label=_("N&ew"))
        self.bwizard.SetToolTip(
            _("Create a new location using location wizard."
              " After location is created successfully,"
              " GRASS session is started."))
        self.rename_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Rename location
            label=_("Ren&ame"))
        self.rename_location_button.SetToolTip(_("Rename selected location"))
        self.delete_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Delete location
            label=_("De&lete"))
        self.delete_location_button.SetToolTip(_("Delete selected location"))
        self.download_location_button = Button(parent=self.location_panel,
                                               id=wx.ID_ANY,
                                               label=_("Do&wnload"))
        self.download_location_button.SetToolTip(_("Download sample location"))

        self.rename_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Rename mapset
            label=_("&Rename"))
        self.rename_mapset_button.SetToolTip(_("Rename selected mapset"))
        self.delete_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Delete mapset
            label=_("&Delete"))
        self.delete_mapset_button.SetToolTip(_("Delete selected mapset"))

        # textinputs
        self.tgisdbase = TextCtrl(parent=self.gisdbase_panel,
                                  id=wx.ID_ANY,
                                  value="",
                                  size=(300, -1),
                                  style=wx.TE_PROCESS_ENTER)

        # Locations
        self.lblocations = GListBox(parent=self.location_panel,
                                    id=wx.ID_ANY,
                                    size=(180, 200),
                                    choices=self.listOfLocations)
        self.lblocations.SetColumnWidth(0, 180)

        # TODO: sort; but keep PERMANENT on top of list
        # Mapsets
        self.lbmapsets = GListBox(parent=self.mapset_panel,
                                  id=wx.ID_ANY,
                                  size=(180, 200),
                                  choices=self.listOfMapsets)
        self.lbmapsets.SetColumnWidth(0, 180)

        # layout & properties, first do layout so everything is created
        self._do_layout()
        self._set_properties(grassVersion, grassRevisionStr)

        # events
        self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
        self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
        self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
        self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
        self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)

        self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
        self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
        self.download_location_button.Bind(wx.EVT_BUTTON,
                                           self.DownloadLocation)
        self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
        self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)

        self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
        self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)