File: cocoatabcontrols.pas

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (970 lines) | stat: -rw-r--r-- 27,492 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
{ $Id: $}
{                  --------------------------------------------
                  cocoatabcontrols.pas  -  Cocoa internal classes
                  --------------------------------------------

 This unit contains the private classhierarchy for the Cocoa implemetations

 *****************************************************************************
  This file is part of the Lazarus Component Library (LCL)

  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************
}
unit CocoaTabControls;

{$mode objfpc}{$H+}
{$modeswitch objectivec1}
{$modeswitch objectivec2}
{$interfaces corba}
{$include cocoadefines.inc}

interface

uses
  Types, Classes, SysUtils,
  MacOSAll, CocoaAll, CocoaUtils, CocoaPrivate, CocoaCallback, CocoaConst,
  CocoaCustomControl;

type

  ITabControlCallback = interface(ICommonCallback)
    function shouldSelectTabViewItem(aTabIndex: Integer): Boolean;
    procedure willSelectTabViewItem(aTabIndex: Integer);
    procedure didSelectTabViewItem(aTabIndex: Integer);
  end;

  { TCocoaTabPage }

  TCocoaTabPage = objcclass(NSTabViewItem)
  public
    callback: ICommonCallback;
    function lclGetCallback: ICommonCallback; override;
    procedure lclClearCallback; override;
    function lclFrame: TRect; override;
    function lclClientFrame: TRect; override;
    procedure setLabel(label__: NSString); override;
  end;

  { TCocoaTabControl }

  TCocoaTabControl = objcclass(NSTabView, NSTabViewDelegateProtocol)
  private
    prevarr  : NSButton;
    nextarr  : NSButton;

  public
    triggeringByLCL: Boolean;

    { various indexes in fulltabs }
    currentIndex : Integer;     // index of the current tab
    visibleLeftIndex: Integer;  // index shown in TabView on the left
    leftKeepAmount: Integer;    // left tab amount to keep, equals currentIndex-visibleLeftIndex

    procedure attachAllTabs; message 'attachAllTabs';
    procedure updateVariousIndex; message 'updateVariousIndex';

  public
    callback: ITabControlCallback;

    fulltabs : NSMutableArray;  // the full list of NSTabViewItems
    lclEnabled: Boolean;
    // cocoa
    class function alloc: id; override;
    procedure dealloc; override;
    procedure setFrame(aframe: NSRect); override;
    procedure setTabViewType(newValue: NSTabViewType); override;
    // lcl
    function lclIsEnabled: Boolean; override;
    procedure lclSetEnabled(AEnabled: Boolean); override;
    function lclGetCallback: ICommonCallback; override;
    procedure lclClearCallback; override;
    function lclClientFrame: TRect; override;
    function lclGetFrameToLayoutDelta: TRect; override;
    // NSTabViewDelegateProtocol
    function tabView_shouldSelectTabViewItem(tabView: NSTabView; tabViewItem: NSTabViewItem): Boolean; message 'tabView:shouldSelectTabViewItem:';
    procedure tabView_willSelectTabViewItem(tabView: NSTabView; tabViewItem: NSTabViewItem); message 'tabView:willSelectTabViewItem:';
    procedure tabView_didSelectTabViewItem(tabView: NSTabView; tabViewItem: NSTabViewItem); message 'tabView:didSelectTabViewItem:';
    procedure tabViewDidChangeNumberOfTabViewItems(TabView: NSTabView); message 'tabViewDidChangeNumberOfTabViewItems:';
    // mouse events
    procedure mouseDown(event: NSEvent); override;
    procedure mouseUp(event: NSEvent); override;
    procedure rightMouseDown(event: NSEvent); override;
    procedure rightMouseUp(event: NSEvent); override;
    procedure rightMouseDragged(event: NSEvent); override;
    procedure otherMouseDown(event: NSEvent); override;
    procedure otherMouseUp(event: NSEvent); override;
    procedure otherMouseDragged(event: NSEvent); override;
    procedure mouseDragged(event: NSEvent); override;
    procedure mouseMoved(event: NSEvent); override;
    // lcl
    procedure exttabInsertTabViewItem_atIndex(lTabPage: NSTabViewItem; index: integer);
      message 'exttabInsertTabViewItem:atIndex:';
    procedure exttabMoveTabViewItem_toIndex(lTabPage: NSTabViewItem; NewIndex: integer);
      message 'exttabMoveTabViewItem:toIndex:';
    procedure exttabRemoveTabViewItem(removedTabPage: NSTabViewItem);
      message 'exttabRemoveTabViewItem:';
    function exttabIndexOfTabViewItem(lTabPage: NSTabViewItem): NSInteger;
      message 'exttabIndexOfTabViewItem:';
    procedure extselectTabViewItemAtIndex(index: NSInteger);
      message 'extselectTabViewItemAtIndex:';
  end;

  { TCocoaTabControlArrow }

  TCocoaTabControlArrow = objcclass(NSButton)
  private
    _tabControl: TCocoaTabControl;
    _lastMouseDownTime: NSDate;
  private
    function shouldSpeedUp(): Boolean; message 'shouldSpeedUp';
  public
    procedure mouseDown(theEvent: NSEvent); override;
    procedure prevClick(sender: id); message 'prevClick:';
    procedure nextClick(sender: id); message 'nextClick:';
  end;

  { TCocoaTabPageView }

  TCocoaTabPageView = objcclass(TCocoaCustomControl)
  public
    tabView: TCocoaTabControl;
    tabPage: TCocoaTabPage;
    procedure setFrame(arect: NSRect); override;
  end;

