def OnPaint(self, evt):
        """
        Internal use, handles the drawing of the widget.
        :param evt: wxEvent instance.
        :return: None
        """

        value = self.value
        # reversing the max/min if wx.SL_INVERSE was set
        if self.inverse:
            maxValue = self.minValue
            minValue = self.maxValue
            sliderRange = minValue - maxValue
        else:
            minValue = self.minValue
            maxValue = self.maxValue
            sliderRange = maxValue - minValue

        # grabbing the colours and setting the wxSlider as the same and the
        # colours will also be used in the drawing of the labels
        forecolour = self.GetForegroundColour()
        backcolour = self.GetBackgroundColour()
        self.Slider.SetForegroundColour(forecolour)
        self.Slider.SetBackgroundColour(backcolour)

        panelW, panelH = self.GetSizeTuple()
        sliderW, sliderH = self.Slider.GetSize()
        sliderX, sliderY = self.Slider.GetPosition()

        bmp = wx.EmptyBitmap(panelW, panelH)
        font = self.GetFont()
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetFont(font)

        # drawing the background for the labels
        dc.SetBrush(wx.Brush(wx.Colour(*backcolour)))
        dc.SetPen(wx.Pen(wx.Colour(*backcolour), 0))
        dc.DrawRectangle(0, 0, panelW, panelH)
        dc.SetTextForeground(wx.Colour(*forecolour))
        dc.SetTextBackground(wx.Colour(*backcolour))

        if self.mLabel:
            print 'mLabel'
            # converting the max/min to strings
            maxText = self.floatFormat % maxValue
            minText = self.floatFormat % minValue

            # getting the size in pixels of the max/min values
            minW, minH = dc.GetTextExtent(minText)
            maxW, maxH = dc.GetTextExtent(maxText)

            if self.horizontal:
                if self.top:
                    y = sliderY + sliderH
                else:
                    y = sliderY - minH
                minX = sliderX
                maxX = panelW - maxW
                minY = y
                maxY = y
            else:
                if self.left:
                    x = sliderX + sliderW + 3
                else:
                    x = sliderX - minW
                minY = sliderY
                maxY = sliderY + sliderH - maxH
                minX = x
                maxX = x
            dc.DrawText(minText, minX, minY)
            dc.DrawText(maxText, maxX, maxY)

        if self.vLabel:
            print 'vLabel'
            valText = self.floatFormat % value
            valW, valH = dc.GetTextExtent(valText)

            if self.horizontal:
                slider = float(sliderW)
                val = valW
            else:
                slider = float(sliderH)
                val = valH
            sldRatio = float(slider) / sliderRange
            loc = sldRatio * value

            if value == minValue:
                pos = 0
            elif value == maxValue:
                pos = slider - val
            else:
                pos = loc - (val * (loc / slider))

            if self.top:
                pos = (pos, sliderY - valH)
            elif self.left:
                pos = (sliderX - valW - 3, pos)
            elif self.horizontal:
                pos = (pos, sliderY + sliderH)
            else:
                pos = (sliderX + sliderW, pos)
            dc.DrawText(valText, *pos)

        dc.Destroy()
        del dc

        pdc = wx.PaintDC(self)
        pdc.DrawBitmap(bmp, 0, 0)

        evt.Skip()
Exemple #2
0
    def SetBalloonShape(self, event=None):
        """
        Sets the balloon shape.

        :param `event`: on wxGTK, a `wx.WindowCreateEvent` event to process.
        """

        size = self.GetSize()
        pos = self.GetPosition()

        dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
        textlabel = self._balloonmsg.GetLabel()
        textfont = self._balloonmsg.GetFont()
        textextent = dc.GetFullTextExtent(textlabel, textfont)

        boxheight = size.y - textextent[1] * len(textlabel.split("\n"))
        boxwidth = size.x

        position = wx.GetMousePosition()

        xpos = position[0]
        ypos = position[1]

        if xpos > 20 and ypos > 20:

            # This Is NW Positioning
            positioning = "NW"
            xpos = position[0] - boxwidth + 20
            ypos = position[1] - boxheight - 20

        elif xpos <= 20 and ypos <= 20:

            # This Is SE Positioning
            positioning = "SE"
            xpos = position[0] - 20
            ypos = position[1]

        elif xpos > 20 and ypos <= 20:

            # This Is SW Positioning
            positioning = "SW"
            xpos = position[0] - boxwidth + 20
            ypos = position[1]

        else:

            # This Is NE Positioning
            positioning = "NE"
            xpos = position[0]
            ypos = position[1] - boxheight + 20

        bmp = wx.EmptyBitmap(size.x, size.y)
        dc = wx.BufferedDC(None, bmp)
        dc.BeginDrawing()
        dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0), wx.SOLID))
        dc.Clear()
        dc.SetPen(wx.Pen(wx.Colour(0, 0, 0), 1, wx.TRANSPARENT))

        if self._shape == BT_ROUNDED:
            dc.DrawRoundedRectangle(0, 20, boxwidth, boxheight - 20, 12)

        elif self._shape == BT_RECTANGLE:
            dc.DrawRectangle(0, 20, boxwidth, boxheight - 20)

        if positioning == "NW":
            dc.DrawPolygon(
                ((boxwidth - 40, boxheight), (boxwidth - 20, boxheight + 20),
                 (boxwidth - 20, boxheight)))
        elif positioning == "SE":
            dc.DrawPolygon(((20, 20), (20, 0), (40, 20)))

        elif positioning == "SW":
            dc.DrawPolygon(
                ((boxwidth - 40, 20), (boxwidth - 20, 0), (boxwidth - 20, 20)))

        else:
            dc.DrawPolygon(
                ((20, boxheight), (20, boxheight + 20), (40, boxheight)))

        dc.EndDrawing()

        r = wx.RegionFromBitmapColour(bmp, wx.Colour(0, 0, 0))
        self.hasShape = self.SetShape(r)

        if self._tipstyle == BT_BUTTON:
            colour = self.panel.GetBackgroundColour()
            self._closebutton.SetBackgroundColour(colour)

        self.SetPosition((xpos, ypos))
Exemple #3
0
    def Realize(self):
        """
        Calculates tool layouts and positions.

        Must be called after tools are added to the tool bar, as otherwise the newly
        added tools will not be displayed.

        :note: Reimplemented from :class:`~wx.lib.agw.ribbon.control.RibbonControl`.
        """

        if self._art is None:
            return False

        # Calculate the size of each group and the position/size of each tool
        temp_dc = wx.MemoryDC()
        group_count = len(self._groups)

        for group in self._groups:

            prev = None
            tool_count = len(group.tools)
            tallest = 0

            for t, tool in enumerate(group.tools):

                tool.size, tool.dropdown = self._art.GetToolSize(
                    temp_dc, self, tool.bitmap.GetSize(), tool.kind, t == 0,
                    t == (tool_count - 1))
                tool.state = tool.state & ~RIBBON_TOOLBAR_TOOL_DISABLED
                if t == 0:
                    tool.state |= RIBBON_TOOLBAR_TOOL_FIRST
                if t == tool_count - 1:
                    tool.state |= RIBBON_TOOLBAR_TOOL_LAST
                if tool.size.GetHeight() > tallest:
                    tallest = tool.size.GetHeight()
                if prev:
                    tool.position = wx.Point(*prev.position)
                    tool.position.x += prev.size.x
                else:
                    tool.position = wx.Point(0, 0)

                prev = tool

            if tool_count == 0:
                group.size = wx.Size(0, 0)
            else:
                group.size = wx.Size(prev.position.x + prev.size.x, tallest)
                for tool in group.tools:
                    tool.size.SetHeight(tallest)

        # Calculate the minimum size for each possible number of rows
        sep = self._art.GetMetric(RIBBON_ART_TOOL_GROUP_SEPARATION_SIZE)
        smallest_area = 10000
        row_sizes = [wx.Size(0, 0) for i in range(self._nrows_max)]
        major_axis = ((self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL)
                      and [wx.VERTICAL] or [wx.HORIZONTAL])[0]
        self.SetMinSize(wx.Size(0, 0))

        minSize = wx.Size(10000, 10000)

        # See if we're sizing flexibly (i.e. wrapping), and set min size differently
        sizingFlexibly = False
        panel = self.GetParent()

        if isinstance(panel, RibbonPanel) and (panel.GetFlags()
                                               & RIBBON_PANEL_FLEXIBLE):
            sizingFlexibly = True

        # Without this, there will be redundant horizontal space because SetMinSize will
        # use the smallest possible height (and therefore largest width).
        if sizingFlexibly:
            major_axis = wx.HORIZONTAL

        for nrows in range(self._nrows_min, self._nrows_max + 1):

            for r in range(nrows):
                row_sizes[r] = wx.Size(0, 0)

            for g in range(group_count):

                group = self._groups[g]
                shortest_row = 0

                for r in range(1, nrows):
                    if row_sizes[r].GetWidth(
                    ) < row_sizes[shortest_row].GetWidth():
                        shortest_row = r

                row_sizes[shortest_row].x += group.size.x + sep
                if group.size.y > row_sizes[shortest_row].y:
                    row_sizes[shortest_row].y = group.size.y

            size = wx.Size(0, 0)

            for r in range(nrows):
                if row_sizes[r].GetWidth() != 0:
                    row_sizes[r].DecBy(sep, 0)
                if row_sizes[r].GetWidth() > size.GetWidth():
                    size.SetWidth(row_sizes[r].GetWidth())

                size.IncBy(0, row_sizes[r].y)

            self._sizes[nrows - self._nrows_min] = size

            if GetSizeInOrientation(size, major_axis) < smallest_area:
                smallest_area = GetSizeInOrientation(size, major_axis)
                self.SetMinSize(size)

            if sizingFlexibly:
                if size.x < minSize.x:
                    minSize.x = size.x
                if size.y < minSize.y:
                    minSize.y = size.y

        if sizingFlexibly:
            # Give it the min size in either direction regardless of row,
            # so that we're able to vary the size of the panel according to
            # the space the toolbar takes up.
            self.SetMinSize(minSize)

        # Position the groups
        dummy_event = wx.SizeEvent(self.GetSize())
        self.OnSize(dummy_event)

        return True
Exemple #4
0
 def clearBmp(self, bmp):
     dc = wx.MemoryDC()
     dc.SelectObject(bmp)
     dc.SetBackground(wx.Brush("white"))
     dc.Clear()
Exemple #5
0
    def _Render(self):
        """Renders the tab, complete with the icon, text, and close button"""
        if self.tabBitmap:
            del self.tabBitmap

        height = self.tabHeight

        #rect = wx.Rect(0, 0, self.tabWidth, self.tabHeight)

        canvas = wx.EmptyBitmap(self.tabWidth, self.tabHeight, 24)

        mdc = wx.MemoryDC()

        mdc.SelectObject(canvas)
        #mdc.SetBackground(wx.Brush ((0x12,0x23,0x32)))
        mdc.Clear()

        #r = copy.copy(rect)
        #r.top = r.left = 0
        #r.height = height
        mdc.DrawBitmap(self.tabBackBitmap, 0, 0, True)

        if self.tabImg:
            bmp = wx.BitmapFromImage(self.tabImg)
            if self.contentWidth > 16:  # @todo: is this conditional relevant anymore?
                # Draw tab icon
                mdc.DrawBitmap(bmp, self.leftWidth + self.padding - bmp.GetWidth()/2, (height - bmp.GetHeight())/2)
            textStart = self.leftWidth + self.padding + bmp.GetWidth()/2
        else:
            textStart = self.leftWidth

        mdc.SetFont(self.font)

        maxsize = self.tabWidth - textStart - self.rightWidth - self.padding*4
        color = self.selectedColor if self.selected else self.inactiveColor

        mdc.SetTextForeground(colorUtils.GetSuitableColor(color, 1))

        text = drawUtils.GetPartialText(mdc, self.text, maxsize, "")
        tx, ty = mdc.GetTextExtent(text)
        mdc.DrawText(text, textStart + self.padding, height / 2 - ty / 2)

        if self.closeButton:
            if self.closeBtnHovering:
                cbmp = self.ctabCloseBmp
            else:
                cimg = self.ctabCloseBmp.ConvertToImage()
                cimg = cimg.AdjustChannels(0.7, 0.7, 0.7, 0.3)
                cbmp = wx.BitmapFromImage(cimg)

            mdc.DrawBitmap(
                        cbmp,
                        self.contentWidth + self.leftWidth - self.ctabCloseBmp.GetWidth()/2,
                        (height - self.ctabCloseBmp.GetHeight())/2)

        mdc.SelectObject(wx.NullBitmap)

        canvas.SetMaskColour((0x12, 0x23, 0x32))
        img = canvas.ConvertToImage()

        if not img.HasAlpha():
            img.InitAlpha()

        bmp = wx.BitmapFromImage(img)
        self.tabBitmap = bmp
