]> git.saurik.com Git - wxWidgets.git/blame - wxPython/wx/lib/wordwrap.py
Added a set of button classes to wx.lib.buttons from David Hughes that
[wxWidgets.git] / wxPython / wx / lib / wordwrap.py
CommitLineData
f9c1b462
RD
1#----------------------------------------------------------------------
2# Name: wx.lib.wrap
3# Purpose: Contains a function to aid in word-wrapping some text
4#
5# Author: Robin Dunn
6#
7# Created: 15-Oct-2006
8# RCS-ID: $Id$
9# Copyright: (c) 2006 by Total Control Software
10# Licence: wxWindows license
11#----------------------------------------------------------------------
12
13
14
15def wordwrap(text, width, dc, breakLongWords=True):
16 """
17 Returns a copy of text with newline characters inserted where long
18 lines should be broken such that they will fit within the given
19 width, on the given `wx.DC` using its current font settings. By
20 default words that are wider than width will be broken at the
21 nearest character boundary, but this can be disabled by passing
22 ``False`` for the ``breakLongWords`` parameter.
23 """
24
25 wrapped_lines = []
26 text = text.split('\n')
27 for line in text:
28 pte = dc.GetPartialTextExtents(line)
29 idx = 0
30 start = 0
31 startIdx = 0
32 spcIdx = -1
33 while idx < len(pte):
34 # remember the last seen space
35 if line[idx] == ' ':
36 spcIdx = idx
37
38 # have we reached the max width?
39 if pte[idx] - start > width and (spcIdx != -1 or breakLongWords):
40 if spcIdx != -1:
41 idx = spcIdx + 1
42 wrapped_lines.append( line[startIdx : idx] )
43 start = pte[idx]
44 startIdx = idx
45 spcIdx = -1
46
47 idx += 1
48
49 wrapped_lines.append( line[startIdx : idx] )
50
51 return '\n'.join(wrapped_lines)
52
53
54
55
56
57if __name__ == '__main__':
58 import wx
59 class TestPanel(wx.Panel):
60 def __init__(self, parent):
61 wx.Panel.__init__(self, parent)
62
63 self.tc = wx.TextCtrl(self, -1, "", (20,20), (150,150), wx.TE_MULTILINE)
64 self.Bind(wx.EVT_TEXT, self.OnDoUpdate, self.tc)
65
66 def OnDoUpdate(self, evt):
67 WIDTH = 200
68 bmp = wx.EmptyBitmap(WIDTH, WIDTH)
69 mdc = wx.MemoryDC(bmp)
70 mdc.SetBackground(wx.Brush("white"))
71 mdc.Clear()
72 mdc.SetPen(wx.Pen("black"))
73 mdc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
74 mdc.DrawRectangle(0,0, WIDTH, WIDTH)
75
76 text = wordwrap(self.tc.GetValue(), WIDTH-2, mdc, False)
77 #print repr(text)
78 mdc.DrawLabel(text, (1,1, WIDTH-2, WIDTH-2))
79
80 del mdc
81 dc = wx.ClientDC(self)
82 dc.DrawBitmap(bmp, 200, 20)
83
84
85 app = wx.App(False)
86 frm = wx.Frame(None, title="Test wordWrap")
87 pnl = TestPanel(frm)
88 frm.Show()
89 app.MainLoop()
90
91