function IndexOfTab(ahost: TCocoaTabControl; atab: NSTabViewItem): Integer;

// Hack: The function attempts to determine the tabs view
// if the view is found it would return its frame rect in LCL coordinates
// if the view cannot be determinted, the function returns false
// This is implemented as ObjC method, because "prevarr" and "nextarr"
// are private methods.
// It's unknown, if it's safe to cache the result, so the search is performed
// everytime
function GetTabsRect(tabs: TCocoaTabControl; var r: TRect): Boolean;

procedure UpdateTabAndArrowVisibility(aview: TCocoaTabControl);

implementation

function GetTabsRect(tabs: TCocoaTabControl; var r: TRect): Boolean;
var
  i  : integer;
  sv : NSView;
  f  : NSRect;
begin
  Result:=Assigned(tabs);
  if not Result then Exit;

  for i:=0 to Integer(tabs.subviews.count)-1 do
  begin
    sv:=NSView(tabs.subviews.objectAtIndex(i));
    if not Assigned(sv)
       or (sv = tabs.nextarr)
       or (sv = tabs.prevarr)
       or (sv.isKindOfClass(TCocoaTabPageView))
    then Continue;

    f := sv.frame;
    if tabs.isFlipped then
      r := NSRectToRect( f )
    else
      NSToLCLRect( f, tabs.frame.size.height, r );
    Result := true;
    Exit;
  end;
  Result:=false;
end;

function AllocArrowButton(tabControl:TCocoaTabControl; isPrev:Boolean): NSButton;
var
  btn : TCocoaTabControlArrow;
begin
  btn := TCocoaTabControlArrow.alloc.initWithFrame(NSZeroRect);
  btn._tabControl := tabControl;
  btn.setBezelStyle(NSRegularSquareBezelStyle);
  btn.setButtonType(NSMomentaryLightButton);

  if isPrev then
    btn.setTitle( NSSTR_TABCONTROL_PREV_ARROW )
  else
    btn.setTitle( NSSTR_TABCONTROL_NEXT_ARROW );

  {$ifdef BOOLFIX}
  btn.setBordered_(Ord(false));
  {$else}
  btn.setBordered(false);
  {$endif}
  btn.sizeToFit();
  if not isPrev then btn.setAutoresizingMask(NSViewMinXMargin);
  Result:=btn;
