Added stubs for (DeviceToLogical|LogicalToDevice)(X|Y)Rel
[wxWidgets.git] / src / cocoa / dc.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/cocoa/dc.mm
3 // Purpose:     wxDC
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2003/04/01
7 // RCS-ID:      $Id$
8 // Copyright:   (c) 2003 David Elliott
9 // Licence:     wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/dc.h"
13 #include "wx/log.h"
14
15 #include "wx/cocoa/autorelease.h"
16
17 #import <AppKit/NSBezierPath.h>
18 #import <AppKit/NSTextStorage.h>
19 #import <AppKit/NSLayoutManager.h>
20 #import <AppKit/NSTextContainer.h>
21 #import <AppKit/NSGraphicsContext.h>
22 #import <AppKit/NSAffineTransform.h>
23 #import <AppKit/NSColor.h>
24 #import <AppKit/NSTypeSetter.h>
25 #import <AppKit/NSImage.h>
26
27 #include <wx/listimpl.cpp>
28 WX_DEFINE_LIST(wxCocoaDCStack);
29
30 IMPLEMENT_ABSTRACT_CLASS(wxDC, wxObject)
31 WX_NSTextStorage wxDC::sm_cocoaNSTextStorage = nil;
32 WX_NSLayoutManager wxDC::sm_cocoaNSLayoutManager = nil;
33 WX_NSTextContainer wxDC::sm_cocoaNSTextContainer = nil;
34 wxCocoaDCStack wxDC::sm_cocoaDCStack;
35
36 void wxDC::CocoaInitializeTextSystem()
37 {
38     wxASSERT_MSG(!sm_cocoaNSTextStorage && !sm_cocoaNSLayoutManager && !sm_cocoaNSTextContainer,"Text system already initalized!  BAD PROGRAMMER!");
39
40     sm_cocoaNSTextStorage = [[NSTextStorage alloc] init];
41
42     sm_cocoaNSLayoutManager = [[NSLayoutManager alloc] init];
43     [sm_cocoaNSTextStorage addLayoutManager:sm_cocoaNSLayoutManager];
44     // NSTextStorage retains NSLayoutManager, but so do we
45     // [sm_cocoaNSLayoutManager release]; [sm_cocoaNSLayoutManager retain];
46
47     // NOTE:  initWithContainerSize is the designated initializer, but the
48     // Apple CircleView sample gets away with just calling init, which
49     // is all we really need for our purposes.
50     sm_cocoaNSTextContainer = [[NSTextContainer alloc] init];
51     [sm_cocoaNSLayoutManager addTextContainer:sm_cocoaNSTextContainer];
52     // NSLayoutManager retains NSTextContainer, but so do we
53     // [sm_cocoaNSTextContainer release]; [sm_cocoaNSTextContainer retain];
54 }
55
56 void wxDC::CocoaShutdownTextSystem()
57 {
58     [sm_cocoaNSTextContainer release]; sm_cocoaNSTextContainer = nil;
59     [sm_cocoaNSLayoutManager release]; sm_cocoaNSLayoutManager = nil;
60     [sm_cocoaNSTextStorage release]; sm_cocoaNSTextStorage = nil;
61 }
62
63 void wxDC::CocoaUnwindStackAndLoseFocus()
64 {
65     wxCocoaDCStack::Node *ourNode=sm_cocoaDCStack.Find(this);
66     if(ourNode)
67     {
68         wxCocoaDCStack::Node *node=sm_cocoaDCStack.GetFirst();
69         for(;node!=ourNode; node=sm_cocoaDCStack.GetFirst())
70         {
71             wxDC *dc = node->GetData();
72             wxASSERT(dc);
73             wxASSERT(dc!=this);
74             if(!dc->CocoaUnlockFocus())
75             {
76                 wxFAIL_MSG("Unable to unlock focus on higher-level DC!");
77             }
78             sm_cocoaDCStack.DeleteNode(node);
79         }
80         wxASSERT(node==ourNode);
81         wxASSERT(ourNode->GetData() == this);
82         ourNode->GetData()->CocoaUnlockFocus();
83         sm_cocoaDCStack.DeleteNode(ourNode);
84     }
85 }
86
87 bool wxDC::CocoaUnwindStackAndTakeFocus()
88 {
89     wxCocoaDCStack::Node *node=sm_cocoaDCStack.GetFirst();
90     for(;node;node = sm_cocoaDCStack.GetFirst())
91     {
92         wxDC *dc = node->GetData();
93         wxASSERT(dc);
94         // If we're on the stack, then it's unwound enough and we have focus
95         if(dc==this)
96             return true;
97         // If unable to unlockFocus (e.g. wxPaintDC) stop here
98         if(!dc->CocoaUnlockFocus())
99             break;
100         sm_cocoaDCStack.DeleteNode(node);
101     }
102     return CocoaLockFocus();
103 }
104
105 wxDC::wxDC(void)
106 {
107     m_cocoaFlipped = false;
108     m_cocoaHeight = 0.0;
109 }
110
111 wxDC::~wxDC(void)
112 {
113 }
114
115 bool wxDC::CocoaLockFocus()
116 {
117     return false;
118 }
119
120 bool wxDC::CocoaUnlockFocus()
121 {
122     return false;
123 }
124
125 void wxDC::CocoaApplyTransformations()
126 {
127     // This transform flips the graphics since wxDC uses top-left origin
128     if(!m_cocoaFlipped)
129     {
130         // The transform is auto released
131         NSAffineTransform *transform = [NSAffineTransform transform];
132         /*  x' = 1x + 0y + 0
133             y' = 0x + -1y + window's height
134         */
135         NSAffineTransformStruct matrix = {
136             1,  0
137         ,   0, -1
138         ,   0, m_cocoaHeight
139         };
140         [transform setTransformStruct: matrix];
141         // Apply the transform 
142         [transform concat];
143     }
144     // TODO: Apply scaling transformation
145 }
146
147 void wxDC::DoDrawRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
148 {
149     if(!CocoaTakeFocus()) return;
150     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,width,height)];
151     [m_textForegroundColour.GetNSColor() set];
152     [bezpath stroke];
153     [m_brush.GetNSColor() set];
154     [bezpath fill];
155 }
156
157 void wxDC::DoDrawLine(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2)
158 {
159     if(!CocoaTakeFocus()) return;
160     NSBezierPath *bezpath = [NSBezierPath bezierPath];
161     [bezpath moveToPoint:NSMakePoint(x1,y1)];
162     [bezpath lineToPoint:NSMakePoint(x2,y2)];
163
164     [m_textForegroundColour.GetNSColor() set];
165     [bezpath stroke];
166 }
167
168 void wxDC::DoGetTextExtent(const wxString& text, wxCoord *x, wxCoord *y, wxCoord *descent, wxCoord *externalLeading, wxFont *theFont) const
169 {
170     wxAutoNSAutoreleasePool pool;
171 // FIXME: Cache this so it can be used for DoDrawText
172     wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, "Text system has not been initialized.  BAD PROGRAMMER!");
173     NSAttributedString *attributedString = [[NSAttributedString alloc]
174             initWithString:[NSString stringWithCString:text.c_str()]];
175     [sm_cocoaNSTextStorage setAttributedString:attributedString];
176     [attributedString release];
177
178     NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
179     NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
180     if(x)
181         *x=(int)usedRect.size.width;
182     if(y)
183         *y=(int)usedRect.size.height;
184     if(descent)
185         *descent=0;
186     if(externalLeading)
187         *externalLeading=0;
188 }
189
190 void wxDC::DoDrawText(const wxString& text, wxCoord x, wxCoord y)
191 {
192     if(!CocoaTakeFocus()) return;
193     wxASSERT_MSG(sm_cocoaNSTextStorage && sm_cocoaNSLayoutManager && sm_cocoaNSTextContainer, "Text system has not been initialized.  BAD PROGRAMMER!");
194     NSAttributedString *attributedString = [[NSAttributedString alloc]
195             initWithString:[NSString stringWithCString:text.c_str()]];
196     [sm_cocoaNSTextStorage setAttributedString:attributedString];
197     [attributedString release];
198
199     // Set the color (and later font) attributes
200     NSColor *fgColor = m_textForegroundColour.GetNSColor();
201     NSColor *bgColor = m_textBackgroundColour.GetNSColor();
202     if(!fgColor)
203         fgColor = [NSColor clearColor];
204     if(!bgColor)
205         bgColor = [NSColor clearColor];
206     NSDictionary *attrDict = [[NSDictionary alloc] initWithObjectsAndKeys:
207             fgColor, NSForegroundColorAttributeName,
208             bgColor, NSBackgroundColorAttributeName,
209             nil];
210     [sm_cocoaNSTextStorage addAttributes: attrDict range:NSMakeRange(0,[sm_cocoaNSTextStorage length])];
211     [attrDict release];
212
213     NSRange glyphRange = [sm_cocoaNSLayoutManager glyphRangeForTextContainer:sm_cocoaNSTextContainer];
214     NSRect usedRect = [sm_cocoaNSLayoutManager usedRectForTextContainer:sm_cocoaNSTextContainer];
215     // NOTE: We'll crash trying to get the location of glyphAtIndex:0 if
216     // there is no length or we don't start at zero
217     if(!glyphRange.length)
218         return;
219     wxASSERT_MSG(glyphRange.location==0,"glyphRange must begin at zero");
220
221     NSAffineTransform *transform = [NSAffineTransform transform];
222     [transform translateXBy:x yBy:y];
223
224     NSAffineTransform *flipTransform = [NSAffineTransform transform];
225     /*  x' = 1x + 0y + 0
226         y' = 0x + -1y + window's height
227     */
228     NSAffineTransformStruct matrix = {
229         1,  0
230     ,   0, -1
231     ,   0, usedRect.size.height
232     };
233     [flipTransform setTransformStruct: matrix];
234
235     NSGraphicsContext *context = [NSGraphicsContext currentContext];
236     [context saveGraphicsState];
237     [transform concat];
238     [flipTransform concat];
239     #if 0
240     // Draw+fill a rectangle so we can see where the shit is supposed to be.
241     wxLogDebug("(%f,%f) (%fx%f)",usedRect.origin.x,usedRect.origin.y,usedRect.size.width,usedRect.size.height);
242     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(0,0,usedRect.size.width,usedRect.size.height)];
243     [[NSColor blackColor] set];
244     [bezpath stroke];
245     [[NSColor blueColor] set];
246     [bezpath fill];
247     #endif
248
249     NSPoint layoutLocation = [sm_cocoaNSLayoutManager locationForGlyphAtIndex:0];
250     layoutLocation.x = 0.0;
251     layoutLocation.y *= -1.0;
252     layoutLocation.y += [[sm_cocoaNSLayoutManager typesetter] baselineOffsetInLayoutManager:sm_cocoaNSLayoutManager glyphIndex:0];
253     if(m_backgroundMode==wxSOLID)
254         [sm_cocoaNSLayoutManager drawBackgroundForGlyphRange:glyphRange  atPoint:NSZeroPoint];
255     [sm_cocoaNSLayoutManager drawGlyphsForGlyphRange:glyphRange  atPoint:layoutLocation];
256
257     [context restoreGraphicsState];
258 }
259
260 // wxDCBase functions
261 int wxDCBase::DeviceToLogicalX(int x) const
262 {
263     return x;
264 }
265
266 int wxDCBase::DeviceToLogicalY(int y) const
267 {
268     return y;
269 }
270
271 int wxDCBase::DeviceToLogicalXRel(int x) const
272 {
273     return x;
274 }
275
276 int wxDCBase::DeviceToLogicalYRel(int y) const
277 {
278     return y;
279 }
280
281 int wxDCBase::LogicalToDeviceX(int x) const
282 {
283     return x;
284 }
285
286 int wxDCBase::LogicalToDeviceY(int y) const
287 {
288     return y;
289 }
290
291 int wxDCBase::LogicalToDeviceXRel(int x) const
292 {
293     return x;
294 }
295
296 int wxDCBase::LogicalToDeviceYRel(int y) const
297 {
298     return y;
299 }
300
301 ///////////////////////////////////////////////////////////////////////////
302 // cut here, the rest is stubs
303 ///////////////////////////////////////////////////////////////////////////
304
305 //-----------------------------------------------------------------------------
306 // constants
307 //-----------------------------------------------------------------------------
308
309 #define mm2inches               0.0393700787402
310 #define inches2mm               25.4
311 #define mm2twips                56.6929133859
312 #define twips2mm                0.0176388888889
313 #define mm2pt                   2.83464566929
314 #define pt2mm                   0.352777777778
315
316 //-----------------------------------------------------------------------------
317 // wxDC
318 //-----------------------------------------------------------------------------
319
320 void wxDC::DoDrawIcon( const wxIcon &WXUNUSED(icon), int WXUNUSED(x), int WXUNUSED(y) )
321 {
322 };
323
324 void wxDC::DoDrawPoint( int x, int y ) 
325
326 };
327
328 void wxDC::DoDrawPolygon( int, wxPoint *, int, int, int)
329 {
330 };
331
332 void wxDC::DoDrawLines( int, wxPoint *, int, int )
333 {
334 }
335
336 int wxDC::GetDepth() const
337 {
338     return 0;
339 }
340
341 wxSize wxDC::GetPPI() const
342 {
343     return wxSize(0,0);
344 }
345
346 bool wxDC::CanGetTextExtent() const
347 {
348     return false;
349 }
350
351 wxCoord wxDC::GetCharHeight() const
352 {
353     return 0;
354 }
355
356 wxCoord wxDC::GetCharWidth() const
357 {
358     return 0;
359 }
360
361 bool wxDC::CanDrawBitmap() const
362 {
363     return true;
364 }
365
366 bool wxDC::DoGetPixel(wxCoord x, wxCoord y, wxColour *col) const
367 {
368     return false;
369 }
370
371 void wxDC::DoDrawArc(wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, wxCoord xc, wxCoord yc)
372 {
373 }
374     
375 void wxDC::SetPen(const wxPen& pen)
376 {
377 }
378
379 void wxDC::SetBrush(const wxBrush& brush)
380 {
381     m_brush = brush;
382 }
383
384 void wxDC::DoSetClippingRegionAsRegion(const wxRegion& region)
385 {
386 }
387
388 void wxDC::DoSetClippingRegion(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
389 {
390 }
391
392 void wxDC::DestroyClippingRegion()
393 {
394 }
395
396 void wxDC::DoDrawRoundedRectangle(wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius)
397 {
398 }
399
400 void wxDC::DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y, double angle)
401 {
402 }
403
404 void wxDC::DoDrawEllipticArc(wxCoord x, wxCoord y, wxCoord w, wxCoord h, double sa, double ea)
405 {
406 }
407
408 void wxDC::DoDrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height)
409 {
410 }
411
412 void wxDC::DoDrawBitmap(const wxBitmap &bmp, wxCoord x, wxCoord y, bool useMask)
413 {
414     if(!CocoaTakeFocus()) return;
415     if(!bmp.Ok())
416         return;
417
418 #if 0
419     // Draw a rect so we can see where it's supposed to be
420     wxLogDebug("image at (%d,%d) size %dx%d",x,y,bmp.GetWidth(),bmp.GetHeight());
421     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:NSMakeRect(x,y,bmp.GetWidth(),bmp.GetHeight())];
422     [[NSColor blackColor] set];
423     [bezpath stroke];
424     [[NSColor blueColor] set];
425     [bezpath fill];
426 #endif // 0
427
428     NSAffineTransform *transform = [NSAffineTransform transform];
429     [transform translateXBy:x yBy:y];
430
431     NSAffineTransform *flipTransform = [NSAffineTransform transform];
432     /*  x' = 1x + 0y + 0
433         y' = 0x + -1y + window's height
434     */
435     NSAffineTransformStruct matrix = {
436         1,  0
437     ,   0, -1
438     ,   0, bmp.GetHeight()
439     };
440     [flipTransform setTransformStruct: matrix];
441
442     NSGraphicsContext *context = [NSGraphicsContext currentContext];
443     [context saveGraphicsState];
444     [transform concat];
445     [flipTransform concat];
446
447     NSImage *nsimage = [[NSImage alloc]
448             initWithSize:NSMakeSize(bmp.GetWidth(), bmp.GetHeight())];
449     [nsimage addRepresentation: const_cast<wxBitmap&>(bmp).GetNSBitmapImageRep()];
450     [nsimage drawAtPoint: NSMakePoint(0,0)
451         fromRect: NSMakeRect(0.0,0.0,bmp.GetWidth(),bmp.GetHeight())
452         operation: NSCompositeCopy
453         fraction: 1.0];
454         
455     [nsimage release];
456     [context restoreGraphicsState];
457 }
458
459 bool wxDC::DoFloodFill(wxCoord x, wxCoord y, const wxColour& col, int style)
460 {
461     return false;
462 }
463
464 void wxDC::DoCrossHair(wxCoord x, wxCoord y)
465 {
466 }
467
468
469 bool wxDC::DoBlit(wxCoord xdest, wxCoord ydest, wxCoord width, wxCoord height, wxDC *source, wxCoord xsrc, wxCoord ysrc, int rop, bool useMask , wxCoord xsrcMask, wxCoord ysrcMask)
470 {
471     if(!CocoaTakeFocus()) return false;
472     if(!source) return false;
473     return source->CocoaDoBlitOnFocusedDC(xdest,ydest,width,height,
474         xsrc, ysrc, rop, useMask, xsrcMask, ysrcMask);
475 }
476
477 bool wxDC::CocoaDoBlitOnFocusedDC(wxCoord xdest, wxCoord ydest,
478     wxCoord width, wxCoord height, wxCoord xsrc, wxCoord ysrc,
479     int logicalFunc, bool useMask, wxCoord xsrcMask, wxCoord ysrcMask)
480 {
481     return false;
482 }
483
484 void wxDC::DoGetSize( int* width, int* height ) const
485 {
486   *width = m_maxX-m_minX;
487   *height = m_maxY-m_minY;
488 };
489
490 void wxDC::DoGetSizeMM( int* width, int* height ) const
491 {
492   int w = 0;
493   int h = 0;
494   GetSize( &w, &h );
495 };
496
497 void wxDC::SetTextForeground( const wxColour &col )
498 {
499   if (!Ok()) return;
500   m_textForegroundColour = col;
501 };
502
503 void wxDC::SetTextBackground( const wxColour &col )
504 {
505   if (!Ok()) return;
506   m_textBackgroundColour = col;
507 };
508
509 void wxDC::Clear()
510 {
511 }
512
513 void wxDC::SetBackground(const wxBrush& brush)
514 {
515     m_backgroundBrush = brush;
516 }
517
518 void wxDC::SetPalette(const wxPalette&)
519 {
520 }
521
522 void wxDC::SetLogicalFunction(int)
523 {
524 }
525
526
527 void wxDC::SetMapMode( int mode )
528 {
529   switch (mode) 
530   {
531     case wxMM_TWIPS:
532       break;
533     case wxMM_POINTS:
534       break;
535     case wxMM_METRIC:
536       break;
537     case wxMM_LOMETRIC:
538       break;
539     default:
540     case wxMM_TEXT:
541       SetLogicalScale( 1.0, 1.0 );
542       break;
543   };
544   if (mode != wxMM_TEXT)
545   {
546   };
547 };
548
549 void wxDC::SetUserScale( double x, double y )
550 {
551   // allow negative ? -> no
552   m_userScaleX = x;
553   m_userScaleY = y;
554   ComputeScaleAndOrigin();
555 };
556
557 void wxDC::SetLogicalScale( double x, double y )
558 {
559   // allow negative ?
560   m_logicalScaleX = x;
561   m_logicalScaleY = y;
562   ComputeScaleAndOrigin();
563 };
564
565 void wxDC::SetLogicalOrigin( wxCoord x, wxCoord y )
566 {
567   m_logicalOriginX = x * m_signX;   // is this still correct ?
568   m_logicalOriginY = y * m_signY;
569   ComputeScaleAndOrigin();
570 };
571
572 void wxDC::SetDeviceOrigin( wxCoord x, wxCoord y )
573 {
574   ComputeScaleAndOrigin();
575 };
576
577 void wxDC::SetAxisOrientation( bool xLeftRight, bool yBottomUp )
578 {
579   m_signX = (xLeftRight ?  1 : -1);
580   m_signY = (yBottomUp  ? -1 :  1);
581   ComputeScaleAndOrigin();
582 };
583
584 void wxDC::ComputeScaleAndOrigin(void)
585 {
586   // CMB: copy scale to see if it changes
587   double origScaleX = m_scaleX;
588   double origScaleY = m_scaleY;
589
590   m_scaleX = m_logicalScaleX * m_userScaleX;
591   m_scaleY = m_logicalScaleY * m_userScaleY;
592
593   // CMB: if scale has changed call SetPen to recalulate the line width 
594   if (m_scaleX != origScaleX || m_scaleY != origScaleY)
595   {
596     // this is a bit artificial, but we need to force wxDC to think
597     // the pen has changed
598     wxPen* pen = & GetPen();
599     wxPen tempPen;
600     m_pen = tempPen;
601     SetPen(* pen);
602   }
603 };
604