Exemple #6
0
    def paintScatterplot(self, lower1, upper1, lower2, upper2, slope,
                         intercept):
        """
		Paint the scatterplot showing the given thresholds and correlation
		@param lower1 The lower threshold for Ch1
		@param upper1 The upper threshold for Ch1
		@param lower2 The lower threshold for Ch2
		@param upper2 The upper threshold for Ch2
		"""
        dc = wx.MemoryDC()
        dc.SelectObject(self.buffer)
        dc.BeginDrawing()

        colour = self.parent.GetBackgroundColour()

        dc.SetBackground(wx.Brush(colour))
        dc.SetPen(wx.Pen(colour, 0))
        dc.SetBrush(wx.Brush(colour))
        dc.DrawRectangle(0, 0, self.size[0], self.size[1])
        if not self.scatter:
            dc.EndDrawing()
            dc = None
            return

        c = 256.0 / (self.scalarMax + 1)
        bmp = self.scatter.ConvertToBitmap()
        self.scatterBitmap = bmp

        if not self.verticalLegend:
            verticalLegend = lib.ImageOperations.paintCTFValues(
                self.sources[1].getColorTransferFunction(),
                height=256,
                width=self.legendWidth,
                paintScalars=self.paintScalars)
            self.verticalLegend = verticalLegend
        else:
            verticalLegend = self.verticalLegend

        if not self.horizontalLegend:
            horizontalLegend = lib.ImageOperations.paintCTFValues(
                self.sources[0].getColorTransferFunction(),
                width=256,
                height=self.legendWidth,
                paintScalars=self.paintScalars)
            self.horizontalLegend = horizontalLegend
        else:
            horizontalLegend = self.horizontalLegend

        horizontalLegendWidth = verticalLegend.GetWidth() + 2 * self.emptySpace

        dc.DrawBitmap(verticalLegend, 0, 0)
        dc.DrawBitmap(horizontalLegend, self.xoffset + horizontalLegendWidth,
                      bmp.GetHeight() + self.emptySpace)
        dc.DrawBitmap(bmp, self.xoffset + horizontalLegendWidth, 0, True)

        self.bmp = self.buffer

        dc.SetPen(wx.Pen(wx.Colour(255, 255, 255), 1))

        if slope and intercept:
            x = 255
            y = 255 - (255 * slope + intercept)
            dc.DrawLine(self.xoffset + horizontalLegendWidth, 255 - intercept,
                        self.xoffset + horizontalLegendWidth + x, y)

        ymax = 255
        # These are the threshold lines
        dc.DrawLine(self.xoffset + horizontalLegendWidth + lower1 * c, 0,
                    self.xoffset + horizontalLegendWidth + lower1 * c, 255)
        dc.DrawLine(self.xoffset + horizontalLegendWidth, ymax - lower2 * c,
                    self.xoffset + 255 + horizontalLegendWidth,
                    ymax - lower2 * c)
        dc.DrawLine(self.xoffset + horizontalLegendWidth + upper1 * c, 0,
                    self.xoffset + horizontalLegendWidth + upper1 * c, 255)
        dc.DrawLine(self.xoffset + horizontalLegendWidth, ymax - upper2 * c,
                    self.xoffset + horizontalLegendWidth + 255,
                    ymax - upper2 * c)

        if upper1 != lower1 and upper2 != lower2:
            overlay = lib.ImageOperations.getOverlay(
                int((upper1 - lower1) * c), int((upper2 - lower2) * c),
                (0, 0, 255), 64)
            overlay = overlay.ConvertToBitmap()
            borders = lib.ImageOperations.getOverlayBorders(
                int((upper1 - lower1) * c) + 1,
                int((upper2 - lower2) * c) + 1, (0, 0, 255),
                90,
                lineWidth=2)
            borders = borders.ConvertToBitmap()
            dc.DrawBitmap(overlay,
                          self.xoffset + horizontalLegendWidth + lower1 * c,
                          ymax - upper2 * c, 1)
            dc.DrawBitmap(borders,
                          self.xoffset + horizontalLegendWidth + lower1 * c,
                          ymax - upper2 * c, 1)

        if not self.scatterLegend:
            self.scatterLegend = lib.ImageOperations.paintCTFValues(
                self.scatterCTF,
                width=self.legendWidth,
                height=256,
                paintScale=1)

        dc.DrawBitmap(
            self.scatterLegend,
            self.xoffset + horizontalLegendWidth + 255 + 2 * self.emptySpace,
            0)

        dc.SetTextForeground(wx.Colour(255, 255, 255))
        dc.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.NORMAL))
        dc.DrawText("%d" % lower2, 3, ymax - lower2 * c)
        dc.DrawText("%d" % lower1,
                    self.xoffset + horizontalLegendWidth + lower1 * c, 265)

        self.scatterLegendBitmap = self.buffer

        self.dc = dc
        del self.dc
        dc.EndDrawing()
        dc = None
    def Render(self):
        """
        Recalculate dimensions as client area may have been scrolled or resized.
        The smallest unit of rendering that can be done is the pdf page. So render
        the drawing commands for the pages in the visible rectangle into a buffer
        big enough to hold this set of pages. Force re-creating the page buffer
        only when client view moves outside it.
        With PyPDF2, use gc.Translate to render each page wrt the pdf origin,
        which is at the bottom left corner of the page.
        """
        if not self.have_file:
            return
        self.CalculateDimensions()
        if not self.page_buffer_valid:
            # Initialize the buffer bitmap.
            self.pagebuffer = wx.Bitmap(self.pagebufferwidth,
                                        self.pagebufferheight)
            self.pdc = wx.MemoryDC(self.pagebuffer)  # must persist

            gc = GraphicsContext.Create(
                self.pdc)  # Cairo/wx.GraphicsContext API

            # white background
            path = gc.CreatePath()
            path.AddRectangle(0, 0, self.pagebuffer.GetWidth(),
                              self.pagebuffer.GetHeight())
            gc.SetBrush(wx.WHITE_BRUSH)
            gc.FillPath(path)

            for pageno in range(self.frompage, self.topage + 1):
                self.xpageoffset = 0 - self.x0
                self.ypageoffset = pageno * self.Ypagepixels - self.page_y0
                gc.PushState()
                if mupdf:
                    gc.Translate(self.xpageoffset, self.ypageoffset)
                    # scaling is done inside RenderPage
                else:

                    gc.Translate(
                        self.xpageoffset,
                        self.ypageoffset + self.pageheight * self.scale)
                    gc.Scale(self.scale, self.scale)
                self.pdfdoc.RenderPage(gc, pageno, scale=self.scale)
                # Show inter-page gap
                gc.SetBrush(wx.Brush(wx.Colour(180, 180, 180)))  #mid grey
                gc.SetPen(wx.TRANSPARENT_PEN)
                if mupdf:
                    gc.DrawRectangle(0, self.pageheight * self.scale,
                                     self.pagewidth * self.scale,
                                     self.page_gap * self.scale)
                else:
                    gc.DrawRectangle(0, 0, self.pagewidth, self.page_gap)
                gc.PopState()
            gc.PushState()
            gc.Translate(0 - self.x0, 0 - self.page_y0)
            self.RenderPageBoundaries(gc)
            gc.PopState()

        self.page_buffer_valid = True
        self.Refresh(
            0
        )  # Blit appropriate area of new or existing page buffer to screen

        # ensure we stay on the same page after zoom scale is changed
        if self.page_after_zoom_change:
            self.GoPage(self.page_after_zoom_change)
            self.page_after_zoom_change = None
Exemple #8
0
    def ShowOSD(
            self,
            osdText="",
            fontInfo=None,
            textColour=(255, 255, 255),
            outlineColour=(0, 0, 0),
            alignment=0,
            offset=(0, 0),
            displayNumber=0,
            timeout=3.0,
            event=None,
            skin=None,
    ):
        self.timer.cancel()
        if osdText.strip() == "":
            self.bitmap = wx.EmptyBitmap(0, 0)
            SetWindowPos(self.hwnd, 0, 0, 0, 0, 0, HWND_FLAGS | SWP_HIDEWINDOW)
            SetEvent(event)
            return

        #self.Freeze()
        memoryDC = wx.MemoryDC()

        # make sure the mask colour is not used by foreground or
        # background colour
        forbiddenColours = (textColour, outlineColour)
        maskColour = (255, 0, 255)
        if maskColour in forbiddenColours:
            maskColour = (0, 0, 2)
            if maskColour in forbiddenColours:
                maskColour = (0, 0, 3)
        maskBrush = wx.Brush(maskColour, wx.SOLID)
        memoryDC.SetBackground(maskBrush)

        if fontInfo is None:
            fontInfo = DEFAULT_FONT_INFO
        font = wx.FontFromNativeInfoString(fontInfo)
        memoryDC.SetFont(font)

        textLines = osdText.splitlines()
        sizes = [memoryDC.GetTextExtent(line or " ") for line in textLines]
        textWidths, textHeights = zip(*sizes)
        textWidth = max(textWidths)
        textHeight = sum(textHeights)

        if skin:
            bitmap = self.GetSkinnedBitmap(textLines, textWidths, textHeights,
                                           textWidth, textHeight, memoryDC,
                                           textColour, "Default")
            width, height = bitmap.GetSize()
        elif outlineColour is None:
            width, height = textWidth, textHeight
            bitmap = wx.EmptyBitmap(width, height)
            memoryDC.SelectObject(bitmap)

            # fill the DC background with the maskColour
            memoryDC.Clear()

            # draw the text with the foreground colour
            memoryDC.SetTextForeground(textColour)
            DrawTextLines(memoryDC, textLines, textHeights)

            # mask the bitmap, so we can use it to get the needed
            # region of the window
            memoryDC.SelectObject(wx.NullBitmap)
            bitmap.SetMask(wx.Mask(bitmap, maskColour))

            # fill the anti-aliased pixels of the text with the foreground
            # colour, because the region of the window will add these
            # half filled pixels also. Otherwise we would get an ugly
            # border with mask-coloured pixels.
            memoryDC.SetBackground(wx.Brush(textColour, wx.SOLID))
            memoryDC.SelectObject(bitmap)
            memoryDC.Clear()
            memoryDC.SelectObject(wx.NullBitmap)
        else:
            width, height = textWidth + 5, textHeight + 5
            outlineBitmap = wx.EmptyBitmap(width, height, 1)
            outlineDC = wx.MemoryDC()
            outlineDC.SetFont(font)
            outlineDC.SelectObject(outlineBitmap)
            outlineDC.Clear()
            outlineDC.SetBackgroundMode(wx.SOLID)
            DrawTextLines(outlineDC, textLines, textHeights)
            outlineDC.SelectObject(wx.NullBitmap)
            outlineBitmap.SetMask(wx.Mask(outlineBitmap))
            outlineDC.SelectObject(outlineBitmap)

            bitmap = wx.EmptyBitmap(width, height)
            memoryDC.SetTextForeground(outlineColour)
            memoryDC.SelectObject(bitmap)
            memoryDC.Clear()

            Blit = memoryDC.Blit
            logicalFunc = wx.COPY
            for x in xrange(5):
                for y in xrange(5):
                    Blit(x, y, width, height, outlineDC, 0, 0, logicalFunc,
                         True)
            outlineDC.SelectObject(wx.NullBitmap)
            memoryDC.SetTextForeground(textColour)
            DrawTextLines(memoryDC, textLines, textHeights, 2, 2)
            memoryDC.SelectObject(wx.NullBitmap)
            bitmap.SetMask(wx.Mask(bitmap, maskColour))

        region = wx.RegionFromBitmap(bitmap)
        self.SetShape(region)
        self.bitmap = bitmap
        monitorDimensions = GetMonitorDimensions()
        try:
            displayRect = monitorDimensions[displayNumber]
        except IndexError:
            displayRect = monitorDimensions[0]
        xOffset, yOffset = offset
        xFunc, yFunc = ALIGNMENT_FUNCS[alignment]
        x = displayRect.x + xFunc((displayRect.width - width), xOffset)
        y = displayRect.y + yFunc((displayRect.height - height), yOffset)
        deviceContext = wx.ClientDC(self)
        deviceContext.DrawBitmap(self.bitmap, 0, 0, False)
        SetWindowPos(self.hwnd, 0, x, y, width, height,
                     HWND_FLAGS | SWP_SHOWWINDOW)

        if timeout > 0.0:
            self.timer = threading.Timer(timeout, self.OnTimeout)
            self.timer.start()
        eg.app.Yield(True)
        SetEvent(event)
Exemple #9
0
 def OnPaint(self, event):
     dc = wx.PaintDC(self)
     if self.bitmap:
         dc.Blit(0, 0, self.bitmap.GetWidth(), self.bitmap.GetHeight(),
                 wx.MemoryDC(self.bitmap), 0, 0)