end;

const
  arrow_hofs = 12;
  arrow_vofs = 10;

procedure PlaceButton(isPrev: Boolean; abtn: NSButton; dst: NSTabView);
var
  org: NSPoint;
begin
  if not assigned(abtn) then Exit;

  if dst.tabViewType = NSTopTabsBezelBorder then
    org.y := arrow_vofs
  else
    org.y := dst.frame.size.height - abtn.frame.size.height - arrow_vofs;

  if isPrev then
    org.x := arrow_hofs
  else
    org.x := dst.frame.size.width - abtn.frame.size.width - arrow_hofs;

  abtn.setFrameOrigin(org);
end;


procedure AllocPrevNext(aview: TCocoaTabControl);
begin
  aview.prevarr := AllocArrowButton(aview, true);
  aview.addSubview(aview.prevarr);
  aview.prevarr.setTarget(aview.prevarr);
  aview.prevarr.setAction( ObjCSelector('prevClick:') );

  aview.nextarr := AllocArrowButton(aview, false);
  aview.addSubview(aview.nextarr);
  aview.nextarr.setTarget(aview.nextarr);
  aview.nextarr.setAction( ObjCSelector('nextClick:') );
end;

// by fine-tuning the algorithm, guarantee that the `selectedTabViewItem`
// remains unchanged when TabControl is not wide enough,
// so as to avoid a lot of useless `tabView_didSelectTabViewItem` events are triggered
// (Resize TabControl, Add Tab, Remove Tab、Prev Tab、Next Tab)
// 1. change `leftmost` to `currentIndex`, and change the meaning to the index of
//    the currently selected Tab (mapping selectedTabViewItem)
// 2. currentIndex remains unchanged in ReviseTabs()
// 3. selectedTabViewItem is no longer removed and then added,
//    but always remains in tabViewItems,
//    thus tabView_didSelectTabViewItem is not triggered anymore
// 4. taking currentIndex as the intermediate value,
//    try to keep the tabs on the right side, and then the left side
procedure ReviseTabs(aview: TCocoaTabControl; out ShowPrev,ShowNext: Boolean);
var
  minw: double;
  i: integer;
  arr: NSArray;
  vi : NSTabViewItem;
  sz : NSSize;
  x,y: integer;
  lw  : double;
  tbext : double;
  lwid : array of double;
  xd  : double;
  j : integer;
  ofs : integer;
  frw: double;
  v : NSView;

  tryToKeepIndex : NSInteger;
  leftIndex : Integer;
