mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathnsterm.m
10254 lines (8493 loc) · 305 KB
/
nsterm.m
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* NeXT/Open/GNUstep / macOS communication module. -*- coding: utf-8 -*-
Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2021 Free Software
Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
/*
Originally by Carl Edman
Updated by Christian Limpach ([email protected])
OpenStep/Rhapsody port by Scott Bender ([email protected])
macOS/Aqua port by Christophe de Dinechin ([email protected])
GNUstep port and post-20 update by Adrian Robert ([email protected])
*/
/* This should be the first include, as it may set up #defines affecting
interpretation of even the system includes. */
#include <config.h>
#include <fcntl.h>
#include <math.h>
#include <pthread.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <c-ctype.h>
#include <c-strcase.h>
#include <ftoastr.h>
#include "lisp.h"
#include "blockinput.h"
#include "sysselect.h"
#include "nsterm.h"
#include "systime.h"
#include "character.h"
#include "xwidget.h"
#include "fontset.h"
#include "composite.h"
#include "ccl.h"
#include "termhooks.h"
#include "termchar.h"
#include "menu.h"
#include "window.h"
#include "keyboard.h"
#include "buffer.h"
#include "font.h"
#include "pdumper.h"
#ifdef NS_IMPL_GNUSTEP
#include "process.h"
#endif
#ifdef NS_IMPL_COCOA
#include "macfont.h"
#include <Carbon/Carbon.h>
#endif
#ifdef NS_DRAW_TO_BUFFER
#include <IOSurface/IOSurface.h>
#endif
static EmacsMenu *dockMenu;
#ifdef NS_IMPL_COCOA
static EmacsMenu *mainMenu;
#endif
/* ==========================================================================
NSTRACE, Trace support.
========================================================================== */
#if NSTRACE_ENABLED
/* The following use "volatile" since they can be accessed from
parallel threads. */
volatile int nstrace_num = 0;
volatile int nstrace_depth = 0;
/* When 0, no trace is emitted. This is used by NSTRACE_WHEN and
NSTRACE_UNLESS to silence functions called.
TODO: This should really be a thread-local variable, to avoid that
a function with disabled trace thread silence trace output in
another. However, in practice this seldom is a problem. */
volatile int nstrace_enabled_global = 1;
/* Called when nstrace_enabled goes out of scope. */
void nstrace_leave(int * pointer_to_nstrace_enabled)
{
if (*pointer_to_nstrace_enabled)
{
--nstrace_depth;
}
}
/* Called when nstrace_saved_enabled_global goes out of scope. */
void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
{
nstrace_enabled_global = *pointer_to_saved_enabled_global;
}
char const * nstrace_fullscreen_type_name (int fs_type)
{
switch (fs_type)
{
case -1: return "-1";
case FULLSCREEN_NONE: return "FULLSCREEN_NONE";
case FULLSCREEN_WIDTH: return "FULLSCREEN_WIDTH";
case FULLSCREEN_HEIGHT: return "FULLSCREEN_HEIGHT";
case FULLSCREEN_BOTH: return "FULLSCREEN_BOTH";
case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
default: return "FULLSCREEN_?????";
}
}
#endif
/* ==========================================================================
NSColor, EmacsColor category.
========================================================================== */
@implementation NSColor (EmacsColor)
+ (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
blue:(CGFloat)blue alpha:(CGFloat)alpha
{
#if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
if (ns_use_srgb_colorspace
&& NSAppKitVersionNumber >= NSAppKitVersionNumber10_7)
return [NSColor colorWithSRGBRed: red
green: green
blue: blue
alpha: alpha];
#endif
return [NSColor colorWithCalibratedRed: red
green: green
blue: blue
alpha: alpha];
}
- (NSColor *)colorUsingDefaultColorSpace
{
#if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
if (ns_use_srgb_colorspace
&& NSAppKitVersionNumber >= NSAppKitVersionNumber10_7)
return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
#endif
return [self colorUsingColorSpace: [NSColorSpace deviceRGBColorSpace]];
}
@end
/* ==========================================================================
Local declarations
========================================================================== */
/* Convert a symbol indexed with an NSxxx value to a value as defined
in keyboard.c (lispy_function_key). I hope this is a correct way
of doing things... */
static unsigned convert_ns_to_X_keysym[] =
{
NSHomeFunctionKey, 0x50,
NSLeftArrowFunctionKey, 0x51,
NSUpArrowFunctionKey, 0x52,
NSRightArrowFunctionKey, 0x53,
NSDownArrowFunctionKey, 0x54,
NSPageUpFunctionKey, 0x55,
NSPageDownFunctionKey, 0x56,
NSEndFunctionKey, 0x57,
NSBeginFunctionKey, 0x58,
NSSelectFunctionKey, 0x60,
NSPrintFunctionKey, 0x61,
NSClearLineFunctionKey, 0x0B,
NSExecuteFunctionKey, 0x62,
NSInsertFunctionKey, 0x63,
NSUndoFunctionKey, 0x65,
NSRedoFunctionKey, 0x66,
NSMenuFunctionKey, 0x67,
NSFindFunctionKey, 0x68,
NSHelpFunctionKey, 0x6A,
NSBreakFunctionKey, 0x6B,
NSF1FunctionKey, 0xBE,
NSF2FunctionKey, 0xBF,
NSF3FunctionKey, 0xC0,
NSF4FunctionKey, 0xC1,
NSF5FunctionKey, 0xC2,
NSF6FunctionKey, 0xC3,
NSF7FunctionKey, 0xC4,
NSF8FunctionKey, 0xC5,
NSF9FunctionKey, 0xC6,
NSF10FunctionKey, 0xC7,
NSF11FunctionKey, 0xC8,
NSF12FunctionKey, 0xC9,
NSF13FunctionKey, 0xCA,
NSF14FunctionKey, 0xCB,
NSF15FunctionKey, 0xCC,
NSF16FunctionKey, 0xCD,
NSF17FunctionKey, 0xCE,
NSF18FunctionKey, 0xCF,
NSF19FunctionKey, 0xD0,
NSF20FunctionKey, 0xD1,
NSF21FunctionKey, 0xD2,
NSF22FunctionKey, 0xD3,
NSF23FunctionKey, 0xD4,
NSF24FunctionKey, 0xD5,
NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
NSTabCharacter, 0x09,
0x19, 0x09, /* left tab->regular since pass shift */
NSCarriageReturnCharacter, 0x0D,
NSNewlineCharacter, 0x0D,
NSEnterCharacter, 0x8D,
0x41|NSEventModifierFlagNumericPad, 0xAE, /* KP_Decimal */
0x43|NSEventModifierFlagNumericPad, 0xAA, /* KP_Multiply */
0x45|NSEventModifierFlagNumericPad, 0xAB, /* KP_Add */
0x4B|NSEventModifierFlagNumericPad, 0xAF, /* KP_Divide */
0x4E|NSEventModifierFlagNumericPad, 0xAD, /* KP_Subtract */
0x51|NSEventModifierFlagNumericPad, 0xBD, /* KP_Equal */
0x52|NSEventModifierFlagNumericPad, 0xB0, /* KP_0 */
0x53|NSEventModifierFlagNumericPad, 0xB1, /* KP_1 */
0x54|NSEventModifierFlagNumericPad, 0xB2, /* KP_2 */
0x55|NSEventModifierFlagNumericPad, 0xB3, /* KP_3 */
0x56|NSEventModifierFlagNumericPad, 0xB4, /* KP_4 */
0x57|NSEventModifierFlagNumericPad, 0xB5, /* KP_5 */
0x58|NSEventModifierFlagNumericPad, 0xB6, /* KP_6 */
0x59|NSEventModifierFlagNumericPad, 0xB7, /* KP_7 */
0x5B|NSEventModifierFlagNumericPad, 0xB8, /* KP_8 */
0x5C|NSEventModifierFlagNumericPad, 0xB9, /* KP_9 */
0x1B, 0x1B /* escape */
};
/* On macOS picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
the maximum font size to NOT antialias. On GNUstep there is currently
no way to control this behavior. */
float ns_antialias_threshold;
NSArray *ns_send_types = 0, *ns_return_types = 0;
static NSArray *ns_drag_types = 0;
NSString *ns_app_name = @"Emacs"; /* default changed later */
/* Display variables */
struct ns_display_info *x_display_list; /* Chain of existing displays */
long context_menu_value = 0;
/* display update */
static struct frame *ns_updating_frame;
#if !defined (NS_DRAW_TO_BUFFER) || MAC_OS_X_VERSION_MIN_REQUIRED < 101400
static NSView *focus_view = NULL;
#endif
static int ns_window_num = 0;
static BOOL gsaved = NO;
static BOOL ns_fake_keydown = NO;
#ifdef NS_IMPL_COCOA
static BOOL ns_menu_bar_is_hidden = NO;
#endif
/* static int debug_lock = 0; */
/* event loop */
static BOOL send_appdefined = YES;
#define NO_APPDEFINED_DATA (-8)
static int last_appdefined_event_data = NO_APPDEFINED_DATA;
static NSTimer *timed_entry = 0;
static NSTimer *scroll_repeat_entry = nil;
static fd_set select_readfds, select_writefds;
enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
static int select_nfds = 0, select_valid = 0;
static struct timespec select_timeout = { 0, 0 };
static int selfds[2] = { -1, -1 };
static pthread_mutex_t select_mutex;
static NSAutoreleasePool *outerpool;
static struct input_event *emacs_event = NULL;
static struct input_event *q_event_ptr = NULL;
static int n_emacs_events_pending = 0;
static NSMutableArray *ns_pending_files, *ns_pending_service_names,
*ns_pending_service_args;
static BOOL ns_do_open_file = NO;
static BOOL ns_last_use_native_fullscreen;
/* Non-zero means that a HELP_EVENT has been generated since Emacs
start. */
static BOOL any_help_event_p = NO;
static struct {
struct input_event *q;
int nr, cap;
} hold_event_q = {
NULL, 0, 0
};
/* Convert modifiers in a NeXTstep event to emacs style modifiers. */
#define NS_FUNCTION_KEY_MASK 0x800000
#define NSLeftControlKeyMask (0x000001 | NSEventModifierFlagControl)
#define NSRightControlKeyMask (0x002000 | NSEventModifierFlagControl)
#define NSLeftCommandKeyMask (0x000008 | NSEventModifierFlagCommand)
#define NSRightCommandKeyMask (0x000010 | NSEventModifierFlagCommand)
#define NSLeftAlternateKeyMask (0x000020 | NSEventModifierFlagOption)
#define NSRightAlternateKeyMask (0x000040 | NSEventModifierFlagOption)
/* MODIFIER if a symbol; otherwise its property KIND, if a symbol. */
static Lisp_Object
mod_of_kind (Lisp_Object modifier, Lisp_Object kind)
{
if (SYMBOLP (modifier))
return modifier;
else
{
Lisp_Object val = Fplist_get (modifier, kind);
return SYMBOLP (val) ? val : Qnil;
}
}
static unsigned int
ev_modifiers_helper (unsigned int flags, unsigned int left_mask,
unsigned int right_mask, unsigned int either_mask,
Lisp_Object left_modifier, Lisp_Object right_modifier)
{
unsigned int modifiers = 0;
if (flags & either_mask)
{
BOOL left_key = (flags & left_mask) == left_mask;
BOOL right_key = (flags & right_mask) == right_mask
&& ! EQ (right_modifier, Qleft);
if (right_key)
modifiers |= parse_solitary_modifier (right_modifier);
/* GNUstep (and possibly macOS in certain circumstances) doesn't
differentiate between the left and right keys, so if we can't
identify which key it is, we use the left key setting. */
if (left_key || ! right_key)
modifiers |= parse_solitary_modifier (left_modifier);
}
return modifiers;
}
#define EV_MODIFIERS2(flags, kind) \
(((flags & NSEventModifierFlagHelp) ? \
hyper_modifier : 0) \
| ((flags & NSEventModifierFlagShift) ? \
shift_modifier : 0) \
| ((flags & NS_FUNCTION_KEY_MASK) \
? parse_solitary_modifier (mod_of_kind (ns_function_modifier, \
kind)) \
: 0) \
| ev_modifiers_helper (flags, NSLeftControlKeyMask, \
NSRightControlKeyMask, \
NSEventModifierFlagControl, \
mod_of_kind (ns_control_modifier, kind), \
mod_of_kind (ns_right_control_modifier, \
kind)) \
| ev_modifiers_helper (flags, NSLeftCommandKeyMask, \
NSRightCommandKeyMask, \
NSEventModifierFlagCommand, \
mod_of_kind (ns_command_modifier, kind), \
mod_of_kind (ns_right_command_modifier, \
kind)) \
| ev_modifiers_helper (flags, NSLeftAlternateKeyMask, \
NSRightAlternateKeyMask, \
NSEventModifierFlagOption, \
mod_of_kind (ns_alternate_modifier, kind), \
mod_of_kind (ns_right_alternate_modifier, \
kind)))
#define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags], QCmouse)
#define EV_UDMODIFIERS(e) \
((([e type] == NSEventTypeLeftMouseDown) ? down_modifier : 0) \
| (([e type] == NSEventTypeRightMouseDown) ? down_modifier : 0) \
| (([e type] == NSEventTypeOtherMouseDown) ? down_modifier : 0) \
| (([e type] == NSEventTypeLeftMouseDragged) ? down_modifier : 0) \
| (([e type] == NSEventTypeRightMouseDragged) ? down_modifier : 0) \
| (([e type] == NSEventTypeOtherMouseDragged) ? down_modifier : 0) \
| (([e type] == NSEventTypeLeftMouseUp) ? up_modifier : 0) \
| (([e type] == NSEventTypeRightMouseUp) ? up_modifier : 0) \
| (([e type] == NSEventTypeOtherMouseUp) ? up_modifier : 0))
#define EV_BUTTON(e) \
((([e type] == NSEventTypeLeftMouseDown) || ([e type] == NSEventTypeLeftMouseUp)) ? 0 : \
(([e type] == NSEventTypeRightMouseDown) || ([e type] == NSEventTypeRightMouseUp)) ? 2 : \
[e buttonNumber] - 1)
/* Convert the time field to a timestamp in milliseconds. */
#define EV_TIMESTAMP(e) ([e timestamp] * 1000)
/* This is a piece of code which is common to all the event handling
methods. Maybe it should even be a function. */
#define EV_TRAILER(e) \
{ \
XSETFRAME (emacs_event->frame_or_window, emacsframe); \
EV_TRAILER2 (e); \
}
#define EV_TRAILER2(e) \
{ \
if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
if (q_event_ptr) \
{ \
Lisp_Object tem = Vinhibit_quit; \
Vinhibit_quit = Qt; \
n_emacs_events_pending++; \
kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
Vinhibit_quit = tem; \
} \
else \
hold_event (emacs_event); \
EVENT_INIT (*emacs_event); \
ns_send_appdefined (-1); \
}
/* These flags will be OR'd or XOR'd with the NSWindow's styleMask
property depending on what we're doing. */
#define FRAME_DECORATED_FLAGS (NSWindowStyleMaskTitled \
| NSWindowStyleMaskResizable \
| NSWindowStyleMaskMiniaturizable \
| NSWindowStyleMaskClosable)
#define FRAME_UNDECORATED_FLAGS NSWindowStyleMaskBorderless
/* TODO: Get rid of need for these forward declarations. */
static void ns_condemn_scroll_bars (struct frame *f);
static void ns_judge_scroll_bars (struct frame *f);
/* ==========================================================================
Utilities
========================================================================== */
void
ns_init_events (struct input_event *ev)
{
EVENT_INIT (*ev);
emacs_event = ev;
}
void
ns_finish_events (void)
{
emacs_event = NULL;
}
static void
hold_event (struct input_event *event)
{
if (hold_event_q.nr == hold_event_q.cap)
{
if (hold_event_q.cap == 0) hold_event_q.cap = 10;
else hold_event_q.cap *= 2;
hold_event_q.q =
xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
}
hold_event_q.q[hold_event_q.nr++] = *event;
/* Make sure ns_read_socket is called, i.e. we have input. */
raise (SIGIO);
send_appdefined = YES;
}
static Lisp_Object
append2 (Lisp_Object list, Lisp_Object item)
/* --------------------------------------------------------------------------
Utility to append to a list
-------------------------------------------------------------------------- */
{
return nconc2 (list, list (item));
}
const char *
ns_etc_directory (void)
/* If running as a self-contained app bundle, return as a string the
filename of the etc directory, if present; else nil. */
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *resourceDir = [bundle resourcePath];
NSString *resourcePath;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
{
if (isDir) return [resourcePath UTF8String];
}
return NULL;
}
const char *
ns_exec_path (void)
/* If running as a self-contained app bundle, return as a path string
the filenames of the libexec and bin directories, ie libexec:bin.
Otherwise, return nil.
Normally, Emacs does not add its own bin/ directory to the PATH.
However, a self-contained NS build has a different layout, with
bin/ and libexec/ subdirectories in the directory that contains
Emacs.app itself.
We put libexec first, because init_callproc_1 uses the first
element to initialize exec-directory. An alternative would be
for init_callproc to check for invocation-directory/libexec.
*/
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *resourceDir = [bundle resourcePath];
NSString *binDir = [bundle bundlePath];
NSString *resourcePath, *resourcePaths;
NSRange range;
NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths;
NSEnumerator *pathEnum;
BOOL isDir;
range = [resourceDir rangeOfString: @"Contents"];
if (range.location != NSNotFound)
{
binDir = [binDir stringByAppendingPathComponent: @"Contents"];
#ifdef NS_IMPL_COCOA
binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
#endif
}
paths = [binDir stringsByAppendingPaths:
[NSArray arrayWithObjects: @"libexec", @"bin", nil]];
pathEnum = [paths objectEnumerator];
resourcePaths = @"";
while ((resourcePath = [pathEnum nextObject]))
{
if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
if (isDir)
{
if ([resourcePaths length] > 0)
resourcePaths
= [resourcePaths stringByAppendingString: pathSeparator];
resourcePaths
= [resourcePaths stringByAppendingString: resourcePath];
}
}
if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
return NULL;
}
const char *
ns_load_path (void)
/* If running as a self-contained app bundle, return as a path string
the filenames of the site-lisp and lisp directories.
Ie, site-lisp:lisp. Otherwise, return nil. */
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *resourceDir = [bundle resourcePath];
NSString *resourcePath, *resourcePaths;
NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
NSArray *paths = [resourceDir stringsByAppendingPaths:
[NSArray arrayWithObjects:
@"site-lisp", @"lisp", nil]];
NSEnumerator *pathEnum = [paths objectEnumerator];
resourcePaths = @"";
/* Hack to skip site-lisp. */
if (no_site_lisp) resourcePath = [pathEnum nextObject];
while ((resourcePath = [pathEnum nextObject]))
{
if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
if (isDir)
{
if ([resourcePaths length] > 0)
resourcePaths
= [resourcePaths stringByAppendingString: pathSeparator];
resourcePaths
= [resourcePaths stringByAppendingString: resourcePath];
}
}
if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
return NULL;
}
void
ns_init_locale (void)
/* macOS doesn't set any environment variables for the locale when run
from the GUI. Get the locale from the OS and set LANG. */
{
NSLocale *locale = [NSLocale currentLocale];
NSTRACE ("ns_init_locale");
@try
{
/* It seems macOS should probably use UTF-8 everywhere.
'localeIdentifier' does not specify the encoding, and I can't
find any way to get the OS to tell us which encoding to use,
so hard-code '.UTF-8'. */
NSString *localeID = [NSString stringWithFormat:@"%@.UTF-8",
[locale localeIdentifier]];
/* Set LANG to locale, but not if LANG is already set. */
setenv("LANG", [localeID UTF8String], 0);
}
@catch (NSException *e)
{
NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
}
}
void
ns_release_object (void *obj)
/* --------------------------------------------------------------------------
Release an object (callable from C)
-------------------------------------------------------------------------- */
{
[(id)obj release];
}
void
ns_retain_object (void *obj)
/* --------------------------------------------------------------------------
Retain an object (callable from C)
-------------------------------------------------------------------------- */
{
[(id)obj retain];
}
void *
ns_alloc_autorelease_pool (void)
/* --------------------------------------------------------------------------
Allocate a pool for temporary objects (callable from C)
-------------------------------------------------------------------------- */
{
return [[NSAutoreleasePool alloc] init];
}
void
ns_release_autorelease_pool (void *pool)
/* --------------------------------------------------------------------------
Free a pool and temporary objects it refers to (callable from C)
-------------------------------------------------------------------------- */
{
ns_release_object (pool);
}
static BOOL
ns_menu_bar_should_be_hidden (void)
/* True, if the menu bar should be hidden. */
{
return !NILP (ns_auto_hide_menu_bar)
&& [NSApp respondsToSelector:@selector(setPresentationOptions:)];
}
struct EmacsMargins
{
CGFloat top;
CGFloat bottom;
CGFloat left;
CGFloat right;
};
static struct EmacsMargins
ns_screen_margins (NSScreen *screen)
/* The parts of SCREEN used by the operating system. */
{
NSTRACE ("ns_screen_margins");
struct EmacsMargins margins;
NSRect screenFrame = [screen frame];
NSRect screenVisibleFrame = [screen visibleFrame];
/* Sometimes, visibleFrame isn't up-to-date with respect to a hidden
menu bar, check this explicitly. */
if (ns_menu_bar_should_be_hidden())
{
margins.top = 0;
}
else
{
CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
+ screenVisibleFrame.size.height);
margins.top = frameTop - visibleFrameTop;
}
{
CGFloat frameRight = screenFrame.origin.x + screenFrame.size.width;
CGFloat visibleFrameRight = (screenVisibleFrame.origin.x
+ screenVisibleFrame.size.width);
margins.right = frameRight - visibleFrameRight;
}
margins.bottom = screenVisibleFrame.origin.y - screenFrame.origin.y;
margins.left = screenVisibleFrame.origin.x - screenFrame.origin.x;
NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
margins.left,
margins.right,
margins.top,
margins.bottom);
return margins;
}
/* A screen margin between 1 and DOCK_IGNORE_LIMIT (inclusive) is
assumed to contain a hidden dock. macOS currently use 4 pixels for
this, however, to be future compatible, a larger value is used. */
#define DOCK_IGNORE_LIMIT 6
static struct EmacsMargins
ns_screen_margins_ignoring_hidden_dock (NSScreen *screen)
/* The parts of SCREEN used by the operating system, excluding the parts
reserved for a hidden dock. */
{
NSTRACE ("ns_screen_margins_ignoring_hidden_dock");
struct EmacsMargins margins = ns_screen_margins(screen);
/* macOS (currently) reserved 4 pixels along the edge where a hidden
dock is located. Unfortunately, it's not possible to find the
location and information about if the dock is hidden. Instead,
it is assumed that if the margin of an edge is less than
DOCK_IGNORE_LIMIT, it contains a hidden dock. */
if (margins.left <= DOCK_IGNORE_LIMIT)
{
margins.left = 0;
}
if (margins.right <= DOCK_IGNORE_LIMIT)
{
margins.right = 0;
}
if (margins.top <= DOCK_IGNORE_LIMIT)
{
margins.top = 0;
}
/* Note: This doesn't occur in current versions of macOS, but
included for completeness and future compatibility. */
if (margins.bottom <= DOCK_IGNORE_LIMIT)
{
margins.bottom = 0;
}
NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
margins.left,
margins.right,
margins.top,
margins.bottom);
return margins;
}
static CGFloat
ns_menu_bar_height (NSScreen *screen)
/* The height of the menu bar, if visible.
Note: Don't use this when fullscreen is enabled -- the screen
sometimes includes, sometimes excludes the menu bar area. */
{
struct EmacsMargins margins = ns_screen_margins(screen);
CGFloat res = margins.top;
NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
return res;
}
/* Get the frame rect, in system coordinates, of the parent window or,
if there is no parent window, the main screen. */
static inline NSRect
ns_parent_window_rect (struct frame *f)
{
NSRect parentRect;
if (FRAME_PARENT_FRAME (f) != NULL)
{
EmacsView *parentView = FRAME_NS_VIEW (FRAME_PARENT_FRAME (f));
parentRect = [parentView convertRect:[parentView frame]
toView:nil];
parentRect = [[parentView window] convertRectToScreen:parentRect];
}
else
parentRect = [[[NSScreen screens] objectAtIndex:0] frame];
return parentRect;
}
/* Calculate system coordinates of the left and top of the parent
window or, if there is no parent window, the main screen. */
#define NS_PARENT_WINDOW_LEFT_POS(f) NSMinX (ns_parent_window_rect (f))
#define NS_PARENT_WINDOW_TOP_POS(f) NSMaxY (ns_parent_window_rect (f))
static NSRect
ns_row_rect (struct window *w, struct glyph_row *row,
enum glyph_row_area area)
/* Get the row as an NSRect. */
{
NSRect rect;
int window_x, window_y, window_width;
window_box (w, area, &window_x, &window_y, &window_width, 0);
rect.origin.x = window_x;
rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
rect.origin.y = max (rect.origin.y, window_y);
rect.size.width = window_width;
rect.size.height = row->visible_height;
return rect;
}
double
ns_frame_scale_factor (struct frame *f)
{
#if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > 1060
return [[FRAME_NS_VIEW (f) window] backingScaleFactor];
#else
return [[FRAME_NS_VIEW (f) window] userSpaceScaleFactor];
#endif
}
/* ==========================================================================
Focus (clipping) and screen update
========================================================================== */
//
// Window constraining
// -------------------
//
// To ensure that the windows are not placed under the menu bar, they
// are typically moved by the call-back constrainFrameRect. However,
// by overriding it, it's possible to inhibit this, leaving the window
// in it's original position.
//
// It's possible to hide the menu bar. However, technically, it's only
// possible to hide it when the application is active. To ensure that
// this work properly, the menu bar and window constraining are
// deferred until the application becomes active.
//
// Even though it's not possible to manually move a window above the
// top of the screen, it is allowed if it's done programmatically,
// when the menu is hidden. This allows the editable area to cover the
// full screen height.
//
// Test cases
// ----------
//
// Use the following extra files:
//
// init.el:
// ;; Hide menu and place frame slightly above the top of the screen.
// (setq ns-auto-hide-menu-bar t)
// (set-frame-position (selected-frame) 0 -20)
//
// Test 1:
//
// emacs -Q -l init.el
//
// Result: No menu bar, and the title bar should be above the screen.
//
// Test 2:
//
// emacs -Q
//
// Result: Menu bar visible, frame placed immediately below the menu.
//
static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
{
NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
NSTRACE_ARG_RECT (frameRect));
// --------------------
// Collect information about the screen the frame is covering.
//
NSArray *screens = [NSScreen screens];
NSUInteger nr_screens = [screens count];
int i;
// The height of the menu bar, if present in any screen the frame is
// displayed in.
int menu_bar_height = 0;
// A rectangle covering all the screen the frame is displayed in.
NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
for (i = 0; i < nr_screens; ++i )
{
NSScreen *s = [screens objectAtIndex: i];
NSRect scrRect = [s frame];
NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
i, NSTRACE_ARG_RECT (scrRect));
if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
{
multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
if (!isFullscreen)
{
CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
}
}
}
NSTRACE_RECT ("multiscreenRect", multiscreenRect);
NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
if (multiscreenRect.size.width == 0
|| multiscreenRect.size.height == 0)
{
// Failed to find any monitor, give up.
NSTRACE_MSG ("multiscreenRect empty");
NSTRACE_RETURN_RECT (frameRect);
return frameRect;
}
// --------------------
// Find a suitable placement.
//
if (ns_menu_bar_should_be_hidden())
{
// When the menu bar is hidden, the user may place part of the
// frame above the top of the screen, for example to hide the
// title bar.
//
// Hence, keep the original position.
}
else
{
// Ensure that the frame is below the menu bar, or below the top
// of the screen.
//
// This assume that the menu bar is placed at the top in the
// rectangle that covers the monitors. (It doesn't have to be,
// but if it's not it's hard to do anything useful.)
CGFloat topOfWorkArea = (multiscreenRect.origin.y
+ multiscreenRect.size.height
- menu_bar_height);
CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
if (topOfFrame > topOfWorkArea)
{
frameRect.origin.y -= topOfFrame - topOfWorkArea;