Exemple #10
0
    def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, log=None):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        panel = wx.Panel(self)
        
        self._ribbon = RB.RibbonBar(panel, wx.ID_ANY, agwStyle=RB.RIBBON_BAR_DEFAULT_STYLE|RB.RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS)

        self._bitmap_creation_dc = wx.MemoryDC()
        self._colour_data = wx.ColourData()
        
        home = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Examples", CreateBitmap("ribbon"))
        toolbar_panel = RB.RibbonPanel(home, wx.ID_ANY, "Toolbar", wx.NullBitmap, wx.DefaultPosition,
                                       wx.DefaultSize, agwStyle=RB.RIBBON_PANEL_NO_AUTO_MINIMISE|RB.RIBBON_PANEL_EXT_BUTTON)
        
        toolbar = RB.RibbonToolBar(toolbar_panel, ID_MAIN_TOOLBAR)
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_left"))
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_center"))
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_right"))
        toolbar.AddSeparator()
        toolbar.AddHybridTool(wx.ID_NEW, wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE_AS, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddDropdownTool(wx.ID_UNDO, wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddDropdownTool(wx.ID_REDO, wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_REPORT_VIEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_LIST_VIEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddHybridTool(ID_POSITION_LEFT, CreateBitmap("position_left"), "Align ribbonbar vertically\non the left\nfor demonstration purposes")
        toolbar.AddHybridTool(ID_POSITION_TOP, CreateBitmap("position_top"), "Align the ribbonbar horizontally\nat the top\nfor demonstration purposes")
        toolbar.AddSeparator()
        toolbar.AddHybridTool(wx.ID_PRINT, wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_OTHER, wx.Size(16, 15)),
                              "This is the Print button tooltip\ndemonstrating a tooltip")
        toolbar.SetRows(2, 3)

        selection_panel = RB.RibbonPanel(home, wx.ID_ANY, "Selection", CreateBitmap("selection_panel"))
        selection = RB.RibbonButtonBar(selection_panel)
        selection.AddSimpleButton(ID_SELECTION_EXPAND_V, "Expand Vertically", CreateBitmap("expand_selection_v"),
                                  "This is a tooltip for Expand Vertically\ndemonstrating a tooltip")
        selection.AddSimpleButton(ID_SELECTION_EXPAND_H, "Expand Horizontally", CreateBitmap("expand_selection_h"), "")
        selection.AddButton(ID_SELECTION_CONTRACT, "Contract", CreateBitmap("auto_crop_selection"),
                                  CreateBitmap("auto_crop_selection_small"))

        shapes_panel = RB.RibbonPanel(home, wx.ID_ANY, "Shapes", CreateBitmap("circle_small"))
        shapes = RB.RibbonButtonBar(shapes_panel)
        shapes.AddButton(ID_CIRCLE, "Circle", CreateBitmap("circle"), CreateBitmap("circle_small"),
                         help_string="This is a tooltip for the circle button\ndemonstrating another tooltip",
                         kind=RB.RIBBON_BUTTON_TOGGLE)
        shapes.AddSimpleButton(ID_CROSS, "Cross", CreateBitmap("cross"), "")
        shapes.AddHybridButton(ID_TRIANGLE, "Triangle", CreateBitmap("triangle"))
        shapes.AddSimpleButton(ID_SQUARE, "Square", CreateBitmap("square"), "")
        shapes.AddDropdownButton(ID_POLYGON, "Other Polygon", CreateBitmap("hexagon"), "")

        sizer_panel = RB.RibbonPanel(home, wx.ID_ANY, "Panel with Sizer",
                                     wx.NullBitmap, wx.DefaultPosition, wx.DefaultSize,
                                     agwStyle=RB.RIBBON_PANEL_DEFAULT_STYLE)

        strs = ["Item 1 using a box sizer now", "Item 2 using a box sizer now"]
        sizer_panelcombo = wx.ComboBox(sizer_panel, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize,
                                       strs, wx.CB_READONLY)

        sizer_panelcombo2 = wx.ComboBox(sizer_panel, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize,
                                        strs, wx.CB_READONLY)

        sizer_panelcombo.Select(0)
        sizer_panelcombo2.Select(1)
        sizer_panelcombo.SetMinSize(wx.Size(150, -1))
        sizer_panelcombo2.SetMinSize(wx.Size(150, -1))

        # not using wx.WrapSizer(wx.HORIZONTAL) as it reports an incorrect min height
        sizer_panelsizer = wx.BoxSizer(wx.VERTICAL)
        sizer_panelsizer.AddStretchSpacer(1)
        sizer_panelsizer.Add(sizer_panelcombo, 0, wx.ALL|wx.EXPAND, 2)
        sizer_panelsizer.Add(sizer_panelcombo2, 0, wx.ALL|wx.EXPAND, 2)
        sizer_panelsizer.AddStretchSpacer(1)
        sizer_panel.SetSizer(sizer_panelsizer)
        
        label_font = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_LIGHT)
        self._bitmap_creation_dc.SetFont(label_font)

        scheme = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Appearance", CreateBitmap("eye"))
        self._default_primary, self._default_secondary, self._default_tertiary = self._ribbon.GetArtProvider().GetColourScheme(1, 1, 1)

        provider_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Art", wx.NullBitmap, wx.DefaultPosition, wx.DefaultSize,
                                        agwStyle=RB.RIBBON_PANEL_NO_AUTO_MINIMISE)
        provider_bar = RB.RibbonButtonBar(provider_panel, wx.ID_ANY)
        provider_bar.AddSimpleButton(ID_DEFAULT_PROVIDER, "Default Provider",
                                     wx.ArtProvider.GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(32, 32)), "")
        provider_bar.AddSimpleButton(ID_AUI_PROVIDER, "AUI Provider", CreateBitmap("aui_style"), "")
        provider_bar.AddSimpleButton(ID_MSW_PROVIDER, "MSW Provider", CreateBitmap("msw_style"), "")
        
        primary_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Primary Colour", CreateBitmap("colours"))
        self._primary_gallery = self.PopulateColoursPanel(primary_panel, self._default_primary, ID_PRIMARY_COLOUR)

        secondary_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Secondary Colour", CreateBitmap("colours"))
        self._secondary_gallery = self.PopulateColoursPanel(secondary_panel, self._default_secondary, ID_SECONDARY_COLOUR)
    
        dummy_2 = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Empty Page", CreateBitmap("empty"))
        dummy_3 = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Another Page", CreateBitmap("empty"))

        self._ribbon.Realize()

        self._logwindow = wx.TextCtrl(panel, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize,
                                      wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_LEFT | wx.TE_BESTWRAP | wx.BORDER_NONE)

        self._togglePanels = wx.ToggleButton(panel, ID_TOGGLE_PANELS, "&Toggle panels")
        self._togglePanels.SetValue(True)
    
        s = wx.BoxSizer(wx.VERTICAL)

        s.Add(self._ribbon, 0, wx.EXPAND)
        s.Add(self._logwindow, 1, wx.EXPAND)
        s.Add(self._togglePanels, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 10)

        panel.SetSizer(s)
        self.panel = panel

        self.BindEvents([selection, shapes, provider_bar, toolbar_panel])

        self.CenterOnScreen()
        self.Show()
Exemple #11
0
    def OnPaint(self, _):

        width, height = self._handler.size

        if width <= 0 or height <= 0:
            bmp = wx.EmptyBitmapRGBA(1, 1)
            pdc = wx.PaintDC(self)
            gcdc = wx.GCDC(pdc)
            gcdc.DrawBitmap(bmp, 0, 0)

            gcdc.Destroy()
            del gcdc

            self._startup = None
            return

        bmp = wx.EmptyBitmapRGBA(width, height)

        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        gc = wx.GraphicsContext.Create(dc)
        gcdc = wx.GCDC(gc)

        gcdc.SetBrush(wx.Brush(self.GetBackgroundColour()))
        gcdc.SetPen(wx.TRANSPARENT_PEN)

        gcdc.DrawRectangle(0, 0, width, height)

        def draw_circle(x, y, r, _gcdc):
            _gcdc.DrawEllipse(int(round(float(x) - r)),
                              int(round(float(y) - r)), int(round(r * 2.0)),
                              int(round(r * 2.0)))

        gcdc.SetBrush(wx.TRANSPARENT_BRUSH)
        x_center, y_center = self._handler.center

        gcdc.SetPen(wx.TRANSPARENT_PEN)
        radius = self._handler.radius

        if self._handler.shadow:
            # shadow
            stops = wx.GraphicsGradientStops()
            stops.Add(wx.GraphicsGradientStop(wx.TransparentColour, 0.45))
            stops.Add(wx.GraphicsGradientStop(wx.Colour(0, 0, 0, 255), 0.25))

            stops.SetStartColour(wx.Colour(0, 0, 0, 255))
            stops.SetEndColour(wx.TransparentColour)

            gc.SetBrush(
                gc.CreateRadialGradientBrush(x_center + (radius * 0.10),
                                             y_center + (radius * 0.10),
                                             x_center + (radius * 0.30),
                                             y_center + (radius * 0.30),
                                             radius * 2.3, stops))

            draw_circle(x_center + (radius * 0.10), y_center + (radius * 0.10),
                        radius * 2, gcdc)

            # eliminate any shadow under the knob just in case there is a color
            # used in the gradient of the knob that does not have an alpha level of 255

            gc.SetBrush(wx.Brush(self.GetBackgroundColour()))
            draw_circle(x_center, y_center, radius - 2, gcdc)

        if self._handler.glow:
            _ = self._handler.tick_list
            neon_colour = self._handler.neon_colour

            stops = wx.GraphicsGradientStops()

            stops.Add(wx.GraphicsGradientStop(wx.TransparentColour, 0.265))
            stops.Add(
                wx.GraphicsGradientStop(wx.Colour(*neon_colour + (255, )),
                                        0.25))
            stops.Add(wx.GraphicsGradientStop(wx.TransparentColour, 0.248))

            stops.SetStartColour(wx.TransparentColour)
            stops.SetEndColour(wx.TransparentColour)

            gc.SetBrush(
                gc.CreateRadialGradientBrush(x_center, y_center, x_center,
                                             y_center, radius * 4, stops))

            draw_circle(x_center, y_center, radius * 2, gcdc)

        # outside ring of volume knob

        gc.SetBrush(
            gc.CreateRadialGradientBrush(x_center - radius, y_center - radius,
                                         x_center, y_center - radius,
                                         radius * 2,
                                         self._handler.secondary_colour,
                                         self._handler.primary_colour))

        draw_circle(x_center, y_center, radius, gcdc)

        thumb_x, thumb_y = self._handler.thumb_position
        thumb_radius = self._handler.thumb_radius

        # inside of volume knob
        if self._handler.depression:
            center_radius = self._handler.center_radius
            gc.SetBrush(
                gc.CreateRadialGradientBrush(
                    x_center + center_radius, y_center + center_radius,
                    x_center, y_center + center_radius, center_radius * 2,
                    self._handler.secondary_colour,
                    self._handler.primary_colour))

            draw_circle(x_center, y_center, center_radius, gcdc)

        if self._last_degrees is None:
            self._last_degrees = _remap(self._handler.value,
                                        self._handler.min_value,
                                        self._handler.max_value, 135.0, 405.0)

        # handle of the volume knob
        gc.SetBrush(
            gc.CreateRadialGradientBrush(thumb_x + thumb_radius,
                                         thumb_y + thumb_radius, thumb_x,
                                         thumb_y + thumb_radius,
                                         thumb_radius * 2,
                                         self._handler.secondary_colour,
                                         self._handler.primary_colour))

        draw_circle(thumb_x, thumb_y, thumb_radius, gcdc)

        if self._handler.thumb_glow:
            _ = self._handler.tick_list
            neon_colour = self._handler.neon_colour

            stops = wx.GraphicsGradientStops()

            stops.Add(wx.GraphicsGradientStop(wx.TransparentColour, 0.355))
            stops.Add(
                wx.GraphicsGradientStop(wx.Colour(*neon_colour + (255, )),
                                        0.28))
            stops.Add(wx.GraphicsGradientStop(wx.TransparentColour, 0.258))

            stops.SetStartColour(wx.TransparentColour)
            stops.SetEndColour(wx.TransparentColour)

            gc.SetBrush(
                gc.CreateRadialGradientBrush(thumb_x, thumb_y, thumb_x,
                                             thumb_y, thumb_radius * 4, stops))

            draw_circle(thumb_x, thumb_y, thumb_radius * 2, gcdc)

        gcdc.SetBrush(wx.TRANSPARENT_BRUSH)

        # draw the tick marks
        if self._handler.ticks:
            ticks = []
            pens = []
            for _, pen, coords in self._handler.tick_list:
                ticks += [coords]
                pens += [pen]

            gcdc.DrawLineList(ticks, pens)

        dc.SelectObject(wx.EmptyBitmap(1, 1))
        gcdc.Destroy()
        del gcdc

        dc.Destroy()
        del dc

        # create a buffered paint dc to draw the bmp to the client area
        pdc = wx.PaintDC(self)
        gcdc = wx.GCDC(pdc)
        gcdc.DrawBitmap(bmp, 0, 0)

        gcdc.Destroy()
        del gcdc

        if self._startup is True:
            self._startup = None
            t = threading.Thread(target=self._run_startup)
            t.daemon = True
            t.start()
        else:
            self._startup = None