begin
  ShowPrev := false;
  ShowNext := false;

  // ReviseTabs() supports tpTop and tpBottom only
  if (aview.tabViewType=NSLeftTabsBezelBorder) or (aview.tabViewType=NSRightTabsBezelBorder) then exit;

  if aview.fulltabs.count=0 then exit;

  tryToKeepIndex:= aview.currentIndex - aview.leftKeepAmount;
  if tryToKeepIndex < 0 then
    tryToKeepIndex:= 0;

  // AttachAllTabs() has been modified to not remove the selectedTabViewItem first,
  // and no longer trigger tabView_didSelectTabViewItem
  // regardless of whether aview.fulltabs.count>aview.tabViewItems.count,
  // tabs need to be attached because the order may have been adjusted.
  aview.attachAllTabs;

  minw := aview.minimumSize.width;
  if (minw<aview.frame.size.width) then Exit;

  arr := aview.tabViewItems;

  lw := 0;
  SetLength(lwid, arr.count);
  for i := 0 to Integer(arr.count) - 1 do
  begin
    vi := NSTabViewItem( arr.objectAtIndex(i) );
    sz := vi.sizeOfLabel(false);
    lw := lw + sz.width;
    lwid[i] := sz.width;
  end;

  tbext := (minw - lw) / arr.count;
  for i:=0 to length(lwid)-1 do
    lwid[i] := lwid[i] + tbext;

  frw := aview.frame.size.width;
  frw := frw - ((arrow_hofs + aview.nextarr.frame.size.width) * 2);
  if frw<0 then frw := 0;

  ofs := aview.currentIndex;
  if ofs>=length(lwid) then ofs:=length(lwid)-1;
  if (ofs < 0) then ofs:=0;

  // 1. keep the current tab first
  //    selectedTabViewItem is guaranteed to remain in the updated tabViewItems
  xd := lwid[ofs];

  // 2. try to keep the tabs on the left side, the amount not exceed leftKeepAmount,
  //    in order to fix the position of currentTab.
  leftIndex := ofs;
  for i := ofs-1 downto tryToKeepIndex do begin
    if xd + lwid[i] > frw then begin
      ShowPrev := true;
      Break;
    end;
    xd := xd + lwid[i];
    leftIndex := i;
  end;

  // 3. try to keep the tabs on the right side until it's not wide enough
  //    and ShowNext if necessary
  for i := ofs+1 to length(lwid)-1 do begin
    if xd + lwid[i] > frw then begin
      for j:=length(lwid)-1 downto i do
        aview.removeTabViewItem( arr.objectAtIndex(j));
      ShowNext := true;
      Break;
    end;
    xd := xd + lwid[i];
  end;

  // 4. try to keep the tabs on the left side until it's not wide enough
  //    and ShowPrev if necessary
  if leftIndex <= 0 then
    exit;
  for i := leftIndex-1 downto 0 do begin
    if xd + lwid[i] > frw then begin
      ShowPrev := true;
      Break;
    end;
    xd := xd + lwid[i];
    leftIndex := i;
  end;
  for j:=leftIndex-1 downto 0 do
    aview.removeTabViewItem( arr.objectAtIndex(j));
end;

procedure UpdateTabAndArrowVisibility(aview: TCocoaTabControl);
var
  showNext : Boolean;
  showPrev : Boolean;
  responder: NSResponder;
begin
  responder:= nil;
  if Assigned(aview.window) then
    responder:= aview.window.firstResponder;

  ReviseTabs(aview, showPrev, showNExt);
  aview.updateVariousIndex;
  if Assigned(aview.prevarr) then
  begin
    PlaceButton(true, aview.prevarr, aview);
    {$ifdef BOOLFIX}
    aview.prevarr.setHidden_(Ord(not showPrev));
    {$else}
    aview.prevarr.setHidden(not showPrev);
    {$endif}
  end;
  if Assigned(aview.nextarr) then
  begin
    PlaceButton(false, aview.nextarr, aview);
    {$ifdef BOOLFIX}
    aview.nextarr.setHidden_(Ord(not showNext));
    {$else}
    aview.nextarr.setHidden(not showNext);
    {$endif}
  end;

  if Assigned(aview.window) then begin
    if Assigned(responder) and (responder<>aview.window.firstResponder) then
      aview.window.makeFirstResponder(responder);
  end;
end;

function IndexOfTab(ahost: TCocoaTabControl; atab: NSTabViewItem): Integer;
var
  idx : NSUInteger;
begin
  idx := ahost.fulltabs.indexOfObject(atab);
  if idx=NSUIntegerMax then Result:=-1
  else begin
    if idx>MaxInt then Result:=-1
    else Result:=Integer(idx);
  end;
end;

{ TCocoaTabPageView }

procedure TCocoaTabPageView.setFrame(arect: NSRect);
begin
  // It's possible for a tab page view to go in negative height.
  // However, automatic resizing flags (for whatever reason) prevent
  // TCocoaTabPageView to go into negative height (remaining at 0 pixels)
  // The code below makes sure that resizing is actually happening
  if Assigned(superView) and (superView.frame.size.height < arect.size.height) then
    arect.size.height := superView.frame.size.height;

  inherited setFrame(arect);
