remove always-true test of unsigned >= 0
[wxWidgets.git] / src / common / ctrlcmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/ctrlcmn.cpp
3 // Purpose: wxControl common interface
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 26.07.99
7 // RCS-ID: $Id$
8 // Copyright: (c) wxWidgets team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_CONTROLS
28
29 #include "wx/control.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/dc.h"
33 #include "wx/log.h"
34 #include "wx/radiobut.h"
35 #include "wx/statbmp.h"
36 #include "wx/bitmap.h"
37 #include "wx/utils.h" // for wxStripMenuCodes()
38 #include "wx/settings.h"
39 #endif
40
41 const char wxControlNameStr[] = "control";
42
43 // ============================================================================
44 // implementation
45 // ============================================================================
46
47 wxControlBase::~wxControlBase()
48 {
49 // this destructor is required for Darwin
50 }
51
52 bool wxControlBase::Create(wxWindow *parent,
53 wxWindowID id,
54 const wxPoint &pos,
55 const wxSize &size,
56 long style,
57 const wxValidator& wxVALIDATOR_PARAM(validator),
58 const wxString &name)
59 {
60 bool ret = wxWindow::Create(parent, id, pos, size, style, name);
61
62 #if wxUSE_VALIDATORS
63 if ( ret )
64 SetValidator(validator);
65 #endif // wxUSE_VALIDATORS
66
67 return ret;
68 }
69
70 bool wxControlBase::CreateControl(wxWindowBase *parent,
71 wxWindowID id,
72 const wxPoint& pos,
73 const wxSize& size,
74 long style,
75 const wxValidator& validator,
76 const wxString& name)
77 {
78 // even if it's possible to create controls without parents in some port,
79 // it should surely be discouraged because it doesn't work at all under
80 // Windows
81 wxCHECK_MSG( parent, false, wxT("all controls must have parents") );
82
83 if ( !CreateBase(parent, id, pos, size, style, validator, name) )
84 return false;
85
86 parent->AddChild(this);
87
88 return true;
89 }
90
91 void wxControlBase::Command(wxCommandEvent& event)
92 {
93 (void)GetEventHandler()->ProcessEvent(event);
94 }
95
96 void wxControlBase::InitCommandEvent(wxCommandEvent& event) const
97 {
98 event.SetEventObject(const_cast<wxControlBase *>(this));
99
100 // event.SetId(GetId()); -- this is usuall done in the event ctor
101
102 switch ( m_clientDataType )
103 {
104 case wxClientData_Void:
105 event.SetClientData(GetClientData());
106 break;
107
108 case wxClientData_Object:
109 event.SetClientObject(GetClientObject());
110 break;
111
112 case wxClientData_None:
113 // nothing to do
114 ;
115 }
116 }
117
118 bool wxControlBase::SetFont(const wxFont& font)
119 {
120 InvalidateBestSize();
121 return wxWindow::SetFont(font);
122 }
123
124 // wxControl-specific processing after processing the update event
125 void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent& event)
126 {
127 // call inherited
128 wxWindowBase::DoUpdateWindowUI(event);
129
130 // update label
131 if ( event.GetSetText() )
132 {
133 if ( event.GetText() != GetLabel() )
134 SetLabel(event.GetText());
135 }
136
137 // Unfortunately we don't yet have common base class for
138 // wxRadioButton, so we handle updates of radiobuttons here.
139 // TODO: If once wxRadioButtonBase will exist, move this code there.
140 #if wxUSE_RADIOBTN
141 if ( event.GetSetChecked() )
142 {
143 wxRadioButton *radiobtn = wxDynamicCastThis(wxRadioButton);
144 if ( radiobtn )
145 radiobtn->SetValue(event.GetChecked());
146 }
147 #endif // wxUSE_RADIOBTN
148 }
149
150 /* static */
151 wxString wxControlBase::GetLabelText(const wxString& label)
152 {
153 // we don't want strip the TABs here, just the mnemonics
154 return wxStripMenuCodes(label, wxStrip_Mnemonics);
155 }
156
157 /* static */
158 wxString wxControlBase::RemoveMnemonics(const wxString& str)
159 {
160 // we don't want strip the TABs here, just the mnemonics
161 return wxStripMenuCodes(str, wxStrip_Mnemonics);
162 }
163
164 /* static */
165 wxString wxControlBase::EscapeMnemonics(const wxString& text)
166 {
167 wxString label(text);
168 label.Replace("&", "&&");
169 return label;
170 }
171
172 /* static */
173 int wxControlBase::FindAccelIndex(const wxString& label, wxString *labelOnly)
174 {
175 // the character following MNEMONIC_PREFIX is the accelerator for this
176 // control unless it is MNEMONIC_PREFIX too - this allows to insert
177 // literal MNEMONIC_PREFIX chars into the label
178 static const wxChar MNEMONIC_PREFIX = wxT('&');
179
180 if ( labelOnly )
181 {
182 labelOnly->Empty();
183 labelOnly->Alloc(label.length());
184 }
185
186 int indexAccel = -1;
187 for ( wxString::const_iterator pc = label.begin(); pc != label.end(); ++pc )
188 {
189 if ( *pc == MNEMONIC_PREFIX )
190 {
191 ++pc; // skip it
192 if ( pc == label.end() )
193 break;
194 else if ( *pc != MNEMONIC_PREFIX )
195 {
196 if ( indexAccel == -1 )
197 {
198 // remember it (-1 is for MNEMONIC_PREFIX itself
199 indexAccel = pc - label.begin() - 1;
200 }
201 else
202 {
203 wxFAIL_MSG(wxT("duplicate accel char in control label"));
204 }
205 }
206 }
207
208 if ( labelOnly )
209 {
210 *labelOnly += *pc;
211 }
212 }
213
214 return indexAccel;
215 }
216
217 wxBorder wxControlBase::GetDefaultBorder() const
218 {
219 return wxBORDER_THEME;
220 }
221
222 /* static */ wxVisualAttributes
223 wxControlBase::GetCompositeControlsDefaultAttributes(wxWindowVariant WXUNUSED(variant))
224 {
225 wxVisualAttributes attrs;
226 attrs.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
227 attrs.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
228 attrs.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
229
230 return attrs;
231 }
232
233 // ----------------------------------------------------------------------------
234 // wxControlBase - ellipsization code
235 // ----------------------------------------------------------------------------
236
237 #define wxELLIPSE_REPLACEMENT wxS("...")
238
239 /* static and protected */
240 wxString wxControlBase::DoEllipsizeSingleLine(const wxString& curLine, const wxDC& dc,
241 wxEllipsizeMode mode, int maxFinalWidthPx,
242 int replacementWidthPx, int marginWidthPx)
243 {
244 wxASSERT_MSG(replacementWidthPx > 0 && marginWidthPx > 0,
245 "Invalid parameters");
246 wxASSERT_LEVEL_2_MSG(!curLine.Contains('\n'),
247 "Use Ellipsize() instead!");
248
249 wxASSERT_MSG( mode != wxELLIPSIZE_NONE, "shouldn't be called at all then" );
250
251 // NOTE: this function assumes that any mnemonic/tab character has already
252 // been handled if it was necessary to handle them (see Ellipsize())
253
254 if (maxFinalWidthPx <= 0)
255 return wxEmptyString;
256
257 wxArrayInt charOffsetsPx;
258 size_t len = curLine.length();
259 if (len == 0 ||
260 !dc.GetPartialTextExtents(curLine, charOffsetsPx))
261 return curLine;
262
263 wxASSERT(charOffsetsPx.GetCount() == len);
264
265 // NOTE: charOffsetsPx[n] is the width in pixels of the first n characters (with the last one INCLUDED)
266 // thus charOffsetsPx[len-1] is the total width of the string
267 size_t totalWidthPx = charOffsetsPx.Last();
268 if ( totalWidthPx <= (size_t)maxFinalWidthPx )
269 return curLine; // we don't need to do any ellipsization!
270
271 int excessPx = wxMin(totalWidthPx - maxFinalWidthPx +
272 replacementWidthPx +
273 marginWidthPx, // security margin
274 totalWidthPx);
275 wxASSERT(excessPx>0); // excessPx should be in the [1;totalWidthPx] range
276
277 // REMEMBER: indexes inside the string have a valid range of [0;len-1] if not otherwise constrained
278 // lengths/counts of characters (e.g. nCharsToRemove) have a valid range of [0;len] if not otherwise constrained
279 // NOTE: since this point we know we have for sure a non-empty string from which we need
280 // to remove _at least_ one character (thus nCharsToRemove below is constrained to be >= 1)
281
282 size_t initialCharToRemove, // index of first character to erase, valid range is [0;len-1]
283 nCharsToRemove; // how many chars do we need to erase? valid range is [1;len-initialCharToRemove]
284
285 // let's compute the range of characters to remove depending on the ellipsization mode:
286 switch (mode)
287 {
288 case wxELLIPSIZE_START:
289 initialCharToRemove = 0;
290 for ( nCharsToRemove = 1;
291 nCharsToRemove < len && charOffsetsPx[nCharsToRemove-1] < excessPx;
292 nCharsToRemove++ )
293 ;
294 break;
295
296 case wxELLIPSIZE_MIDDLE:
297 {
298 // NOTE: the following piece of code works also when len == 1
299
300 // start the removal process from the middle of the string
301 // i.e. separe the string in three parts:
302 // - the first one to preserve, valid range [0;initialCharToRemove-1] or the empty range if initialCharToRemove==0
303 // - the second one to remove, valid range [initialCharToRemove;endCharToRemove]
304 // - the third one to preserve, valid range [endCharToRemove+1;len-1] or the empty range if endCharToRemove==len-1
305 // NOTE: empty range != range [0;0] since the range [0;0] contains 1 character (the zero-th one)!
306 initialCharToRemove = len/2;
307 size_t endCharToRemove = len/2; // index of the last character to remove; valid range is [0;len-1]
308
309 int removedPx = 0;
310 for ( ; removedPx < excessPx; )
311 {
312 // try to remove the last character of the first part of the string
313 if (initialCharToRemove > 0)
314 {
315 // width of the (initialCharToRemove-1)-th character
316 int widthPx;
317 if (initialCharToRemove >= 2)
318 widthPx = charOffsetsPx[initialCharToRemove-1] - charOffsetsPx[initialCharToRemove-2];
319 else
320 widthPx = charOffsetsPx[initialCharToRemove-1];
321 // the (initialCharToRemove-1)-th character is the first char of the string
322
323 wxASSERT(widthPx >= 0); // widthPx is zero for e.g. tab characters
324
325 // mark the (initialCharToRemove-1)-th character as removable
326 initialCharToRemove--;
327 removedPx += widthPx;
328 }
329
330 // try to remove the first character of the last part of the string
331 if (endCharToRemove < len - 1 &&
332 removedPx < excessPx)
333 {
334 // width of the (endCharToRemove+1)-th character
335 int widthPx = charOffsetsPx[endCharToRemove+1] -
336 charOffsetsPx[endCharToRemove];
337
338 wxASSERT(widthPx >= 0); // widthPx is zero for e.g. tab characters
339
340 // mark the (endCharToRemove+1)-th character as removable
341 endCharToRemove++;
342 removedPx += widthPx;
343 }
344
345 if (initialCharToRemove == 0 && endCharToRemove == len-1)
346 {
347 // we need to remove all the characters of the string!
348 break;
349 }
350 }
351
352 nCharsToRemove = endCharToRemove - initialCharToRemove + 1;
353 }
354 break;
355
356 case wxELLIPSIZE_END:
357 {
358 int maxWidthPx = totalWidthPx - excessPx;
359
360 // go backward from the end of the string toward the start
361 for ( initialCharToRemove = len-1;
362 initialCharToRemove > 0 && charOffsetsPx[initialCharToRemove-1] > maxWidthPx;
363 initialCharToRemove-- )
364 ;
365 nCharsToRemove = len - initialCharToRemove;
366 }
367 break;
368
369 case wxELLIPSIZE_NONE:
370 default:
371 wxFAIL_MSG("invalid ellipsize mode");
372 return curLine;
373 }
374
375 wxASSERT(initialCharToRemove <= len-1); // see valid range for initialCharToRemove above
376 wxASSERT(nCharsToRemove >= 1 && nCharsToRemove <= len-initialCharToRemove); // see valid range for nCharsToRemove above
377
378 // erase nCharsToRemove characters after initialCharToRemove (included);
379 // e.g. if we have the string "foobar" (len = 6)
380 // ^
381 // \--- initialCharToRemove = 2
382 // and nCharsToRemove = 2, then we get "foar"
383 wxString ret(curLine);
384 ret.erase(initialCharToRemove, nCharsToRemove);
385
386 int removedPx;
387 if (initialCharToRemove >= 1)
388 removedPx = charOffsetsPx[initialCharToRemove+nCharsToRemove-1] - charOffsetsPx[initialCharToRemove-1];
389 else
390 removedPx = charOffsetsPx[initialCharToRemove+nCharsToRemove-1];
391 wxASSERT(removedPx >= excessPx);
392
393 // if there is space for the replacement dots, add them
394 if ((int)totalWidthPx-removedPx+replacementWidthPx < maxFinalWidthPx)
395 ret.insert(initialCharToRemove, wxELLIPSE_REPLACEMENT);
396
397 // if everything was ok, we should have shortened this line
398 // enough to make it fit in maxFinalWidthPx:
399 wxASSERT_LEVEL_2(dc.GetTextExtent(ret).GetWidth() <= maxFinalWidthPx);
400
401 return ret;
402 }
403
404 /* static */
405 wxString wxControlBase::Ellipsize(const wxString& label, const wxDC& dc,
406 wxEllipsizeMode mode, int maxFinalWidth,
407 int flags)
408 {
409 wxString ret;
410
411 // these cannot be cached between different Ellipsize() calls as they can
412 // change because of e.g. a font change; however we calculate them only once
413 // when ellipsizing multiline labels:
414 int replacementWidth = dc.GetTextExtent(wxELLIPSE_REPLACEMENT).GetWidth();
415 int marginWidth = dc.GetCharWidth();
416
417 // NB: we must handle correctly labels with newlines:
418 wxString curLine;
419 for ( wxString::const_iterator pc = label.begin(); ; ++pc )
420 {
421 if ( pc == label.end() || *pc == wxS('\n') )
422 {
423 curLine = DoEllipsizeSingleLine(curLine, dc, mode, maxFinalWidth,
424 replacementWidth, marginWidth);
425
426 // add this (ellipsized) row to the rest of the label
427 ret << curLine;
428 if ( pc == label.end() )
429 {
430 // NOTE: this is the return which always exits the function
431 return ret;
432 }
433 else
434 {
435 ret << *pc;
436 curLine.clear();
437 }
438 }
439 // we need to remove mnemonics from the label for correct calculations
440 else if ( *pc == wxS('&') && (flags & wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS) )
441 {
442 // pc+1 is safe: at worst we'll be at end()
443 wxString::const_iterator next = pc + 1;
444 if ( next != label.end() && *next == wxS('&') )
445 curLine += wxS('&'); // && becomes &
446 //else: remove this ampersand
447 }
448 // we need also to expand tabs to properly calc their size
449 else if ( *pc == wxS('\t') && (flags & wxELLIPSIZE_FLAGS_EXPAND_TABS) )
450 {
451 // Windows natively expands the TABs to 6 spaces. Do the same:
452 curLine += wxS(" ");
453 }
454 else
455 {
456 curLine += *pc;
457 }
458 }
459
460 // this return would generate a
461 // warning C4702: unreachable code
462 // with MSVC since the function always exits from inside the loop
463 //return ret;
464 }
465
466
467
468 // ----------------------------------------------------------------------------
469 // wxStaticBitmap
470 // ----------------------------------------------------------------------------
471
472 #if wxUSE_STATBMP
473
474 wxStaticBitmapBase::~wxStaticBitmapBase()
475 {
476 // this destructor is required for Darwin
477 }
478
479 wxSize wxStaticBitmapBase::DoGetBestSize() const
480 {
481 wxSize best;
482 wxBitmap bmp = GetBitmap();
483 if ( bmp.Ok() )
484 best = wxSize(bmp.GetWidth(), bmp.GetHeight());
485 else
486 // this is completely arbitrary
487 best = wxSize(16, 16);
488 CacheBestSize(best);
489 return best;
490 }
491
492 #endif // wxUSE_STATBMP
493
494 #endif // wxUSE_CONTROLS