Exemple #12
0
    def MakeSnapshot(self, maxColumns=1337):
        if self.FVsnapshot:
            self.FVsnapshot = None

        tbmp = wx.Bitmap(16, 16)
        tdc = wx.MemoryDC()
        tdc.SelectObject(tbmp)
        tdc.SetFont(self.font)

        columnsWidths = []
        for i in range(len(self.DEFAULT_COLS)):
            columnsWidths.append(0)

        sFit = Fit.getInstance()
        try:
            fit = sFit.getFit(self.activeFitID)
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            pyfalog.critical("Failed to get fit")
            pyfalog.critical(e)
            return

        if fit is None:
            return

        slotMap = {}

        for slot in [e.value for e in FittingSlot]:
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        padding = 2
        isize = 16
        headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2

        maxRowHeight = isize
        rows = 0
        for st in self.mods:
            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break
                name = col.getText(st)

                if not isinstance(name, str):
                    name = ""

                nx, ny = tdc.GetTextExtent(name)
                imgId = col.getImageId(st)
                cw = 0
                if imgId != -1:
                    cw += isize + padding
                if name != "":
                    cw += nx + 4 * padding

                if imgId == -1 and name == "":
                    cw += isize + padding

                maxRowHeight = max(ny, maxRowHeight)
                columnsWidths[i] = max(columnsWidths[i], cw)

            rows += 1

        render = wx.RendererNative.Get()

        # Fix column widths (use biggest between header or items)

        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, str):
                name = ""

            opts = wx.HeaderButtonParams()

            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                opts.m_labelBitmap = wx.Bitmap(isize, isize)

            width = render.DrawHeaderButton(self,
                                            tdc, (0, 0, 16, 16),
                                            sortArrow=wx.HDR_SORT_ICON_NONE,
                                            params=opts)

            columnsWidths[i] = max(columnsWidths[i], width)

        tdc.SelectObject(wx.NullBitmap)

        maxWidth = padding * 2

        for i in range(len(self.DEFAULT_COLS)):
            if i > maxColumns:
                break
            maxWidth += columnsWidths[i]

        mdc = wx.MemoryDC()
        mbmp = wx.Bitmap(maxWidth,
                         maxRowHeight * rows + padding * 4 + headerSize)

        mdc.SelectObject(mbmp)

        mdc.SetBackground(
            wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)))
        mdc.Clear()

        mdc.SetFont(self.font)
        mdc.SetTextForeground(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))

        cx = padding
        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, str):
                name = ""

            opts = wx.HeaderButtonParams()
            opts.m_labelAlignment = wx.ALIGN_LEFT
            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                bmp = col.bitmap
                opts.m_labelBitmap = bmp

            render.DrawHeaderButton(
                self,
                mdc, (cx, padding, columnsWidths[i], headerSize),
                wx.CONTROL_CURRENT,
                sortArrow=wx.HDR_SORT_ICON_NONE,
                params=opts)

            cx += columnsWidths[i]

        brush = wx.Brush(wx.Colour(224, 51, 51))
        pen = wx.Pen(wx.Colour(224, 51, 51))

        mdc.SetPen(pen)
        mdc.SetBrush(brush)

        cy = padding * 2 + headerSize
        for st in self.mods:
            cx = padding

            if slotMap[st.slot]:
                mdc.DrawRectangle(cx, cy, maxWidth - cx, maxRowHeight)

            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break

                name = col.getText(st)
                if not isinstance(name, str):
                    name = ""

                imgId = col.getImageId(st)
                tcx = cx

                if imgId != -1:
                    self.imageList.Draw(imgId, mdc, cx, cy,
                                        wx.IMAGELIST_DRAW_TRANSPARENT, False)
                    tcx += isize + padding

                if name != "":
                    nx, ny = mdc.GetTextExtent(name)
                    rect = wx.Rect()
                    rect.top = cy
                    rect.left = cx + 2 * padding
                    rect.width = nx
                    rect.height = maxRowHeight + padding
                    mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL)
                    tcx += nx + padding

                cx += columnsWidths[i]

            cy += maxRowHeight

        mdc.SelectObject(wx.NullBitmap)

        self.FVsnapshot = mbmp
Exemple #13
0
 def __init__(self, *args, **kwargs):
     DCContextManager.__init__(self, wx.MemoryDC(*args, **kwargs))
Exemple #14
0
    def OnSaveAs(self, event):
        ### XXX TODO: Save overlays
        ### XXX TODO: Fix bug where multi-asic images are slightly cropped due to tranformation error'

        try:
            import PIL.Image as Image
        except ImportError:
            import Image

        dialog = wx.FileDialog(
            self,
            defaultDir='',
            message="Save PNG or PDF file",
            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
            wildcard="PNG file (*.png)|*.png|PDF file (*.pdf)|*.pdf")
        if dialog.ShowModal() != wx.ID_OK:
            return

        file_name = dialog.GetPath()
        if file_name == '':
            return

        self.update_statusbar("Writing " + file_name + "...")
        if dialog.GetFilterIndex() == 0:
            from six.moves import cStringIO as StringIO

            # XXX Copied from tile_generation.py; all its disclaimers
            # apply.
            raw_img = self.pyslip.tiles.raw_image
            detector = raw_img.get_detector()
            data = raw_img.get_raw_data()
            if not isinstance(data, tuple):  # XXX should not need this test
                data = (data, )
            if len(detector) > 1:
                from .tile_generation import _get_flex_image_multipanel
                flex_img = _get_flex_image_multipanel(
                    brightness=self.settings.brightness / 100,
                    panels=detector,
                    raw_data=data,
                    beam=raw_img.get_beam())
            else:
                from .tile_generation import _get_flex_image
                flex_img = _get_flex_image(
                    brightness=self.settings.brightness / 100,
                    data=data[0],
                    saturation=detector[0].get_trusted_range()[1],
                    vendortype=raw_img.get_vendortype())

            if flex_img.supports_rotated_tiles_antialiasing_recommended:
                currentZoom = self.pyslip.level
                self.pyslip.tiles.UseLevel(0)  #1:1 zoom level

                try:
                    x, y, width, height = self._img._raw.bounding_box_mm()
                    x1, y1 = self._img._raw.detector_coords_as_image_coords(
                        x, y)
                    x2, y2 = self._img._raw.detector_coords_as_image_coords(
                        x + width, y + height)
                except AttributeError:
                    x1 = min([p.get_pixel_lab_coord(c)[0]/p.get_pixel_size()[0] \
                              for p in detector \
                              for c in [(0,0),(0,p.get_image_size()[1]),(p.get_image_size()[0],0),(p.get_image_size()[0],p.get_image_size()[1])]])
                    y1 = min([p.get_pixel_lab_coord(c)[1]/p.get_pixel_size()[1] \
                              for p in detector \
                              for c in [(0,0),(0,p.get_image_size()[1]),(p.get_image_size()[0],0),(p.get_image_size()[0],p.get_image_size()[1])]])
                    x2 = max([p.get_pixel_lab_coord(c)[0]/p.get_pixel_size()[0] \
                              for p in detector \
                              for c in [(0,0),(0,p.get_image_size()[1]),(p.get_image_size()[0],0),(p.get_image_size()[0],p.get_image_size()[1])]])
                    y2 = max([p.get_pixel_lab_coord(c)[1]/p.get_pixel_size()[1] \
                              for p in detector \
                              for c in [(0,0),(0,p.get_image_size()[1]),(p.get_image_size()[0],0),(p.get_image_size()[0],p.get_image_size()[1])]])

                # Map > View - determine layout in X direction
                x_offset = x1
                import math
                start_x_tile = int(
                    math.floor(x_offset / self.pyslip.tile_size_x))
                stop_x_tile = ((x2 + self.pyslip.tile_size_x - 1) /
                               self.pyslip.tile_size_x)
                stop_x_tile = int(stop_x_tile)
                col_list = range(start_x_tile, stop_x_tile)
                x_pix = start_x_tile * self.pyslip.tile_size_y - x_offset

                y_offset = y1
                start_y_tile = int(
                    math.floor(y_offset / self.pyslip.tile_size_y))
                stop_y_tile = ((y2 + self.pyslip.tile_size_y - 1) /
                               self.pyslip.tile_size_y)
                stop_y_tile = int(stop_y_tile)
                row_list = range(start_y_tile, stop_y_tile)
                y_pix_start = start_y_tile * self.pyslip.tile_size_y - y_offset

                bitmap = wx.EmptyBitmap(x2 - x1, y2 - y1)
                dc = wx.MemoryDC()
                dc.SelectObject(bitmap)

                # start pasting tiles
                for x in col_list:
                    y_pix = y_pix_start
                    for y in row_list:
                        dc.DrawBitmap(self.pyslip.tiles.GetTile(x, y), x_pix,
                                      y_pix, False)
                        y_pix += self.pyslip.tile_size_y
                    x_pix += self.pyslip.tile_size_x

                dc.SelectObject(wx.NullBitmap)

                wximg = wx.ImageFromBitmap(bitmap)
                imageout = Image.new('RGB',
                                     (wximg.GetWidth(), wximg.GetHeight()))
                imageout.frombytes(wximg.GetData())

                self.pyslip.tiles.UseLevel(currentZoom)

            else:  # write the image out at full resolution
                flex_img.setWindow(0.0, 0.0, 1)
                flex_img.spot_convention(0)
                flex_img.adjust(color_scheme=self.settings.color_scheme)
                flex_img.prep_string()
                data_string = flex_img.export_string
                try:
                    imageout = Image.fromstring(
                        "RGB", (flex_img.ex_size2(), flex_img.ex_size1()),
                        data_string)
                except NotImplementedError:
                    imageout = Image.frombytes(
                        "RGB", (flex_img.ex_size2(), flex_img.ex_size1()),
                        data_string)

            out = StringIO()
            imageout.save(out, "PNG")
            open(file_name, "wb").write(out.getvalue())

        elif dialog.GetFilterIndex() == 1:
            from reportlab.lib.units import inch
            from reportlab.pdfgen import canvas

            # Dots per inch in PDF output, and fudge factor to not make
            # fine features impossibly small.  XXX The fudge factor should
            # go.
            DPI = 72
            LINE_WIDTH_FACTOR = 0.6

            # XXX Copied from tile_generation.py; all its disclaimers
            # apply.
            raw_img = self.pyslip.tiles.raw_image
            detector = raw_img.get_detector()
            data = raw_img.get_raw_data()
            if not isinstance(data, tuple):  # XXX should not need this test
                data = (data, )
            if len(detector) > 1:
                from .tile_generation import _get_flex_image_multipanel
                flex_img = _get_flex_image_multipanel(
                    brightness=self.settings.brightness / 100,
                    panels=detector,
                    raw_data=data,
                    beam=raw_img.get_beam())
            else:
                from .tile_generation import _get_flex_image
                flex_img = _get_flex_image(
                    brightness=self.settings.brightness / 100,
                    data=data[0],
                    saturation=detector[0].get_trusted_range()[1],
                    vendortype=raw_img.get_vendortype())

            flex_img.setWindow(0, 0, 1)
            flex_img.adjust(color_scheme=self.settings.color_scheme)
            flex_img.prep_string()

            # XXX Order of size1/size2 correct?
            pdf_size = (flex_img.size2() * inch / DPI,
                        flex_img.size1() * inch / DPI)
            pdf_canvas = canvas.Canvas(filename=file_name, pagesize=pdf_size)
            try:
                pil_img = Image.fromstring(
                    'RGB', (flex_img.size2(), flex_img.size1()),
                    flex_img.export_string)
            except NotImplementedError:
                pil_img = Image.frombytes('RGB',
                                          (flex_img.size2(), flex_img.size1()),
                                          flex_img.export_string)

            pdf_canvas.drawInlineImage(pil_img,
                                       0,
                                       0,
                                       width=pdf_size[0],
                                       height=pdf_size[1])

            for layer_id in self.pyslip.layer_z_order:
                layer = self.pyslip.layer_mapping[layer_id]

                # XXX This would probably be more elegant if these were
                # functions in some layer class.  Note repeated roundabout
                # way (via a wx.Pen object) to extract RGB values from the
                # colour parameter.
                if layer.type == self.pyslip.TypeEllipse:
                    from math import atan2, degrees, hypot
                    from scitbx.matrix import col

                    for (p, place, width, colour, closed, filled, fillcolour,
                         x_off, y_off, pdata) in layer.data:
                        if layer.map_rel:
                            pp = []
                            for i in range(len(p)):
                                fs = self.pyslip.tiles.map_relative_to_picture_fast_slow(
                                    p[i][0], p[i][1])
                                pp.append((fs[0] * inch / DPI,
                                           pdf_size[1] - fs[1] * inch / DPI))
                            ellipse_center = col(pp[0])
                            major = col(pp[1]) - ellipse_center
                            minor = col(pp[2]) - ellipse_center
                        else:
                            raise NotImplementedError(
                                "PDF output in view-relative coordinates not implemented"
                            )

                        pen = wx.Pen(colour)
                        pdf_canvas.setLineWidth(width * LINE_WIDTH_FACTOR)
                        pdf_canvas.setStrokeColorRGB(pen.Colour.Red() / 255,
                                                     pen.Colour.Green() / 255,
                                                     pen.Colour.Blue() / 255)

                        angle = atan2(major.elems[1], major.elems[0])
                        r_major = hypot(major.elems[0], major.elems[1])
                        r_minor = hypot(minor.elems[0], minor.elems[1])

                        pdf_canvas.saveState()
                        pdf_canvas.translate(ellipse_center.elems[0],
                                             ellipse_center.elems[1])

                        pdf_canvas.rotate(degrees(angle))
                        pdf_canvas.ellipse(-r_major, -r_minor, r_major,
                                           r_minor)
                        pdf_canvas.restoreState()

                elif layer.type == self.pyslip.TypeImage:
                    raise NotImplementedError(
                        "PDF output of image layers not implemented")

                elif layer.type == self.pyslip.TypePoint:
                    for (lon, lat, place, radius, colour, x_off, y_off,
                         pdata) in layer.data:
                        if layer.map_rel:
                            fs = self.pyslip.tiles.map_relative_to_picture_fast_slow(
                                lon, lat)
                        else:
                            raise NotImplementedError(
                                "PDF output in view-relative coordinates not implemented"
                            )

                        pt = (fs[0] * inch / DPI,
                              pdf_size[1] - fs[1] * inch / DPI)
                        pen = wx.Pen(colour)
                        pdf_canvas.setLineWidth(radius)
                        pdf_canvas.setStrokeColorRGB(pen.Colour.Red() / 255,
                                                     pen.Colour.Green() / 255,
                                                     pen.Colour.Blue() / 255)
                        pdf_canvas.circle(pt[0], pt[1],
                                          0.5 * radius * inch / DPI)

                elif layer.type == self.pyslip.TypePolygon:
                    for (p, place, width, colour, closed, filled, fillcolour,
                         x_off, y_off, pdata) in layer.data:
                        path = pdf_canvas.beginPath()
                        for i in range(len(p)):
                            if layer.map_rel:
                                fs = self.pyslip.tiles.map_relative_to_picture_fast_slow(
                                    p[i][0], p[i][1])
                            else:
                                raise NotImplementedError(
                                    "PDF output in view-relative coordinates not implemented"
                                )

                            pt = (fs[0] * inch / DPI,
                                  pdf_size[1] - fs[1] * inch / DPI)
                            if i == 0:
                                path.moveTo(pt[0], pt[1])
                            else:
                                path.lineTo(pt[0], pt[1])

                        if closed:
                            path.close()

                        pen = wx.Pen(colour)
                        pdf_canvas.setFillColorRGB(pen.Colour.Red() / 255,
                                                   pen.Colour.Green() / 255,
                                                   pen.Colour.Blue() / 255)
                        pdf_canvas.setLineWidth(width * LINE_WIDTH_FACTOR)
                        pdf_canvas.setStrokeColorRGB(pen.Colour.Red() / 255,
                                                     pen.Colour.Green() / 255,
                                                     pen.Colour.Blue() / 255)
                        pdf_canvas.drawPath(path, fill=filled)

                elif layer.type == self.pyslip.TypeText:
                    for (lon, lat, tdata, placement, radius, colour,
                         textcolour, fontname, fontsize, offset_x, offset_y,
                         data) in layer.data:
                        if placement != 'cc':
                            print(
                                Warning(
                                    "Only centered placement available when drawing text on pdf"
                                ))
                        if layer.map_rel:
                            fs = self.pyslip.tiles.map_relative_to_picture_fast_slow(
                                lon, lat)
                        else:
                            raise NotImplementedError(
                                "PDF output in view-relative coordinates not implemented"
                            )
                        from reportlab.pdfbase.pdfmetrics import stringWidth
                        scale = 5  # XXX this scaleup by 5 is arbitrary!
                        try:
                            w = stringWidth(tdata, fontname, fontsize * scale)
                        except KeyError:
                            fontname = "Helvetica"
                            w = stringWidth(tdata, fontname, fontsize * scale)
                        if fs[0] - (
                                w / 2
                        ) < 0:  # handle text falling off the left side
                            txt = pdf_canvas.beginText(x=0, y=fs[1])
                        else:
                            txt = pdf_canvas.beginText(x=fs[0] - (w / 2),
                                                       y=fs[1])
                        txt.setFont(fontname, fontsize * scale)
                        txt.setFillColor(textcolour)
                        txt.setStrokeColor(textcolour)
                        txt.textLine(tdata)
                        pdf_canvas.drawText(txt)

            pdf_canvas.save()

        self.update_statusbar("Writing " + file_name + "..." + " Done.")