end;

{ TCocoaTabPage }

function TCocoaTabPage.lclGetCallback: ICommonCallback;
begin
  Result := callback;
end;

procedure TCocoaTabPage.lclClearCallback;
begin
  callback := nil;
end;

function TCocoaTabPage.lclFrame: TRect;
var
  svh: CGFloat;
  lParent: NSTabView;
begin
  lParent := tabView;
  if lParent <> nil then
  begin
    svh := lParent.contentRect.size.height;
    NSToLCLRect(lParent.contentRect, svh, Result);
  end
  else
  begin
    svh := tabView.frame.size.height;
    NSToLCLRect(tabView.contentRect, svh, Result);
  end;
  {$IFDEF COCOA_DEBUG_TABCONTROL}
  WriteLn('[TCocoaTabPage.lclFrame] '+dbgs(Result)+' '+NSStringToString(Self.label_));
  {$ENDIF}
end;

function TCocoaTabPage.lclClientFrame: TRect;
begin
  Result := lclFrame();
end;

procedure TCocoaTabPage.setLabel(label__: NSString);
begin
  inherited setLabel(label__);
  //todo: revise the parent labels
end;

{ TCocoaTabControl }

// by ensuring that selectedTabViewItem cannot be removed
// and tabView_didSelectTabViewItem is not triggered anymore
procedure TCocoaTabControl.attachAllTabs;
var
  i : integer;
  itm: NSTabViewItem;
begin
  // only selectedItem reserved
  for itm{%H-} in tabViewItems do begin
    if itm <> selectedTabViewItem then
      removeTabViewItem( itm );
  end;

  // insert all tabs in the order of fulltabs again
  i:= 0;
  for itm{%H-} in fulltabs do begin
    if itm <> selectedTabViewItem then
      insertTabViewItem_atIndex( itm, i );
    inc( i );
  end;
end;

procedure TCocoaTabControl.updateVariousIndex;
begin
  if numberOfTabViewItems > 0 then begin
    visibleLeftIndex:= fulltabs.indexOfObject( tabViewItemAtIndex(0) );
    leftKeepAmount:= currentIndex - visibleLeftIndex;
  end else begin
    visibleLeftIndex:= -1;
    leftKeepAmount:= 0;
  end;
end;

class function TCocoaTabControl.alloc: id;
begin
  Result := inherited alloc;
  TCocoaTabControl(Result).fulltabs := NSMutableArray(NSMutableArray.alloc).init;
end;

procedure TCocoaTabControl.dealloc;
begin
  if Assigned(fulltabs) then begin
    fulltabs.release;
    fulltabs := nil;
  end;
  inherited dealloc;
end;

procedure TCocoaTabControl.setFrame(aframe: NSRect);
begin
  inherited setFrame(aframe);

  if not Assigned(nextarr) then
    AllocPrevNext( self );

  UpdateTabAndArrowVisibility(self);
end;

procedure TCocoaTabControl.setTabViewType(newValue: NSTabViewType);
begin
  Inherited;
  UpdateTabAndArrowVisibility(self);
end;

procedure TCocoaTabControl.extselectTabViewItemAtIndex( index:NSInteger );
var
  itm: NSTabViewItem;
  visibleIndex: NSInteger;
  oldKeepAmount: Integer;
begin
  if (index<0) or (index>=fulltabs.count) then Exit;

  itm:= NSTabViewItem( fulltabs.objectAtIndex(index) );
  visibleIndex:= indexOfTabViewItem( itm );
  if visibleIndex <> NSNotFound then begin
    inherited selectTabViewItemAtIndex( visibleIndex );
  end else begin
    oldKeepAmount:= leftKeepAmount;
    attachAllTabs;
    inherited selectTabViewItemAtIndex( index );
    leftKeepAmount:= oldKeepAmount;
    UpdateTabAndArrowVisibility( self );
  end;
end;

function TCocoaTabControl.lclIsEnabled: Boolean;
begin
  Result:=lclEnabled and ((Assigned(superview) and superview.lclIsEnabled) or not Assigned(superview));
end;

procedure TCocoaTabControl.lclSetEnabled(AEnabled: Boolean);
begin
  lclEnabled := AEnabled;
  inherited lclSetEnabled(AEnabled);
end;

function TCocoaTabControl.lclGetCallback: ICommonCallback;
begin
  Result := callback;
end;

procedure TCocoaTabControl.lclClearCallback;
begin
  callback := nil;
end;

function TCocoaTabControl.lclClientFrame: TRect;
var
  r : TRect;
  f : NSRect;
begin
  case tabViewType of
    NSNoTabsNoBorder:
    begin
      f := frame;
      f.origin.x := 0;
      f.origin.y := 0;
      Result := NSRectToRect( f );
    end;
  else
    if isFlipped then
      Result:=NSRectToRect( contentRect )
    else
      NSToLCLRect( contentRect, frame.size.height, Result );
  end;

  //if tabs are hidden, frame layout should not be taken into account
  //r:=lclGetFrameToLayoutDelta;
  //Types.OffsetRect(Result, -r.Left, -r.Top);
end;

function TCocoaTabControl.lclGetFrameToLayoutDelta: TRect;
begin
  case tabViewType of
    NSNoTabsNoBorder: begin
      Result.Left := 0;
      Result.Top := 0;
      Result.Bottom := 0;
      Result.Right := 0;
    end;
  else
    Result.Bottom := -4;
    Result.Top := 6;
    Result.Left := 7;
    Result.Right := -7;
  end;
end;

function TCocoaTabControl.tabView_shouldSelectTabViewItem(tabView: NSTabView;
  tabViewItem: NSTabViewItem): Boolean;
begin
  Result := True;
  if Assigned(callback) then
  begin
    Result:= callback.shouldSelectTabViewItem( IndexOfTab( self, tabViewItem) );
  end;
end;

procedure TCocoaTabControl.tabView_willSelectTabViewItem(tabView: NSTabView;
  tabViewItem: NSTabViewItem);
begin
  if Assigned(callback) then
  begin
    callback.willSelectTabViewItem( IndexOfTab( self, tabViewItem) );
  end;
end;

procedure TCocoaTabControl.tabView_didSelectTabViewItem(tabView: NSTabView;
  tabViewItem: NSTabViewItem);
begin
  //it's called together with "willSelect"

  if triggeringByLCL then
    exit;

  currentIndex:= IndexOfTab( self, tabViewItem );
  leftKeepAmount:= currentIndex - visibleLeftIndex;

  if Assigned(callback) then
  begin
    // Expected LCL Focus changing goes as following:
    //   First page becomes visible
    //   Then focus is switching to the control of the page
    // In Cocoa world, first "willSelect" runs,
    //  then "firstResponder" changes to Window
    //  then the views are reorded and the new View becomes a part
    //  of views chain (and attaches to the window
    //  the view is made "firstResponder"
    //  and finally "didSelect" is fired
    callback.didSelectTabViewItem( currentIndex );
  end;

  // The recent clean up, drove the workaround below unnecessary
  // (at least the problem is not observed)
  // The issue, is that the controls are being placed incorrectly, below
  // the actual height of the control. Refactoring, removed direct LCL bindings.
  // And it seemed to helped with returning invalid control bounds?!

  // Update the coordinates of all children of this tab
  // Fixes bug 31914: TPageControl problems with Cocoa
  {lTabView := tabViewItem.view.subViews.objectAtIndex(0);
  for i := 0 to lTabView.subViews.count-1 do
  begin
    lCurSubview := lTabView.subViews.objectAtIndex(i);
    lCurCallback := lCurSubview.lclGetCallback();
    if Assigned(lCurCallback) then
    begin
      lLCLControl := TWinControl(lCurCallback.GetTarget());
      lBounds := Classes.Bounds(lLCLControl.Left, lLCLControl.Top, lLCLControl.Width, lLCLControl.Height);
      lCurSubview.lclSetFrame(lBounds);
    end;
  end;}