Exemple #15
0
    def OnPrintPage(self, page):
        fileSuffix = {
            wx.BITMAP_TYPE_BMP: 'bmp',
            wx.BITMAP_TYPE_JPEG: 'jpg',
            wx.BITMAP_TYPE_PCX: 'pcx',
            wx.BITMAP_TYPE_PNG: 'png',
            wx.BITMAP_TYPE_PNM: 'pnm',
            wx.BITMAP_TYPE_XPM: 'xpm',
            wx.BITMAP_TYPE_ICO: 'ico',
            wx.BITMAP_TYPE_CUR: 'cur',
        }
        try:
            fileSuffix[wx.BITMAP_TYPE_TIFF] = 'tiff'
        except:
            pass

        fileFormat = wx.BITMAP_TYPE_BMP

        fileExt = '.' + fileSuffix[fileFormat]

        exportGrid = self.prepareGrid(page)

        pxPerInch = 148
        if self.orientation == wx.LANDSCAPE:
            bitmap = wx.Bitmap(pxPerInch * 11, int(pxPerInch * 8.5))
        else:
            bitmap = wx.Bitmap(int(pxPerInch * 8.5), pxPerInch * 11)
        dc = wx.MemoryDC()
        dc.SelectObject(bitmap)

        dc.SetBrush(wx.WHITE_BRUSH)
        dc.Clear()
        dc.SetBrush(wx.BLACK_BRUSH)
        exportGrid.drawToFitDC(*([dc] + self.pageInfo[page][1:-1]))
        dc.SelectObject(wx.NullBitmap)
        dc = None
        image = bitmap.ConvertToImage()
        bitmap = None

        category = self.pageInfo[page][0]
        pageNumber = self.pageInfo[page][3]
        pageTotal = self.pageInfo[page][4]

        if pageTotal != 1:
            fname = u'{categoryName}-({pageNumber})-{fileBase}{fileExt}'.format(
                fileBase=self.fileBase,
                categoryName=category.fullname
                if category != 'Primes' else 'Primes',
                pageNumber=pageNumber,
                fileExt=fileExt,
            )
        else:
            fname = u'{categoryName}-{fileBase}{fileExt}'.format(
                fileBase=self.fileBase,
                categoryName=category.fullname
                if category != 'Primes' else 'Primes',
                fileExt=fileExt,
            )

        fname = Utils.RemoveDisallowedFilenameChars(fname).replace(' ', '-')

        if self.dir and not os.path.isdir(self.dir):
            os.mkdir(self.dir)

        fname = os.path.join(self.dir, fname)
        fnamePNG = os.path.splitext(fname)[0] + '.png'

        self.lastFName = fnamePNG

        # First same the file as a bitmap.
        image.SaveFile(fname, fileFormat)

        # Then convert the saved file to a png.
        # For some reason Windows requires this.
        with open(fname, 'rb') as f:
            image = wx.Image(f, fileFormat)
        image.SaveFile(fnamePNG, wx.BITMAP_TYPE_PNG)

        # Cleanup the old file.
        os.remove(fname)
        return True
Exemple #16
0
    def run(self):
        self._is_running = True
        # For identifying "chat:xxx" and "from:xxx" keywords
        query_parser = searchparser.SearchQueryParser()
        result = None
        while self._is_running:
            try:
                search = self._queue.get()
                if not search:
                    continue  # continue while self._is_running

                is_text_output = ("text" == search.get("output"))
                wrap_html = None  # MessageParser wrap function, for HTML output
                if is_text_output:
                    TEMPLATES = {
                        "chat": templates.SEARCH_ROW_CHAT_TXT,
                        "contact": templates.SEARCH_ROW_CONTACT_TXT,
                        "message": templates.SEARCH_ROW_MESSAGE_TXT,
                        "table": templates.SEARCH_ROW_TABLE_HEADER_TXT,
                        "row": templates.SEARCH_ROW_TABLE_TXT,
                    }
                    wrap_b = lambda x: "**%s**" % x.group(0)
                    output = {"format": "text"}
                else:
                    TEMPLATES = {
                        "chat": templates.SEARCH_ROW_CHAT_HTML,
                        "contact": templates.SEARCH_ROW_CONTACT_HTML,
                        "message": templates.SEARCH_ROW_MESSAGE_HTML,
                        "table": templates.SEARCH_ROW_TABLE_HEADER_HTML,
                        "row": templates.SEARCH_ROW_TABLE_HTML,
                    }
                    wrap_b = lambda x: "<b>%s</b>" % x.group(0)
                    output = {"format": "html"}
                    width = search.get("width", -1)
                    if width > 0:
                        dc = wx.MemoryDC()
                        dc.SetFont(
                            wx.Font(8,
                                    wx.FONTFAMILY_SWISS,
                                    wx.FONTSTYLE_NORMAL,
                                    wx.FONTWEIGHT_NORMAL,
                                    face=conf.HistoryFontName))
                        wrap_html = lambda x: wx.lib.wordwrap.wordwrap(
                            x, width, dc)
                        output["wrap"] = True
                main.log('Searching "%(text)s" in %(table)s (%(db)s).' %
                         search)
                self._stop_work = False
                self._drop_results = False

                parser = skypedata.MessageParser(search["db"],
                                                 wrapper=wrap_html)
                # {"output": text with results, "map": link data map}
                # map data: {"contact:666": {"contact": {contact data}}, }
                result_type, result_count, count = None, 0, 0
                result = {
                    "output": "",
                    "map": {},
                    "search": search,
                    "count": 0
                }
                sql, params, match_words = query_parser.Parse(search["text"])

                # Turn wildcard characters * into regex-compatible .*
                match_words_re = [
                    ".*".join(map(re.escape, w.split("*")))
                    for w in match_words
                ]
                patt = "(%s)" % "|".join(match_words_re)
                # For replacing matching words with <b>words</b>
                pattern_replace = re.compile(patt, re.IGNORECASE)

                # Find chats with a matching title or matching participants
                chats = []
                if search["table"] in ["conversations", "messages"]:
                    chats = search["db"].get_conversations()
                    chats.sort(key=lambda x: x["title"])
                    chat_map = {}  # {chat id: {chat data}}
                    template_chat = step.Template(TEMPLATES["chat"])
                for chat in chats:
                    chat_map[chat["id"]] = chat
                    if "conversations" == search["table"] and match_words:
                        title_matches = False
                        matching_authors = []
                        if self.match_all(chat["title"], match_words):
                            title_matches = True
                        for participant in chat["participants"]:
                            contact = participant["contact"]
                            if contact:
                                for n in filter(None, [
                                        contact["fullname"],
                                        contact["displayname"],
                                        contact["identity"]
                                ]):
                                    if self.match_all(n, match_words) \
                                    and contact not in matching_authors:
                                        matching_authors.append(contact)

                        if title_matches or matching_authors:
                            count += 1
                            result_count += 1
                            result["output"] += template_chat.expand(locals())
                            key = "chat:%s" % chat["id"]
                            result["map"][key] = {"chat": chat["id"]}
                            if not count % conf.SearchResultsChunk \
                            and not self._drop_results:
                                result["count"] = result_count
                                self.postback(result)
                                result = {
                                    "output": "",
                                    "map": {},
                                    "search": search,
                                    "count": 0
                                }
                    if self._stop_work:
                        break  # break for chat in chats
                if result["output"] and not self._drop_results:
                    result["count"] = result_count
                    self.postback(result)
                    result = {
                        "output": "",
                        "map": {},
                        "search": search,
                        "count": 0
                    }

                # Find contacts with a matching name
                if not self._stop_work and "contacts" == search["table"] \
                and match_words:
                    count = 0
                    contacts = search["db"].get_contacts()
                    # Possibly more: country (ISO code, need map), birthday
                    # (base has YYYYMMDD in integer field).
                    match_fields = [
                        "displayname",
                        "skypename",
                        "province",
                        "city",
                        "pstnnumber",
                        "phone_home",
                        "phone_office",
                        "phone_mobile",
                        "homepage",
                        "emails",
                        "about",
                        "mood_text",
                    ]
                    template_contact = step.Template(TEMPLATES["contact"])
                    for contact in contacts:
                        match = False
                        fields_filled = {}
                        for field in match_fields:
                            if contact[field]:
                                val = contact[field]
                                if self.match_all(val, match_words):
                                    match = True
                                    val = pattern_replace.sub(wrap_b, val)
                                fields_filled[field] = val
                        if match:
                            count += 1
                            result_count += 1
                            result["output"] += template_contact.expand(
                                locals())
                            if not (self._drop_results
                                    or count % conf.SearchResultsChunk):
                                result["count"] = result_count
                                self.postback(result)
                                result = {
                                    "output": "",
                                    "map": {},
                                    "search": search,
                                    "count": 0
                                }
                        if self._stop_work:
                            break  # break for contact in contacts
                if result["output"] and not self._drop_results:
                    result["count"] = result_count
                    self.postback(result)
                    result = {
                        "output": "",
                        "map": {},
                        "search": search,
                        "count": 0
                    }

                # Find messages with a matching body
                if not self._stop_work and "messages" == search["table"]:
                    template_message = step.Template(TEMPLATES["message"])
                    count, result_type = 0, "messages"
                    chat_messages = {}  # {chat id: [message, ]}
                    chat_order = []  # [chat id, ]
                    messages = search["db"].get_messages(
                        additional_sql=sql,
                        additional_params=params,
                        ascending=False,
                        use_cache=False)
                    for m in messages:
                        chat = chat_map.get(m["convo_id"])
                        body = parser.parse(
                            m, pattern_replace if match_words else None,
                            output)
                        count += 1
                        result_count += 1
                        result["output"] += template_message.expand(locals())
                        key = "message:%s" % m["id"]
                        result["map"][key] = {
                            "chat": chat["id"],
                            "message": m["id"]
                        }
                        if is_text_output or (
                                not self._drop_results
                                and not count % conf.SearchResultsChunk):
                            result["count"] = result_count
                            self.postback(result)
                            result = {
                                "output": "",
                                "map": {},
                                "search": search,
                                "count": 0
                            }
                        if self._stop_work or (not is_text_output and count >=
                                               conf.MaxSearchMessages):
                            break  # break for m in messages

                infotext = search["table"]
                if not self._stop_work and "all tables" == search["table"]:
                    infotext, result_type = "", "table row"
                    # Search over all fields of all tables.
                    template_table = step.Template(TEMPLATES["table"])
                    template_row = step.Template(TEMPLATES["row"])
                    for table in search["db"].get_tables():
                        table["columns"] = search["db"].get_table_columns(
                            table["name"])
                        sql, params, words = query_parser.Parse(
                            search["text"], table)
                        if not sql:
                            continue  # continue for table in search["db"]..
                        infotext += (", " if infotext else "") + table["name"]
                        rows = search["db"].execute(sql, params)
                        row = rows.fetchone()
                        if not row:
                            continue  # continue for table in search["db"]..
                        result["output"] = template_table.expand(locals())
                        count = 0
                        while row:
                            count += 1
                            result_count += 1
                            result["output"] += template_row.expand(locals())
                            key = "table:%s:%s" % (table["name"], count)
                            result["map"][key] = {
                                "table": table["name"],
                                "row": row
                            }
                            if not count % conf.SearchResultsChunk \
                            and not self._drop_results:
                                result["count"] = result_count
                                self.postback(result)
                                result = {
                                    "output": "",
                                    "map": {},
                                    "search": search,
                                    "count": 0
                                }
                            if self._stop_work or (not is_text_output
                                                   and result_count >=
                                                   conf.MaxSearchTableRows):
                                break  # break while row
                            row = rows.fetchone()
                        if not self._drop_results:
                            if not is_text_output:
                                result["output"] += "</table>"
                            result["count"] = result_count
                            self.postback(result)
                            result = {
                                "output": "",
                                "map": {},
                                "search": search,
                                "count": 0
                            }
                        infotext += " (%s)" % util.plural("result", count)
                        if self._stop_work or (
                                not is_text_output
                                and result_count >= conf.MaxSearchTableRows):
                            break  # break for table in search["db"]..
                    single_table = ("," not in infotext)
                    infotext = "table%s: %s" % \
                               ("" if single_table else "s", infotext)
                    if not single_table:
                        infotext += "; %s in total" % \
                                    util.plural("result", result_count)
                final_text = "No matches found."
                if self._drop_results:
                    result["output"] = ""
                if result_count:
                    final_text = "Finished searching %s." % infotext

                if self._stop_work:
                    final_text += " Stopped by user."
                elif "messages" == result_type and not is_text_output \
                and count >= conf.MaxSearchMessages:
                    final_text += " Stopped at %s limit %s." % \
                                  (result_type, conf.MaxSearchMessages)
                elif "table row" == result_type and not is_text_output \
                and count >= conf.MaxSearchTableRows:
                    final_text += " Stopped at %s limit %s." % \
                                  (result_type, conf.MaxSearchTableRows)

                result[
                    "output"] += "</table><br /><br />%s</font>" % final_text
                if is_text_output: result["output"] = ""
                result["done"] = True
                result["count"] = result_count
                self.postback(result)
                main.log("Search found %(count)s results." % result)
            except Exception as e:
                if not result:
                    result = {}
                result["done"], result["error"] = True, traceback.format_exc()
                result["error_short"] = repr(e)
                self.postback(result)