end;

procedure TCocoaTabControl.tabViewDidChangeNumberOfTabViewItems(
  TabView: NSTabView);
begin

end;

procedure TCocoaTabControl.mouseDown(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited mouseDown(event);
    Exit;
  end;

  if not (Assigned(callback) and callback.MouseUpDownEvent(event, false, true)) then
  begin
    inherited mouseDown(event);

    if Assigned(callback) then
    begin
      callback.MouseUpDownEvent(event, True);
    end;
  end
end;

procedure TCocoaTabControl.mouseUp(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited mouseUp(event);
    Exit;
  end;

  if not Assigned(callback) or not callback.MouseUpDownEvent(event) then
    inherited mouseUp(event);
end;

procedure TCocoaTabControl.rightMouseDown(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited rightMouseDown(event);
    Exit;
  end;

  if not Assigned(callback) or not callback.MouseUpDownEvent(event) then
    inherited rightMouseDown(event);
end;

procedure TCocoaTabControl.rightMouseUp(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited rightMouseUp(event);
    Exit;
  end;

  if not Assigned(callback) or not callback.MouseUpDownEvent(event) then
    inherited rightMouseUp(event);
end;

procedure TCocoaTabControl.rightMouseDragged(event: NSEvent);
begin
  if not Assigned(callback) or not callback.MouseMove(event) then
    inherited rightMouseDragged(event);
end;

procedure TCocoaTabControl.otherMouseDown(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited otherMouseDown(event);
    Exit;
  end;

  if not Assigned(callback) or not callback.MouseUpDownEvent(event) then
    inherited otherMouseDown(event);
end;

procedure TCocoaTabControl.otherMouseUp(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited otherMouseUp(event);
    Exit;
  end;

  if not Assigned(callback) or not callback.MouseUpDownEvent(event) then
    inherited otherMouseUp(event);
end;

procedure TCocoaTabControl.otherMouseDragged(event: NSEvent);
begin
  if not Assigned(callback) or not callback.MouseMove(event) then
    inherited otherMouseDragged(event);
end;

procedure TCocoaTabControl.mouseDragged(event: NSEvent);
begin
  if not Assigned(callback) or not callback.MouseMove(event) then
    inherited mouseDragged(event);
end;

procedure TCocoaTabControl.mouseMoved(event: NSEvent);
var
  itm : NSTabViewItem;
begin
  itm := self.tabViewItemAtPoint( self.convertPoint_fromView(event.locationInWindow, nil ));
  if not Assigned(itm) then
  begin
    inherited mouseMoved(event);
    Exit;
  end;

  if Assigned(callback) then callback.MouseMove(event);
  inherited mouseMoved(event);
end;

procedure TCocoaTabControl.exttabMoveTabViewItem_toIndex(
  lTabPage: NSTabViewItem; NewIndex: integer);
var
  isMovingCurrentPage: Boolean;
  OldIndex: Integer;
begin
  if fulltabs.count=0 then
    Exit;

  OldIndex := exttabIndexOfTabViewItem( lTabPage );
  if OldIndex < 0 then
    Exit;

  if NewIndex > fulltabs.count then
    NewIndex:= fulltabs.count;

  isMovingCurrentPage := (OldIndex=currentIndex);

  fulltabs.removeObjectAtIndex( OldIndex );
  fulltabs.insertObject_atIndex( lTabPage, NewIndex );

  if isMovingCurrentPage then begin
    currentIndex:= NewIndex;
    leftKeepAmount:= currentIndex - visibleLeftIndex;
  end else begin
    if (OldIndex<currentIndex) and (NewIndex>=currentIndex) then
      dec( currentIndex )
    else if (OldIndex>currentIndex) and (NewIndex<=currentIndex) then
      inc( currentIndex );
  end;

  UpdateTabAndArrowVisibility( self );
end;

procedure TCocoaTabControl.exttabInsertTabViewItem_atIndex(
  lTabPage:NSTabViewItem; index:integer );
begin
  if index > fulltabs.count then
    index:= fulltabs.count;
  fulltabs.insertObject_atIndex( lTabPage, index );
  if index <= currentIndex then
    inc( currentIndex );

  UpdateTabAndArrowVisibility( self );
end;

procedure TCocoaTabControl.exttabRemoveTabViewItem( removedTabPage: NSTabViewItem );
var
  isRemovingCurrentPage: Boolean;
  removedIndex: Integer;
  nextTabPage: NSTabViewItem;
  prevTabPage: NSTabViewItem;
begin
  triggeringByLCL:= true;
  try
    removedIndex := exttabIndexOfTabViewItem( removedTabPage );
    if removedIndex < 0 then
      Exit;
    isRemovingCurrentPage:= (removedIndex=currentIndex);

    fulltabs.removeObjectAtIndex( removedIndex );

    if isRemovingCurrentPage then begin
      // removing current page
      attachAllTabs;
      if currentIndex = fulltabs.count then begin
        dec( currentIndex );
        removeTabViewItem( removedTabPage );
      end else begin
        selectTabViewItemAtIndex( currentIndex );
      end;
    end else begin
      // not removing current page
      // only fulltabs need to be changed,
      // visible TabView auto updated in UpdateTabAndArrowVisibility()
      if removedIndex < currentIndex then begin
        dec( currentIndex );
        if (removedIndex=visibleLeftIndex) and (removedIndex=currentIndex) then
          leftKeepAmount:= 0;
      end;
    end;

    UpdateTabAndArrowVisibility( self );
  finally
    triggeringByLCL:= false;
  end;
end;

function TCocoaTabControl.exttabIndexOfTabViewItem(lTabPage: NSTabViewItem
  ): NSInteger;
begin
  Result := fulltabs.indexOfObject(lTabPage);
  if Result = NSNotFound then
    Result:= -1;
end;

{ TCocoaTabControlArrow }

procedure TCocoaTabControlArrow.mouseDown(theEvent: NSEvent);
begin
  _lastMouseDownTime := NSDate.date;
  inherited;
  _lastMouseDownTime := nil;
end;

function TCocoaTabControlArrow.shouldSpeedUp(): Boolean;
const
  FOUR_MODIFIER_FLAGS = NSShiftKeyMask
                     or NSControlKeyMask
                     or NSAlternateKeyMask
                     or NSCommandKeyMask;
begin
  if (NSApp.currentEvent.modifierFlags and FOUR_MODIFIER_FLAGS)<>0 then
    exit(true);
  if NSDate.date.timeIntervalSinceDate(_lastMouseDownTime) > NSEvent.doubleClickInterval then
    exit(true);
  Result := false;
end;

procedure TCocoaTabControlArrow.prevClick(sender: id);
var
  currentIndex: Integer;
begin
  currentIndex := _tabControl.currentIndex;
  if currentIndex = 0 then
    Exit;
  if shouldSpeedUp() then
    currentIndex := 0
  else
    dec(currentIndex);
  _tabControl.extselectTabViewItemAtIndex(currentIndex);
end;

procedure TCocoaTabControlArrow.nextClick(sender: id);
var
  currentIndex: Integer;
begin
  currentIndex := _tabControl.currentIndex;
  if currentIndex = Integer(_tabControl.fulltabs.count) - 1 then
    Exit;
  if shouldSpeedUp() then
    currentIndex := Integer(_tabControl.fulltabs.count) - 1
  else
    inc(currentIndex);
  _tabControl.extselectTabViewItemAtIndex(currentIndex);
end;

end.