Exemple #17
0
    def __init__(self, parent, ID):
        wx.ScrolledWindow.__init__(self, parent, ID)
        self.shapes = []
        self.dragImage = None
        self.dragShape = None
        self.hiliteShape = None

        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
        self.bg_bmp = images.getBackgroundBitmap()

        # Make a shape from an image and mask.  This one will demo
        # dragging outside the window
        bmp = images.getTestStarBitmap()
        ##bmp = wx.Bitmap('bitmaps/toucan.png')
        shape = DragShape(bmp)
        shape.pos = (5, 5)
        shape.fullscreen = True
        self.shapes.append(shape)

        # Make a shape from some text
        text = "Some Text"
        bg_colour = wx.Colour(57, 115, 57)  # matches the bg image
        font = wx.Font(15, wx.ROMAN, wx.NORMAL, wx.BOLD)
        textExtent = self.GetFullTextExtent(text, font)

        # create a bitmap the same size as our text
        bmp = wx.EmptyBitmap(textExtent[0], textExtent[1])

        # 'draw' the text onto the bitmap
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetBackground(wx.Brush(bg_colour, wx.SOLID))
        dc.Clear()
        dc.SetTextForeground(wx.RED)
        dc.SetFont(font)
        dc.DrawText(text, 0, 0)
        dc.SelectObject(wx.NullBitmap)
        mask = wx.Mask(bmp, bg_colour)
        bmp.SetMask(mask)
        shape = DragShape(bmp)
        shape.pos = (5, 100)
        shape.text = "Some dragging text"
        self.shapes.append(shape)


        # Make some shapes from some playing card images.
        x = 200

        for card in ['_01c_', '_12h_', '_13d_', '_10s_']:
            bmpFunc = getattr(images, "get%sBitmap" % card)
            bmp = bmpFunc()
            shape = DragShape(bmp)
            shape.pos = (x, 5)
            self.shapes.append(shape)
            x = x + 80


        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
Exemple #18
0
 def test_gcCreate2(self):
     bmp = wx.Bitmap(100, 100)
     mdc = wx.MemoryDC(bmp)
     gc = wx.GraphicsContext.Create(mdc)
     self.assertTrue(gc.IsOk())
Exemple #19
0
    def genImage(self):
        x1 = str(self.x1).rjust(4)
        y1 = str(self.y1).rjust(4)
        x2 = str(self.x2).rjust(4)
        y2 = str(self.y2).rjust(4)

        screen = wx.ScreenDC()
        size = screen.GetSize()
        bmp = wx.EmptyBitmap(size[0], size[1])
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
        del mem
        bmp.SaveFile(self.filepath, wx.BITMAP_TYPE_PNG)

        if (self.comboColor.GetValue() == 'RGB'):
            foo = Image.open(self.filepath)
        else:
            foo = Image.open(self.filepath).convert('LA')

        x, y = foo.size

        if (self.comboQuality.GetValue() == '100%'):
            x_percent = 0
            y_percent = 0
        elif (self.comboQuality.GetValue() == '75%'):
            x_percent = x * 0.25
            y_percent = y * 0.25
        elif (self.comboQuality.GetValue() == '50%'):
            x_percent = x * 0.50
            y_percent = y * 0.50
        elif (self.comboQuality.GetValue() == '25%'):
            x_percent = x * 0.75
            y_percent = y * 0.75

        x3, y3 = math.floor(x - x_percent), math.floor(y - y_percent)
        foo = foo.resize((x3, y3), Image.NEAREST)

        img_quality = 0

        left = int(x1)
        top = int(y1)
        right = int(x3)
        bottom = int(y3)

        if left > right:
            aux = left
            left = right
            right = aux

        if top > bottom:
            aux = top
            top = bottom
            bottom = aux

        foo = foo.crop((left, top, right, bottom))
        output = BytesIO()
        foo.save(self.filepath, optimize=True, quality=img_quality)
        foo.convert("RGB").save(output, "BMP")
        data = output.getvalue()[14:]
        output.close()

        self.copyToClipboard(data)
        '''os._exit(0)
 def __init__(self, parent, font_size):
     super(Frame_Gerenate, self).__init__(parent)
     self.dc = wx.MemoryDC()
     self.parent = parent
     self.parent.Disable()
     self.bmp = wx.Bitmap(RENDERSIZE, RENDERSIZE, depth=1)
Exemple #21
0
    def __init__(self, parent, id_, title,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX):
        """Creates a standalone window that is used for downloading
        updates for the editor.
        @param parent: Parent Window of the dialog
        @param title: Title of dialog

        """
        wx.Frame.__init__(self, parent, id_, title, style=style)
        util.SetWindowIcon(self)

        #---- Attributes/Objects ----#
        self.LOG = wx.GetApp().GetLog()
        panel = wx.Panel(self)
        self._progress = UpdateProgress(panel, self.ID_PROGRESS_BAR)
        fname = self._progress.GetCurrFileName()
        floc = self._progress.GetDownloadLocation()
        dl_file = wx.StaticText(panel, label=_("Downloading: %s") % fname)
        dl_loc = wx.StaticText(panel, wx.ID_ANY,
                               _("Downloading To: %s") % floc)
        self._cancel_bt = wx.Button(panel, wx.ID_CANCEL, _("Cancel"))
        self._timer = wx.Timer(self, id=self.ID_TIMER)
        self._proghist = list()

        #---- Layout ----#
        self.CreateStatusBar(2)
        self._sizer = wx.GridBagSizer()
        bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_WEB), wx.ART_TOOLBAR)
        mdc = wx.MemoryDC(bmp)
        tmp_bmp = wx.Image(ed_glob.CONFIG['SYSPIX_DIR'] + u"editra.png",
                           wx.BITMAP_TYPE_PNG)
        tmp_bmp.Rescale(20, 20, wx.IMAGE_QUALITY_HIGH)
        mdc.DrawBitmap(tmp_bmp.ConvertToBitmap(), 11, 11)
        mdc.SelectObject(wx.NullBitmap)
        bmp = wx.StaticBitmap(panel, wx.ID_ANY, bmp)
        self._sizer.AddMany([(bmp, (1, 1), (3, 2)),
                             (dl_file, (1, 4), (1, 4)),
                             (dl_loc, (2, 4), (1, 4)),
                             ((15, 15), (3, 5), (1, 1))])
        self._sizer.Add(self._progress, (4, 1), (1, 10), wx.EXPAND)

        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.AddStretchSpacer()
        bsizer.Add(self._cancel_bt, 0, wx.ALIGN_CENTER_HORIZONTAL)
        bsizer.AddStretchSpacer()

        self._sizer.Add(bsizer, (6, 1), (1, 10), wx.EXPAND)
        self._sizer.Add((5, 5), (7, 1))
        self._sizer.Add((5, 5), (7, 11))
        panel.SetSizer(self._sizer)
        mwsz = wx.BoxSizer(wx.HORIZONTAL)
        mwsz.Add(panel, 1, wx.EXPAND)
        self.SetSizer(mwsz)
        self.SetInitialSize()

        self.SetStatusWidths([-1, 100])
        self.SetStatusText(_("Downloading") + u"...", self.SB_INFO)

        #---- Bind Events ----#
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_TIMER, self.OnUpdate, id=self.ID_TIMER)
Exemple #22
0
    def Start(self):
        '''Initialize CPA
        '''
        '''List of tables created by the user during this session'''
        self.user_tables = []

        # splashscreen
        splashimage = cpa.icons.cpa_splash.ConvertToBitmap()
        # If the splash image has alpha, it shows up transparently on
        # windows, so we blend it into a white background.
        splashbitmap = wx.EmptyBitmapRGBA(splashimage.GetWidth(),
                                          splashimage.GetHeight(), 255, 255,
                                          255, 255)
        dc = wx.MemoryDC()
        dc.SelectObject(splashbitmap)
        dc.DrawBitmap(splashimage, 0, 0)
        dc.Destroy()  # necessary to avoid a crash in splashscreen
        splash = wx.SplashScreen(
            splashbitmap, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 2000,
            None, -1)
        self.splash = splash

        p = Properties.getInstance()
        if not p.is_initialized():
            from cpa.guiutils import show_load_dialog
            splash.Destroy()
            if not show_load_dialog():
                splash.Destroy()
                example_link_address = 'cellprofiler.org'
                dlg = wx.MessageDialog(
                    None,
                    'CellProfiler Analyst requires a properties file. Download an example at %s'
                    % (example_link_address), 'Properties file required',
                    wx.OK)
                response = dlg.ShowModal()
                logging.error(
                    'CellProfiler Analyst requires a properties file. Exiting.'
                )
                return False

        self.frame = MainGUI(p, None, size=(1000, -1))

        db = DBConnect.getInstance()
        # Black magic: Bus errors occur on Mac OS X if we wait until
        # the JVM or the wx event look has started to connect. But it
        # has to be done after we have read the properties file. So we
        # do it here.
        db.connect()
        db.register_gui_parent(self.frame)

        # The JVM has to be started after db.connect(), otherwise bus errors
        # occur on Mac OS X.
        javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)

        # removes the log4j warnings
        javabridge.attach()

        # TODO: check for updates
        try:
            if __version__ != -1:
                import cpa.util.check_for_updates as cfu
                cfu.check_for_updates(
                    'http://cellprofiler.org/updates/CPA.html',
                    max(__version__, cpa.cpaprefs.get_skip_version()),
                    new_version_cb,
                    user_agent='CPAnalyst/%s' % (__version__))
        except ImportError:
            logging.warn(
                "CPA was unable to check for updates. Could not import cpa.util.check_for_updates."
            )

        self.frame.Show()  # Show frame
        return True
    def DrawView(self):
        """
        Redraw elements.
        Method is used by EVT_PAINT handler.
        """
        if os.name == 'nt':
            width, height = self.GraphicsWindow.GetVirtualSize()
            bitmap = wx.EmptyBitmap(width, height)
            dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap)
            dc.Clear()
            dc.BeginDrawing()
            if self.DraggingAxesPanel is not None:
                destBBox = self.DraggingAxesBoundingBox
                srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox()

                srcBmp = _convert_agg_to_wx_bitmap(
                    self.DraggingAxesPanel.get_renderer(), None)
                srcDC = wx.MemoryDC()
                srcDC.SelectObject(srcBmp)

                dc.Blit(destBBox.x, destBBox.y, int(destBBox.width),
                        int(destBBox.height), srcDC, srcBBox.x, srcBBox.y)
            dc.EndDrawing()

        self.RefreshCanvasPosition()

        if not self.Fixed or self.Force:
            self.Force = False
            refresh_graphics = True
        else:
            refresh_graphics = False

        if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels:
            self.DraggingAxesPanel.RefreshViewer(refresh_graphics)
        for panel in self.GraphicPanels:
            if isinstance(panel, DebugVariableGraphicViewer):
                panel.RefreshViewer(refresh_graphics)
            else:
                panel.RefreshViewer()

        if self.CursorTick is not None:
            tick = self.CursorTick
        elif len(self.Ticks) > 0:
            tick = self.Ticks[-1]
        else:
            tick = None
        if tick is not None:
            self.TickLabel.SetLabel(label=_("Tick: %d") % tick)
            tick_duration = int(tick * self.Ticktime)
            not_null = False
            duration = ""
            for value, format in [(tick_duration // DAY, _("%dd")),
                                  ((tick_duration % DAY) // HOUR, _("%dh")),
                                  ((tick_duration % HOUR) // MINUTE, _("%dm")),
                                  ((tick_duration % MINUTE) // SECOND,
                                   _("%ds"))]:

                if value > 0 or not_null:
                    duration += format % value
                    not_null = True

            duration += _("%03gms") % ((tick_duration % SECOND) / MILLISECOND)
            self.TickTimeLabel.SetLabel("t: %s" % duration)
        else:
            self.TickLabel.SetLabel("")
            self.TickTimeLabel.SetLabel("")
        self.TickSizer.Layout()
Exemple #24
0
    def draw(self, detal):
        # self.user.sync_scene()
        #self.user.match_time()
        if self.inited == False:
            return
        if self.user.ball_id == 0:
            return
        ball = self.user.get_ball()
        if ball == None:
            return
            
        self.lblFPS.SetLabel(": %d" % detal)
        if self.user.udp_pack_size != None:
            self.lblUDP.SetLabel(": %d" % self.user.udp_pack_size)
        else:
            self.lblUDP.SetLabel(": 未开启")
            
            
        self.lblPlayerNum.SetLabel(": %d" % len(self.user.players))
        
        self.lblBallId.SetLabel(": %d" % self.user.ball_id)
        self.lblBallX.SetLabel(": %d" % int(ball.x * self.camera.scale))
        self.lblBallY.SetLabel(": %d" % int(ball.y * self.camera.scale))
        # print("sync_delta: ", self.user.sync_delta, " scale: ", self.camera.scale, " typeof(sync_delta): ", type(self.user.sync_delta), "typeof(scale): ", type(self.camera.scale))
        self.lblBallDel.SetLabel(": %f" % (self.user.sync_delta * self.camera.scale))
        self.lbl_max_dis.SetLabel(": %f" % (self.user.max_dis * self.camera.scale))
        self.lbl_sync_interval.SetLabel(": %f" % ((self.user.thisSyncTime - self.user.lastSyncTime) * self.camera.scale))
        
        
        self.user.mutex.acquire()
        rtData = self.right_top_data()
        myballs = {}
        for k, v in self.user.balls.items():
            myballs[k] = v
        myballs_bg = {}
        for k, v in self.user.balls_bg.items():
            myballs_bg[k] = v
        myplayerballs = {}
        for k, v in self.user.playerballs.items():
            myplayerballs[k] = v
        mynofindball = {}
        for k, v in self.user.no_find_ball.items():
            mynofindball[k] = v
        self.user.mutex.release()

        self.draw_right_top(rtData)
        
        mapsize = NET_SCALE * self.res.map["size"]
        x = 0
        y = 0
        if ball != None:
            x = ball.x
            y = ball.y
        viewdata = self.camera.get_view(    \
            wx.Size(PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT),     \
            wx.Point(x,y),     \
            wx.Size(mapsize, mapsize))
        
        bitmap = wx.Bitmap(viewdata["width"], viewdata["height"])
        m = wx.MemoryDC(bitmap)
        m.Clear()
        
        subBitMap = self.bg.GetSubBitmap(wx.Rect(viewdata["xbegin"], viewdata["ybegin"], PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT))
        m.DrawBitmap(subBitMap, 0, 0)
        
        m.SetBrush(wx.Brush(wx.Colour(184,134,11)))
        for block in self.res.map["nodes"]:
            x = block["px"] * NET_SCALE * self.camera.scale
            y = block["py"] * NET_SCALE * self.camera.scale
            tmps = block["radius"] * NET_SCALE * self.camera.scale
            if x > viewdata["xbegin"] - tmps * 2 and \
                y > viewdata["ybegin"] - tmps * 2 and \
                x < viewdata["xend"] + tmps * 2 and \
                y < viewdata["yend"] + tmps * 2:
                
                if tmps < 5:    #为了看的见
                    tmps = 5
                tmpposx = (x - tmps) - viewdata["xbegin"]
                tmpposy = (y - tmps) - viewdata["ybegin"]
                m.DrawRectangle(tmpposx, tmpposy, tmps*2, tmps*2)
                
                
                
        myball = myplayerballs[self.user.ball_id]
        w = 1800 * self.camera.scale
        h = 1800 * self.camera.scale
        tmpposx = myball.x * self.camera.scale - viewdata["xbegin"]
        tmpposy = myball.y * self.camera.scale - viewdata["ybegin"]
        cellwidth = cellheight = int( math.ceil( NET_SCALE * 5 * self.camera.scale))              
        minX = int(math.floor((tmpposx - w/2)/cellwidth) * cellwidth)
        maxX = int(math.floor((tmpposx + w/2)/cellwidth) * cellwidth)
        minY = int(math.floor((tmpposy - h/2)/cellheight) * cellheight)
        maxY = int(math.floor((tmpposy + h/2)/cellheight) * cellheight)
        
        m.SetBrush(wx.Brush(wx.Colour(238,221,130)))
        for _, bg in myballs_bg.items():
            x = bg.x * self.camera.scale
            y = bg.y * self.camera.scale
            tmps = 25 * self.camera.scale
            if x - viewdata["xbegin"] > minX and \
                y - viewdata["ybegin"] > minY and \
                x - viewdata["xbegin"] < maxX + cellwidth and \
                y - viewdata["ybegin"] < maxY + cellheight:
                
                if tmps < 5:    #为了看的见
                    tmps = 5
                tmpposx = (x - tmps) - viewdata["xbegin"]
                tmpposy = (y - tmps) - viewdata["ybegin"]
                m.DrawRectangle(tmpposx, tmpposy, tmps*2, tmps*2)
                    
        for _, ball in myballs.items():
            tmpposx = ball.x * self.camera.scale - viewdata["xbegin"]# * self.camera.get_cell_size()
            tmpposy = ball.y * self.camera.scale - viewdata["ybegin"]# * self.camera.get_cell_size()
            tmps = int(self.res.food[ball.type]["size"] * NET_SCALE * self.camera.scale)
            if tmps < 5:    #为了看的见
                tmps = 5
            
            t = self.res.food[ball.type]["type"]
            if t == proto.wilds_pb2.FoodNormal:
                m.SetBrush(wx.BLUE_BRUSH)
                m.DrawCircle(tmpposx, tmpposy, tmps)
            elif t == proto.wilds_pb2.FoodHammer:
                m.SetPen(wx.BLACK_PEN)
                m.DrawText("%s" % ("锤子"), tmpposx - 18, tmpposy - 10)
            elif t == proto.wilds_pb2.FoodBomb:
                m.SetPen(wx.BLACK_PEN)
                m.DrawText("%s" % ("炸弹"), tmpposx - 18, tmpposy - 10)
            elif t == proto.wilds_pb2.FeedNormal:
                m.SetBrush(wx.Brush(wx.Colour(153,50,204)))
                m.DrawCircle(tmpposx, tmpposy, tmps)
            elif t == proto.wilds_pb2.SkillHammer:
                m.SetBrush(wx.YELLOW_BRUSH)
                m.DrawCircle(tmpposx, tmpposy, tmps)
                m.DrawText("%s" % ("锤子"), tmpposx - 18, tmpposy - 10)
            elif t == proto.wilds_pb2.SkillBomb:
                m.SetBrush(wx.YELLOW_BRUSH)
                m.DrawCircle(tmpposx, tmpposy, tmps)
                m.DrawText("%s" % ("炸弹"), tmpposx - 18, tmpposy - 10)
                
        for _, ball in myplayerballs.items():
            s = self.res.animal[ball.level]["scale"]
                
            if ball.id == self.user.ball_id:
                m.SetBrush(wx.GREEN_BRUSH)
                self.ballx = ball.x * self.camera.scale - viewdata["xbegin"]
                self.bally = ball.y * self.camera.scale - viewdata["ybegin"]
                
                prex = (ball.client_now_x - ball.client_pre_x ) * (ball.client_now_x - ball.client_pre_x )
                prey = (ball.client_now_y - ball.client_pre_y ) * (ball.client_now_y - ball.client_pre_y )
                self.lblMoveDisC.SetLabel(": %f (100ms)" % (math.sqrt(prex + prey)))

                prex = (ball.server_now_x - ball.server_pre_x ) * (ball.server_now_x - ball.server_pre_x )
                prey = (ball.server_now_y - ball.server_pre_y ) * (ball.server_now_y - ball.server_pre_y )        
                self.lblMoveDisS.SetLabel(": %f (100ms)" % (math.sqrt(prex + prey)))
                
            else:
                m.SetBrush(wx.RED_BRUSH)
                
            m.SetPen(wx.BLACK_PEN)

            tmpposx = ball.x * self.camera.scale - viewdata["xbegin"]
            tmpposy = ball.y * self.camera.scale - viewdata["ybegin"]
            tmps = int(s * NET_SCALE * self.camera.scale)
            if tmps < 5:    #为了看的见
                tmps = 5
            m.DrawCircle(tmpposx, tmpposy, tmps)
            
            m.SetPen(wx.RED_PEN)
            m.SetBrush(wx.TRANSPARENT_BRUSH)
            if ball.id == self.user.ball_id:
                m.DrawRectangle(tmpposx - w/2, tmpposy - h/2, w, h)
                m.DrawRectangle(minX, minY, maxX - minX + cellwidth, maxY - minY + cellheight)
                
            
            m.SetPen(wx.BLACK_PEN)
            
            tempv = None
            if ball.face != 0:
                if ball.face in myplayerballs:
                    tempv = vector2.Vector(myplayerballs[ball.face].x - ball.x, myplayerballs[ball.face].y - ball.y)
            if tempv == None:
                angleX = math.cos(math.pi * ball.angle / 180.0)
                angleY = -math.sin(math.pi * ball.angle / 180.0)
                tempv = vector2.Vector(angleX, angleY)
            tempv.NormalizeSelf()
            tempv.ScaleBy(tmps)
            tempv.IncreaseBy(vector2.Vector(tmpposx, tmpposy))
            m.DrawLine(tmpposx, tmpposy, tempv.x, tempv.y)
            
            
            if ball.state != 0:
                m.DrawText("%s" % state.NAME[ball.state], tmpposx - 20, tmpposy - 35)
            m.DrawText("hp:%d" % ball.hp, tmpposx - 20, tmpposy - 20)
            if ball.id == self.user.ball_id and ball.curmp!=None:
                m.DrawText("curmp:%d" % ball.curmp, tmpposx - 20, tmpposy - 5)
            m.DrawText("lvl:%d" % ball.level, tmpposx - 15, tmpposy + 10)

            # 经验条
            if ball.id == self.user.ball_id:
                nextLevelExp = self.user.res.get_next_level_exp(ball.level)
                curLevelExp = 0
                if ball.level > 1:
                    curLevelExp = self.user.res.get_next_level_exp(ball.level - 1)

                if ball.curexp - curLevelExp > 0:
                    angle = math.pi * 2 * (ball.curexp - curLevelExp) / (nextLevelExp - curLevelExp)
                    # print("level:", ball.level, " nle:", nextLevelExp, " cle:", curLevelExp, " curexp:", ball.curexp, " angle:", angle / math.pi * 180)
                    tox = tmpposx + math.cos(angle) * tmps
                    toy = tmpposy - math.sin(angle) * tmps

                    pen = wx.Pen(wx.Colour(255, 0, 0), 2)
                    m.SetPen(pen)
                    m.DrawArc(tmpposx + tmps, tmpposy, tox, toy, tmpposx, tmpposy)

            
        m.SetBrush(wx.WHITE_BRUSH)
        for _, ball in mynofindball.items():
            tmpposx = ball.x * self.camera.scale - viewdata["xbegin"]
            tmpposy = ball.y * self.camera.scale - viewdata["ybegin"]
            tmps = 30 * self.camera.scale
            m.DrawCircle(tmpposx, tmpposy, tmps)
            m.DrawText("%d" % ball.id, tmpposx - 10, tmpposy - 15)
            
        if self.EndTime!=None:
            m.DrawText("剩余时间:%d" % (self.EndTime), PLAY_AREA_WIDTH / 2 - 50, 50)
        m.SelectObject(wx.NullBitmap)
        del m
        
        dc = wx.ClientDC(self.panel)
        #dc.DrawBitmap(bitmap, -viewdata["draw_xbegin"], -viewdata["draw_ybegin"])
        dc.DrawBitmap(bitmap, 0, 0)
        del dc
Exemple #25
0
 def test_NativeHandle(self):
     dc = wx.MemoryDC(wx.Bitmap(10, 10))
     h = dc.GetHandle()
     self.assertTrue(h is not None)
     self.assertNotEqual(int(h), 0)
Exemple #26
0
    def SetNextPos(self):
        self.user.mutex.acquire()
        mapsize = NET_SCALE * self.res.map["size"]
        radius = 0.25 * NET_SCALE

        # if self.pre_cal_speed_time == 0:
        #     self.pre_cal_speed_time = int(round(time.time() * 1000))
        now = int(round(time.time() * 1000))
        # detal = now - self.pre_cal_speed_time
        # self.pre_cal_speed_time = now

        for _, v in self.user.playerballs.items():
            
            #new
            # prex = v.x
            # prey = v.y
            # passTime = now - v.last_update_time
            # if now < v.this_cli_time:
            #     v.x += v.vx * passTime / 50
            #     v.y += v.vy * passTime / 50
            #     moveDis = math.sqrt((v.x - prex) * (v.x - prex) + (v.y - prey) * (v.y - prey))
            #     # print("move dis ", moveDis, " passtime ", passTime, " vx ", v.vx)
            # elif v.last_update_time >= v.this_cli_time:
            #     v.x += v.this_vx * passTime / 50
            #     v.y += v.this_vy * passTime / 50
            #     moveDis = math.sqrt((v.x - prex) * (v.x - prex) + (v.y - prey) * (v.y - prey))
            #     # print("move dis ", moveDis, " passtime ", passTime, " this_vx ", v.this_vx)
            # else:
            #     t1 = v.this_cli_time - v.last_update_time
            #     v.x += v.vx * t1 / 50
            #     v.y += v.vy * t1 / 50

            #     t2 = now - v.this_cli_time
            #     v.x += v.this_vx * t2 / 50
            #     v.y += v.this_vy * t2 / 50
            #     moveDis = math.sqrt((v.x - prex) * (v.x - prex) + (v.y - prey) * (v.y - prey))
            #     # print("move dis ", moveDis, " passtime ", passTime, " (vx) ", v.vx, " ", v.this_vx)
            # #new

            # #old
            # # v.x += v.vx*detal/50
            # # v.y += v.vy*detal/50
            # #old

            # if v.x > mapsize - radius:
            #     v.x = mapsize - radius
            # elif v.x < radius:
            #     v.x = radius
            # if v.y > mapsize - radius:
            #     v.y = mapsize - radius
            # elif v.y < radius:
            #     v.y = radius

            # if abs(v.x - v.this_x) < 1:
            #     v.x = v.this_x
            # if abs(v.y - v.this_y) < 1:
            #     v.y = v.this_y

            # v.last_update_time = now

            self.user.gameSync.UpdateMove(v, mapsize, now, self)

            # if now >= v.this_cli_time + 100:
            #     v.vx = v.this_vx
            #     v.vy = v.this_vy

            if v.id == self.user.ball_id:
                if self.show_line:
                    m = wx.MemoryDC(self.bg)
                    m.SetBrush(wx.BLACK_BRUSH)
                    m.DrawCircle(v.x, v.y, 1)

                    m.SetBrush(wx.RED_BRUSH)
                    m.DrawCircle(v.this_x, v.this_y, 1)

                    interval = self.user.thisSyncTime - self.user.lastSyncTime
                    if interval >= 150:
                        m.DrawText("%dms" % interval, v.x, v.y)
                        self.user.lastSyncTime = self.user.thisSyncTime

                    m.SelectObject(wx.NullBitmap)
                    del m
                    
        for _, v in self.user.balls.items():
            if v.isplayer != None:
                self.user.gameSync.UpdateMove(v, mapsize, now, self)
                    
        self.user.mutex.release()
import wx
import os
import ftplib

w = wx.App()
screen = wx.ScreenDC()
size = screen.GetSize()
bmap = wx.Bitmap(size[0], size[1])
memo = wx.MemoryDC(bmap)
memo.Blit(0, 0, size[0], size[1], screen, 0, 0)

bmap.SaveFile("grabbed.png", wx.BITMAP_TYPE_PNG)

sess_ = ftplib.FTP("localhost", "flypython", "flypython")
file_ = open("grabbed.png", "rb")
sess_.storbinary("STOR  grabbed.png", file_)

file_.close()
sess_.quit()
Exemple #28
0
#    Este programa eh distribuido na expectativa de ser util, mas SEM
#    QUALQUER GARANTIA; sem mesmo a garantia implicita de
#    COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
#    PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
#    detalhes.
# --------------------------------------------------------------------------
import sys

import numpy
import wx
from wx.lib import intctrl

from invesalius.gui.widgets.inv_spinctrl import InvSpinCtrl

try:
    dc = wx.MemoryDC()
    font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
    dc.SetFont(font)
    PUSH_WIDTH = dc.GetTextExtent("M")[0] // 2 + 1
    del dc
    del font
except Exception:
    PUSH_WIDTH = 7

myEVT_SLIDER_CHANGED = wx.NewEventType()
EVT_SLIDER_CHANGED = wx.PyEventBinder(myEVT_SLIDER_CHANGED, 1)

myEVT_SLIDER_CHANGING = wx.NewEventType()
EVT_SLIDER_CHANGING = wx.PyEventBinder(myEVT_SLIDER_CHANGING, 1)

myEVT_THRESHOLD_CHANGED = wx.NewEventType()
Exemple #29
0
    def onTakeScreenShot(self, event, name):
        # """
        # Делает скриншот выбранного фрагмента экрана
        # Основано на методе, предложенном Андреа Гавана
        start1 = clock()
        with open('coord_snapshot.txt', 'r') as f:  # извлекаем  из файла
            data2 = json.load(f)
        print('', data2)
        rect1 = data2  # win32gui.GetWindowRect(hwnd)

        # mfcDC = win32ui.CreateDCFromHandle(hwnd)
        print('rect', rect1)

        rect = self.GetRect()  # получаем координаты своего окна
        rect.x = rect1[0]  # +134
        rect.y = rect1[1]  # +275
        rect.width = rect1[2] - rect1[0]  # +1080)
        rect.height = rect1[3] - rect1[1]  # +691)
        # print('координаты', rect.x, rect.y, rect.width, rect.height)
        # Настройка ширины для Linux обнаружено Джоном Торресом
        # http://article.gmane.org/gmane.comp.python.wxpython/67327
        if sys.platform == 'linux2':
            client_x, client_y = self.ClientToScreen((0, 0))
            border_width = client_x - rect.x
            title_bar_height = client_y - rect.y
            rect.width += (border_width * 2)
            rect.height += title_bar_height + border_width

        # Сделать скриншот всей зоны DC (контекста устройства)
        dcScreen = wx.ScreenDC()

        # Создать битмап, в котором сохранится скриншот
        # Учтите, что битмап должен быть достаточно большим, чтобы в него поместился скриншот
        # -1 значит использование текущей стандартной глубины цвета
        bmp = wx.Bitmap(rect.width, rect.height)

        # Создать в памяти DC, который будет использован непосредственно для скриншота
        memDC = wx.MemoryDC()

        # Прикажите DC использовать наш битмап
        # Все изображения из DC теперь переместится в битмап
        memDC.SelectObject(bmp)

        # Blit в данном случае скопируйте сам экран в кэш памяти
        # и, таким образом, он попадёт в битмап
        memDC.Blit(
            0,  # Скопируйте сюда координат Х
            0,  # Скопируйте сюда координат Y
            rect.width,  # Скопируйте эту ширину
            rect.height,  # Скопируйте эту высоту
            dcScreen,  # Место, откуда нужно скопировать
            rect.
            x,  # Какой офсет у Х в оригинальном DC (контексте устройства)?
            rect.y  # Какой офсет у Y в оригинальном DC?
        )

        # Select the Bitmap out of the memory DC by selecting a new
        # uninitialized Bitmap
        memDC.SelectObject(wx.NullBitmap)
        fileName = name + '.bmp'

        img = bmp.ConvertToImage()

        img.SaveFile(fileName, wx.BITMAP_TYPE_BMP)

        print('...saving as BMP!')

        end1 = clock()

        print("Result (iterativ): выполняется за " +
              "\nФункция %1.10f секунд" % (end1 - start1))
Exemple #30
0
    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`AquaButton`.

        :param `event`: a :class:`PaintEvent` event to be processed.
        """

        dc = wx.BufferedPaintDC(self)
        gc = wx.GraphicsContext.Create(dc)

        xpos, ypos, width, height = self.GetClientRect()

        dc.SetBackground(wx.Brush(self._rectColour))
        dc.Clear()
        gc.SetBrush(wx.WHITE_BRUSH)

        shadowOffset = 5
        btnOffset = 0
        clr = self._backColour

        if self._mouseAction == CLICK:
            shadowOffset = 3
            clr = self._hoverColour
            btnOffset = 2

        elif self._mouseAction == HOVER:
            clr = self._hoverColour

        elif self._hasFocus:
            clr = self._focusColour

        elif not self.IsEnabled():
            clr = self._disableColour

        rc1 = wx.Rect(btnOffset, btnOffset, width-8-btnOffset, height-8-btnOffset)
        path1 = self.GetPath(gc, rc1, 10)
        br1 = gc.CreateLinearGradientBrush(0, 0, 0, rc1.height+6, clr, wx.WHITE)

        # Create shadow
        rc2 = wx.Rect(*rc1)
        rc2.Offset((shadowOffset, shadowOffset))
        path2 = self.GetPath(gc, rc2, 10)
        br2 = gc.CreateRadialGradientBrush(rc2.x, rc2.y,
                                           rc2.x+rc2.width, rc2.y+rc2.height,
                                           rc2.width, self._shadowColour, wx.WHITE)

        # Create top water colour to give "aqua" effect
        rc3 = wx.Rect(*rc1)
        rc3.Inflate(-5, -5)
        rc3.height = 15
        path3 = self.GetPath(gc, rc3, 10)

        br3 = gc.CreateLinearGradientBrush(rc3.x, rc3.y, rc3.x, rc3.y+rc3.height,
                                           wx.WHITE, wx.TransparentColour)

        # draw shapes
        gc.SetBrush(br2)
        gc.FillPath(path2)  #draw shadow
        gc.SetBrush(br1)
        gc.FillPath(path1) #draw main
        gc.SetBrush(br3)
        gc.FillPath(path3) #draw top bubble

        font = gc.CreateFont(self.GetFont(), self._textColour)

        gc.SetFont(font)
        label = self.GetLabel()
        tw, th = gc.GetTextExtent(label)

        if self._bitmap:
            bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
        else:
            bw = bh = 0

        pos_x = (width-bw-tw)/2+btnOffset-shadowOffset      # adjust for bitmap and text to centre
        if self._bitmap:
            pos_y =  (height-bh-shadowOffset)/2+btnOffset
            gc.DrawBitmap(self._bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
            pos_x = pos_x + 2   # extra spacing from bitmap

        # Create a Path to draw the text
        gc.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)      # draw the text

        if self._saveBitmap:
            # Save the bitmap using wx.MemoryDC for later use
            self._saveBitmap = False
            memory = wx.MemoryDC()
            self._storedBitmap = wx.Bitmap.FromRGBA(max(width, 1), max(height, 1))
            memory.SelectObject(self._storedBitmap)

            gcMemory = wx.GraphicsContext.Create(memory)

            gcMemory.SetBrush(br1)
            gcMemory.FillPath(path1) #draw main
            gcMemory.SetBrush(br3)
            gcMemory.FillPath(path3) #draw top bubble

            if self._bitmap:
                gcMemory.DrawBitmap(self._bitmap, pos_x - 2, pos_y, bw, bh)

            gcMemory.SetFont(font)
            gcMemory.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)

            memory.SelectObject(wx.NullBitmap)
            self._storedBitmap = self._storedBitmap.ConvertToImage()