nsfns.m 95.1 KB
Newer Older
1
/* Functions for the NeXT/Open/GNUstep and macOS window system.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2019 Free Software
4
Foundation, Inc.
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
12 13 14 15 16 17 18

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
19
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
20

21
/*
22 23 24
Originally by Carl Edman
Updated by Christian Limpach (chris@nice.ch)
OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25
macOS/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 27 28
GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
*/

29
/* This should be the first include, as it may set up #defines affecting
30
   interpretation of even the system includes.  */
Dan Nicolaescu's avatar
Dan Nicolaescu committed
31
#include <config.h>
32

33
#include <math.h>
34
#include <c-strcase.h>
35

36 37 38 39
#include "lisp.h"
#include "blockinput.h"
#include "nsterm.h"
#include "window.h"
40
#include "character.h"
41 42 43 44 45 46
#include "buffer.h"
#include "keyboard.h"
#include "termhooks.h"
#include "fontset.h"
#include "font.h"

47 48
#ifdef NS_IMPL_COCOA
#include <IOKit/graphics/IOGraphicsLib.h>
49 50
#include "macfont.h"
#endif
51

52 53
#ifdef HAVE_NS

54
static EmacsTooltip *ns_tooltip = nil;
55

56
/* Static variables to handle AppleScript execution.  */
57 58
static Lisp_Object as_script, *as_result;
static int as_status;
59

60 61
static ptrdiff_t image_cache_refcount;

62
static struct ns_display_info *ns_display_info_for_name (Lisp_Object);
63

64 65 66 67 68 69
/* ==========================================================================

    Internal utility functions

   ========================================================================== */

70 71 72
/* Let the user specify a Nextstep display with a Lisp object.
   OBJECT may be nil, a frame or a terminal object.
   nil stands for the selected frame--or, if that is not a Nextstep frame,
73
   the first Nextstep display on the list.  */
74

75
static struct ns_display_info *
76
check_ns_display_info (Lisp_Object object)
77
{
78 79 80
  struct ns_display_info *dpyinfo = NULL;

  if (NILP (object))
81
    {
82 83 84
      struct frame *sf = XFRAME (selected_frame);

      if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
85
	dpyinfo = FRAME_DISPLAY_INFO (sf);
86
      else if (x_display_list != 0)
87
	dpyinfo = x_display_list;
88
      else
89
        error ("Nextstep windows are not in use or not initialized");
90
    }
91
  else if (TERMINALP (object))
92
    {
93
      struct terminal *t = decode_live_terminal (object);
94 95

      if (t->type != output_ns)
96
        error ("Terminal %d is not a Nextstep display", t->id);
97

98
      dpyinfo = t->display_info.ns;
99
    }
100 101
  else if (STRINGP (object))
    dpyinfo = ns_display_info_for_name (object);
102 103
  else
    {
Dmitry Antipov's avatar
Dmitry Antipov committed
104
      struct frame *f = decode_window_system_frame (object);
105
      dpyinfo = FRAME_DISPLAY_INFO (f);
106
    }
107 108

  return dpyinfo;
109 110 111 112 113 114 115 116 117
}


static id
ns_get_window (Lisp_Object maybeFrame)
{
  id view =nil, window =nil;

  if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
118
    maybeFrame = selected_frame; /* wrong_type_argument (Qframep, maybeFrame); */
119 120 121 122 123 124 125 126 127 128 129

  if (!NILP (maybeFrame))
    view = FRAME_NS_VIEW (XFRAME (maybeFrame));
  if (view) window =[view window];

  return window;
}


/* Return the X display structure for the display named NAME.
   Open a new connection if necessary.  */
130
static struct ns_display_info *
131
ns_display_info_for_name (Lisp_Object name)
132 133 134 135 136
{
  struct ns_display_info *dpyinfo;

  CHECK_STRING (name);

137 138 139
  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
    if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
      return dpyinfo;
140

Glenn Morris's avatar
Glenn Morris committed
141
  error ("Emacs for Nextstep does not yet support multi-display");
142

143 144
  Fx_open_connection (name, Qnil, Qnil);
  dpyinfo = x_display_list;
145 146

  if (dpyinfo == 0)
147
    error ("Display on %s not responding.\n", SDATA (name));
148 149 150 151

  return dpyinfo;
}

152 153 154
static NSString *
ns_filename_from_panel (NSSavePanel *panel)
{
155
#ifdef NS_IMPL_COCOA
156 157 158 159 160 161 162 163 164 165 166
  NSURL *url = [panel URL];
  NSString *str = [url path];
  return str;
#else
  return [panel filename];
#endif
}

static NSString *
ns_directory_from_panel (NSSavePanel *panel)
{
167
#ifdef NS_IMPL_COCOA
168 169 170 171 172 173 174
  NSURL *url = [panel directoryURL];
  NSString *str = [url path];
  return str;
#else
  return [panel directory];
#endif
}
175

176
#ifndef NS_IMPL_COCOA
177 178 179
static Lisp_Object
interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
/* --------------------------------------------------------------------------
180
   Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side.
181 182 183
   -------------------------------------------------------------------------- */
{
  int i, count;
184
  NSMenuItem *item;
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
  const char *name;
  Lisp_Object nameStr;
  unsigned short key;
  NSString *keys;
  Lisp_Object res;

  count = [menu numberOfItems];
  for (i = 0; i<count; i++)
    {
      item = [menu itemAtIndex: i];
      name = [[item title] UTF8String];
      if (!name) continue;

      nameStr = build_string (name);

      if ([item hasSubmenu])
        {
          old = interpret_services_menu ([item submenu],
                                        Fcons (nameStr, prefix), old);
        }
      else
        {
          keys = [item keyEquivalent];
          if (keys && [keys length] )
            {
              key = [keys characterAtIndex: 0];
211
              res = make_fixnum (key|super_modifier);
212 213 214 215 216 217 218 219 220 221 222 223 224
            }
          else
            {
              res = Qundefined;
            }
          old = Fcons (Fcons (res,
                            Freverse (Fcons (nameStr,
                                           prefix))),
                    old);
        }
    }
  return old;
}
225
#endif
226 227 228 229 230 231 232 233 234 235


/* ==========================================================================

    Frame parameter setters

   ========================================================================== */


static void
236
ns_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
237 238
{
  NSColor *col;
239
  EmacsCGFloat r, g, b, alpha;
240

Jan Djärv's avatar
Jan Djärv committed
241 242 243 244
  /* Must block_input, because ns_lisp_to_color does block/unblock_input
     which means that col may be deallocated in its unblock_input if there
     is user input, unless we also block_input.  */
  block_input ();
245 246 247
  if (ns_lisp_to_color (arg, &col))
    {
      store_frame_param (f, Qforeground_color, oldval);
Jan Djärv's avatar
Jan Djärv committed
248
      unblock_input ();
249 250 251 252 253 254 255
      error ("Unknown color");
    }

  [col retain];
  [f->output_data.ns->foreground_color release];
  f->output_data.ns->foreground_color = col;

256 257 258 259
  [col getRed: &r green: &g blue: &b alpha: &alpha];
  FRAME_FOREGROUND_PIXEL (f) =
    ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));

260 261 262
  if (FRAME_NS_VIEW (f))
    {
      update_face_from_frame_parameter (f, Qforeground_color, arg);
263
      /* recompute_basic_faces (f); */
264
      if (FRAME_VISIBLE_P (f))
Jan Djärv's avatar
Jan Djärv committed
265
        SET_FRAME_GARBAGED (f);
266
    }
Jan Djärv's avatar
Jan Djärv committed
267
  unblock_input ();
268 269 270 271
}


static void
272
ns_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
273 274 275 276
{
  struct face *face;
  NSColor *col;
  NSView *view = FRAME_NS_VIEW (f);
277
  EmacsCGFloat r, g, b, alpha;
278

Jan Djärv's avatar
Jan Djärv committed
279
  block_input ();
280 281 282
  if (ns_lisp_to_color (arg, &col))
    {
      store_frame_param (f, Qbackground_color, oldval);
Jan Djärv's avatar
Jan Djärv committed
283
      unblock_input ();
284 285 286
      error ("Unknown color");
    }

287 288 289
  /* Clear the frame; in some instances the NS-internal GC appears not
     to update, or it does update and cannot clear old text
     properly.  */
290 291 292 293 294 295
  if (FRAME_VISIBLE_P (f))
    ns_clear_frame (f);

  [col retain];
  [f->output_data.ns->background_color release];
  f->output_data.ns->background_color = col;
296 297 298 299 300

  [col getRed: &r green: &g blue: &b alpha: &alpha];
  FRAME_BACKGROUND_PIXEL (f) =
    ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));

301 302 303 304
  if (view != nil)
    {
      [[view window] setBackgroundColor: col];

305
      if (alpha != (EmacsCGFloat) 1.0)
306 307 308 309 310 311 312
          [[view window] setOpaque: NO];
      else
          [[view window] setOpaque: YES];

      face = FRAME_DEFAULT_FACE (f);
      if (face)
        {
313
          col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
314 315
          face->background = ns_index_color
            ([col colorWithAlphaComponent: alpha], f);
316 317 318 319 320

          update_face_from_frame_parameter (f, Qbackground_color, arg);
        }

      if (FRAME_VISIBLE_P (f))
Jan Djärv's avatar
Jan Djärv committed
321
        SET_FRAME_GARBAGED (f);
322
    }
Jan Djärv's avatar
Jan Djärv committed
323
  unblock_input ();
324 325 326 327
}


static void
328
ns_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
329 330 331
{
  NSColor *col;

Jan Djärv's avatar
Jan Djärv committed
332
  block_input ();
333 334 335
  if (ns_lisp_to_color (arg, &col))
    {
      store_frame_param (f, Qcursor_color, oldval);
Jan Djärv's avatar
Jan Djärv committed
336
      unblock_input ();
337 338 339
      error ("Unknown color");
    }

340 341
  [FRAME_CURSOR_COLOR (f) release];
  FRAME_CURSOR_COLOR (f) = [col retain];
342 343 344

  if (FRAME_VISIBLE_P (f))
    {
345 346
      gui_update_cursor (f, 0);
      gui_update_cursor (f, 1);
347 348
    }
  update_face_from_frame_parameter (f, Qcursor_color, arg);
Jan Djärv's avatar
Jan Djärv committed
349
  unblock_input ();
350 351
}

352

353
static void
354
ns_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
355 356
{
  NSView *view = FRAME_NS_VIEW (f);
357
  NSTRACE ("ns_set_icon_name");
358

359
  /* See if it's changed.  */
360 361 362 363 364
  if (STRINGP (arg))
    {
      if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
        return;
    }
365
  else if (!STRINGP (oldval) && NILP (oldval) == NILP (arg))
366 367
    return;

368
  fset_icon_name (f, arg);
369 370 371

  if (NILP (arg))
    {
372 373
      if (!NILP (f->title))
        arg = f->title;
374
      else
375
        /* Explicit name and no icon-name -> explicit_name.  */
376
        if (f->explicit_name)
377
          arg = f->name;
378 379
        else
          {
380 381 382
            /* No explicit name and no icon-name ->
               name has to be rebuild from icon_title_format.  */
            windows_or_buffers_changed = 62;
383 384 385 386 387
            return;
          }
    }

  /* Don't change the name if it's already NAME.  */
388 389
  if ([[view window] miniwindowTitle]
      && ([[[view window] miniwindowTitle]
390
             isEqualToString: [NSString stringWithUTF8String:
391
					  SSDATA (arg)]]))
392 393 394
    return;

  [[view window] setMiniwindowTitle:
395
        [NSString stringWithUTF8String: SSDATA (arg)]];
396 397 398
}

static void
Dmitry Antipov's avatar
Dmitry Antipov committed
399
ns_set_name_internal (struct frame *f, Lisp_Object name)
400
{
401 402
  Lisp_Object encoded_name, encoded_icon_name;
  NSString *str;
403 404
  NSView *view = FRAME_NS_VIEW (f);

405

406
  encoded_name = ENCODE_UTF_8 (name);
407

408
  str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
409

410

411 412 413
  /* Don't change the name if it's already NAME.  */
  if (! [[[view window] title] isEqualToString: str])
    [[view window] setTitle: str];
414

415
  if (!STRINGP (f->icon_name))
416
    encoded_icon_name = encoded_name;
417
  else
418
    encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
419

420
  str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
421

422 423
  if ([[view window] miniwindowTitle]
      && ! [[[view window] miniwindowTitle] isEqualToString: str])
424
    [[view window] setMiniwindowTitle: str];
425 426 427 428 429 430

}

static void
ns_set_name (struct frame *f, Lisp_Object name, int explicit)
{
431
  NSTRACE ("ns_set_name");
432 433 434 435 436 437 438 439

  /* Make sure that requests from lisp code override requests from
     Emacs redisplay code.  */
  if (explicit)
    {
      /* If we're switching from explicit to implicit, we had better
         update the mode lines and thereby update the title.  */
      if (f->explicit_name && NILP (name))
440
        update_mode_lines = 21;
441 442 443 444 445 446 447

      f->explicit_name = ! NILP (name);
    }
  else if (f->explicit_name)
    return;

  if (NILP (name))
448
    name = build_string ([ns_app_name UTF8String]);
449 450 451 452
  else
    CHECK_STRING (name);

  /* Don't change the name if it's already NAME.  */
453
  if (! NILP (Fstring_equal (name, f->name)))
454
    return;
455

456
  fset_name (f, name);
457

458
  /* Title overrides explicit name.  */
459 460
  if (! NILP (f->title))
    name = f->title;
461

462
  ns_set_name_internal (f, name);
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
static void
ns_set_represented_filename (struct frame *f)
{
  Lisp_Object filename, encoded_filename;
  Lisp_Object buf = XWINDOW (f->selected_window)->contents;
  NSAutoreleasePool *pool;
  NSString *fstr;
  NSView *view = FRAME_NS_VIEW (f);

  NSTRACE ("ns_set_represented_filename");

  if (f->explicit_name || ! NILP (f->title))
    return;

  block_input ();
  pool = [[NSAutoreleasePool alloc] init];
  filename = BVAR (XBUFFER (buf), filename);

  if (! NILP (filename))
    {
      encoded_filename = ENCODE_UTF_8 (filename);

      fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
      if (fstr == nil) fstr = @"";
    }
  else
    fstr = @"";

#ifdef NS_IMPL_COCOA
  /* Work around a bug observed on 10.3 and later where
     setTitleWithRepresentedFilename does not clear out previous state
     if given filename does not exist.  */
  if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
    [[view window] setRepresentedFilename: @""];
#endif
  [[view window] setRepresentedFilename: fstr];

  [pool release];
  unblock_input ();
}

506 507 508 509 510

/* This function should be called when the user's lisp code has
   specified a name for the frame; the name will override any set by the
   redisplay code.  */
static void
511
ns_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
512
{
513
  NSTRACE ("ns_explicitly_set_name");
514 515 516 517 518 519 520 521
  ns_set_name (f, arg, 1);
}


/* This function should be called by Emacs redisplay code to set the
   name; names set this way will never override names set by the user's
   lisp code.  */
void
522
ns_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
523
{
524
  NSTRACE ("ns_implicitly_set_name");
525

526
  if (ns_use_proxy_icon)
527
    ns_set_represented_filename (f);
528

529
  ns_set_name (f, arg, 0);
530 531 532 533
}


/* Change the title of frame F to NAME.
534
   If NAME is nil, use the frame name as the title.  */
535 536

static void
537
ns_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
538
{
539
  NSTRACE ("ns_set_title");
540
  /* Don't change the title if it's already NAME.  */
541
  if (EQ (name, f->title))
542 543
    return;

544
  update_mode_lines = 22;
545

546
  fset_title (f, name);
547 548

  if (NILP (name))
549
    name = f->name;
550 551 552 553
  else
    CHECK_STRING (name);

  ns_set_name_internal (f, name);
554 555 556
}

void
557
ns_set_doc_edited (void)
558 559
{
  NSAutoreleasePool *pool;
560 561 562 563
  Lisp_Object tail, frame;
  block_input ();
  pool = [[NSAutoreleasePool alloc] init];
  FOR_EACH_FRAME (tail, frame)
564
    {
565 566
      BOOL edited = NO;
      struct frame *f = XFRAME (frame);
567 568 569 570 571 572
      struct window *w;
      NSView *view;

      if (! FRAME_NS_P (f)) continue;
      w = XWINDOW (FRAME_SELECTED_WINDOW (f));
      view = FRAME_NS_VIEW (f);
573 574 575 576
      if (!MINI_WINDOW_P (w))
        edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
          ! NILP (Fbuffer_file_name (w->contents));
      [[view window] setDocumentEdited: edited];
577
    }
578 579 580

  [pool release];
  unblock_input ();
581 582 583
}


584
static void
585
ns_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
586 587 588 589 590
{
  int nlines;
  if (FRAME_MINIBUF_ONLY_P (f))
    return;

591 592
  if (TYPE_RANGED_FIXNUMP (int, value))
    nlines = XFIXNUM (value);
593 594 595 596 597 598 599
  else
    nlines = 0;

  FRAME_MENU_BAR_LINES (f) = 0;
  if (nlines)
    {
      FRAME_EXTERNAL_MENU_BAR (f) = 1;
600
      /* Does for all frames, whereas we just want for one frame
601
	 [NSMenu setMenuBarVisible: YES]; */
602 603 604 605 606
    }
  else
    {
      if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
        free_frame_menubar (f);
607
      /* [NSMenu setMenuBarVisible: NO]; */
608 609 610 611 612
      FRAME_EXTERNAL_MENU_BAR (f) = 0;
    }
}


613
/* toolbar support */
614
static void
615
ns_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
616
{
617
  /* Currently, when the tool bar changes state, the frame is resized.
618 619 620

     TODO: It would be better if this didn't occur when 1) the frame
     is full height or maximized or 2) when specified by
621
     `frame-inhibit-implied-resize'.  */
622 623
  int nlines;

624
  NSTRACE ("ns_set_tool_bar_lines");
625

626 627 628
  if (FRAME_MINIBUF_ONLY_P (f))
    return;

629 630
  if (RANGED_FIXNUMP (0, value, INT_MAX))
    nlines = XFIXNAT (value);
631 632 633 634 635 636 637 638 639 640 641 642 643 644
  else
    nlines = 0;

  if (nlines)
    {
      FRAME_EXTERNAL_TOOL_BAR (f) = 1;
      update_frame_tool_bar (f);
    }
  else
    {
      if (FRAME_EXTERNAL_TOOL_BAR (f))
        {
          free_frame_tool_bar (f);
          FRAME_EXTERNAL_TOOL_BAR (f) = 0;
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

          {
            EmacsView *view = FRAME_NS_VIEW (f);
            int fs_state = [view fullscreenState];

            if (fs_state == FULLSCREEN_MAXIMIZED)
              {
                [view setFSValue:FULLSCREEN_WIDTH];
              }
            else if (fs_state == FULLSCREEN_HEIGHT)
              {
                [view setFSValue:FULLSCREEN_NONE];
              }
          }
       }
660 661
    }

662 663 664 665 666 667 668 669 670 671 672 673
  {
    int inhibit
      = ((f->after_make_frame
	  && !f->tool_bar_resized
	  && (EQ (frame_inhibit_implied_resize, Qt)
	      || (CONSP (frame_inhibit_implied_resize)
		  && !NILP (Fmemq (Qtool_bar_lines,
				   frame_inhibit_implied_resize))))
	  && NILP (get_frame_param (f, Qfullscreen)))
	 ? 0
	 : 2);

674 675
    NSTRACE_MSG ("inhibit:%d", inhibit);

676 677 678
    frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
    adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
  }
679 680 681
}


682
static void
683
ns_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
684 685 686 687
{
  int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);

  CHECK_TYPE_RANGED_INTEGER (int, arg);
688
  f->internal_border_width = XFIXNUM (arg);
689
  if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
690
    f->internal_border_width = 0;
691 692 693 694

  if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
    return;

695
  if (FRAME_NATIVE_WINDOW (f) != 0)
696
    adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
697 698 699 700 701

  SET_FRAME_GARBAGED (f);
}


702
static void
703 704 705 706
ns_implicitly_set_icon_type (struct frame *f)
{
  Lisp_Object tem;
  EmacsView *view = FRAME_NS_VIEW (f);
707
  id image = nil;
708 709 710 711
  Lisp_Object chain, elt;
  NSAutoreleasePool *pool;
  BOOL setMini = YES;

712
  NSTRACE ("ns_implicitly_set_icon_type");
713

714
  block_input ();
715 716
  pool = [[NSAutoreleasePool alloc] init];
  if (f->output_data.ns->miniimage
717
      && [[NSString stringWithUTF8String: SSDATA (f->name)]
718 719 720
               isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
    {
      [pool release];
721
      unblock_input ();
722 723 724
      return;
    }

725
  tem = assq_no_quit (Qicon_type, f->param_alist);
726 727 728
  if (CONSP (tem) && ! NILP (XCDR (tem)))
    {
      [pool release];
729
      unblock_input ();
730 731 732 733
      return;
    }

  for (chain = Vns_icon_type_alist;
734
       image == nil && CONSP (chain);
735 736 737
       chain = XCDR (chain))
    {
      elt = XCAR (chain);
738
      /* Special case: t means go by file type.  */
739
      if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
740
        {
741
          NSString *str
742
	     = [NSString stringWithUTF8String: SSDATA (f->name)];
743 744 745 746 747 748
          if ([[NSFileManager defaultManager] fileExistsAtPath: str])
            image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
        }
      else if (CONSP (elt) &&
               STRINGP (XCAR (elt)) &&
               STRINGP (XCDR (elt)) &&
749
               fast_string_match (XCAR (elt), f->name) >= 0)
750 751 752 753 754
        {
          image = [EmacsImage allocInitFromFile: XCDR (elt)];
          if (image == nil)
            image = [[NSImage imageNamed:
                               [NSString stringWithUTF8String:
755
					    SSDATA (XCDR (elt))]] retain];
756 757 758 759 760 761 762 763 764 765 766 767 768
        }
    }

  if (image == nil)
    {
      image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
      setMini = NO;
    }

  [f->output_data.ns->miniimage release];
  f->output_data.ns->miniimage = image;
  [view setMiniwindowImage: setMini];
  [pool release];
769
  unblock_input ();
770 771 772 773
}


static void
774
ns_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
775 776 777 778 779
{
  EmacsView *view = FRAME_NS_VIEW (f);
  id image = nil;
  BOOL setMini = YES;

780
  NSTRACE ("ns_set_icon_type");
781 782 783

  if (!NILP (arg) && SYMBOLP (arg))
    {
784
      arg =build_string (SSDATA (SYMBOL_NAME (arg)));
785 786 787
      store_frame_param (f, Qicon_type, arg);
    }

788
  /* Do it the implicit way.  */
789 790 791 792 793 794 795 796 797 798 799
  if (NILP (arg))
    {
      ns_implicitly_set_icon_type (f);
      return;
    }

  CHECK_STRING (arg);

  image = [EmacsImage allocInitFromFile: arg];
  if (image == nil)
    image =[NSImage imageNamed: [NSString stringWithUTF8String:
800
                                            SSDATA (arg)]];
801 802 803 804 805 806 807 808 809 810 811

  if (image == nil)
    {
      image = [NSImage imageNamed: @"text"];
      setMini = NO;
    }

  f->output_data.ns->miniimage = image;
  [view setMiniwindowImage: setMini];
}

812
/* This is the same as the xfns.c definition.  */
813
static void
814
ns_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
815
{
816
  set_frame_cursor_types (f, arg);
817 818
}

819 820
/* called to set mouse pointer color, but all other terms use it to
   initialize pointer types (and don't set the color ;) */
821
static void
822
ns_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
823
{
824
  /* Don't think we can do this on Nextstep.  */
825 826 827
}


828 829 830 831
#define Str(x) #x
#define Xstr(x) Str(x)

static Lisp_Object
832
ns_appkit_version_str (void)
833
{
834
  char tmp[256];
835 836 837

#ifdef NS_IMPL_GNUSTEP
  sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
838
#elif defined (NS_IMPL_COCOA)
839 840 841 842 843
  NSString *osversion
    = [[NSProcessInfo processInfo] operatingSystemVersionString];
  sprintf(tmp, "appkit-%.2f %s",
          NSAppKitVersionNumber,
          [osversion UTF8String]);
844 845 846 847 848 849 850
#else
  tmp = "ns-unknown";
#endif
  return build_string (tmp);
}


851 852
/* This is for use by x-server-version and collapses all version info we
   have into a single int.  For a better picture of the implementation
853
   running, use ns_appkit_version_str.  */
854
static int
855
ns_appkit_version_int (void)
856 857
{
#ifdef NS_IMPL_GNUSTEP
858
  return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
859
#elif defined (NS_IMPL_COCOA)
860 861 862 863 864 865
  return (int)NSAppKitVersionNumber;
#endif
  return 0;
}


866
static void
867
ns_icon (struct frame *f, Lisp_Object parms)
868 869
/* --------------------------------------------------------------------------
   Strangely-named function to set icon position parameters in frame.
870
   This is irrelevant under macOS, but might be needed under GNUstep,
871 872 873 874 875 876 877
   depending on the window manager used.  Note, this is not a standard
   frame parameter-setter; it is called directly from x-create-frame.
   -------------------------------------------------------------------------- */
{
  Lisp_Object icon_x, icon_y;
  struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);

878 879
  f->output_data.ns->icon_top = -1;
  f->output_data.ns->icon_left = -1;
880 881

  /* Set the position of the icon.  */
882 883 884 885
  icon_x = gui_display_get_arg (dpyinfo, parms, Qicon_left, 0, 0,
                                RES_TYPE_NUMBER);
  icon_y = gui_display_get_arg (dpyinfo, parms, Qicon_top, 0, 0,
                                RES_TYPE_NUMBER);
886 887
  if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
    {
888 889 890 891
      CHECK_FIXNUM (icon_x);
      CHECK_FIXNUM (icon_y);
      f->output_data.ns->icon_top = XFIXNUM (icon_y);
      f->output_data.ns->icon_left = XFIXNUM (icon_x);
892 893 894 895 896 897
    }
  else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
    error ("Both left and top icon corners of icon must be specified");
}


898 899
/* Note: see frame.c for template, also where generic functions are
   implemented.  */
900 901
frame_parm_handler ns_frame_parm_handlers[] =
{
902 903 904
  gui_set_autoraise, /* generic OK */
  gui_set_autolower, /* generic OK */
  ns_set_background_color,
905 906
  0, /* x_set_border_color,  may be impossible under Nextstep */
  0, /* x_set_border_width,  may be impossible under Nextstep */
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
  ns_set_cursor_color,
  ns_set_cursor_type,
  gui_set_font, /* generic OK */
  ns_set_foreground_color,
  ns_set_icon_name,
  ns_set_icon_type,
  ns_set_internal_border_width,
  gui_set_right_divider_width, /* generic OK */
  gui_set_bottom_divider_width, /* generic OK */
  ns_set_menu_bar_lines,
  ns_set_mouse_color,
  ns_explicitly_set_name,
  gui_set_scroll_bar_width, /* generic OK */
  gui_set_scroll_bar_height, /* generic OK */
  ns_set_title,
  gui_set_unsplittable, /* generic OK */
  gui_set_vertical_scroll_bars, /* generic OK */
  gui_set_horizontal_scroll_bars, /* generic OK */
  gui_set_visibility, /* generic OK */
  ns_set_tool_bar_lines,
927 928
  0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
  0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
929 930 931 932
  gui_set_screen_gamma, /* generic OK */
  gui_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
  gui_set_left_fringe, /* generic OK */
  gui_set_right_fringe, /* generic OK */
933
  0, /* x_set_wait_for_wm, will ignore */
934 935 936
  gui_set_fullscreen, /* generic OK */
  gui_set_font_backend, /* generic OK */
  gui_set_alpha,
937 938
  0, /* x_set_sticky */
  0, /* x_set_tool_bar_position */
939
  0, /* x_set_inhibit_double_buffering */
940
#ifdef NS_IMPL_COCOA
941
  ns_set_undecorated,
942
#else
943
  0, /* ns_set_undecorated */
944
#endif
945
  ns_set_parent_frame,
946
  0, /* x_set_skip_taskbar */
947 948 949
  ns_set_no_focus_on_map,
  ns_set_no_accept_focus,
  ns_set_z_group,
950
  0, /* x_set_override_redirect */
951
  gui_set_no_special_glyphs,
952 953 954 955
#ifdef NS_IMPL_COCOA
  ns_set_appearance,
  ns_set_transparent_titlebar,
#endif
956 957 958
};


959 960 961
/* Handler for signals raised during x_create_frame.
   FRAME is the frame which is partially constructed.  */

962
static void
963 964 965 966 967 968 969 970
unwind_create_frame (Lisp_Object frame)
{
  struct frame *f = XFRAME (frame);

  /* If frame is already dead, nothing to do.  This can happen if the
     display is disconnected after the frame has become official, but
     before x_create_frame removes the unwind protect.  */
  if (!FRAME_LIVE_P (f))
971
    return;
972 973

  /* If frame is ``official'', nothing to do.  */
Jan Djärv's avatar
Jan Djärv committed
974
  if (NILP (Fmemq (frame, Vframe_list)))
975
    {
976
#if defined GLYPH_DEBUG && defined ENABLE_CHECKING
977
      struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
978 979
#endif

980 981 982 983
      /* If the frame's image cache refcount is still the same as our
	 private shadow variable, it means we are unwinding a frame
	 for which we didn't yet call init_frame_faces, where the
	 refcount is incremented.  Therefore, we increment it here, so
984
	 that free_frame_faces, called in ns_free_frame_resources
985 986 987 988 989 990
	 below, will not mistakenly decrement the counter that was not
	 incremented yet to account for this new frame.  */
      if (FRAME_IMAGE_CACHE (f) != NULL
	  && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
	FRAME_IMAGE_CACHE (f)->refcount++;

991
      ns_free_frame_resources (f);
992 993
      free_glyphs (f);

994
#if defined GLYPH_DEBUG && defined ENABLE_CHECKING
995
      /* Check that reference counts are indeed correct.  */
996
      eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
997 998 999 1000
#endif
    }
}

1001 1002 1003 1004
/*
 * Read geometry related parameters from preferences if not in PARMS.
 * Returns the union of parms and any preferences read.
 */
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
static Lisp_Object
get_geometry_from_preferences (struct ns_display_info *dpyinfo,
                               Lisp_Object parms)
{
  struct {
    const char *val;
    const char *cls;
    Lisp_Object tem;
  } r[] = {
    { "width",  "Width", Qwidth },
    { "height", "Height", Qheight },
    { "left", "Left", Qleft },
    { "top", "Top", Qtop },
  };

  int i;
1022
  for (i = 0; i < ARRAYELTS (r); ++i)
1023 1024 1025 1026
    {
      if (NILP (Fassq (r[i].tem, parms)))
        {
          Lisp_Object value
1027 1028
            = gui_display_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
                                   RES_TYPE_NUMBER);
1029 1030 1031 1032
          if (! EQ (value, Qunbound))
            parms = Fcons (Fcons (r[i].tem, value), parms);
        }
    }
1033

1034 1035
  return parms;
}
1036 1037 1038 1039 1040 1041 1042

/* ==========================================================================

    Lisp definitions

   ========================================================================== */

1043
DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1044
       1, 1, 0,
1045
       doc: /* SKIP: real doc in xfns.c.  */)
1046
     (Lisp_Object parms)
1047 1048 1049 1050 1051
{
  struct frame *f;
  Lisp_Object frame, tem;
  Lisp_Object name;
  int minibuffer_only = 0;
1052
  long window_prompting = 0;
1053
  ptrdiff_t count = specpdl_ptr - specpdl;
1054 1055
  Lisp_Object display;
  struct ns_display_info *dpyinfo = NULL;
1056
  Lisp_Object parent, parent_frame;
1057
  struct kboard *kb;
1058
  static int desc_ctr = 1;
1059
  int x_width = 0, x_height = 0;
1060

1061
  /* gui_display_get_arg modifies parms.  */
Adrian Robert's avatar
Adrian Robert committed
1062 1063
  parms = Fcopy_alist (parms);

1064 1065 1066 1067
  /* Use this general default value to start with
     until we know if this frame has a specified name.  */
  Vx_resource_name = Vinvocation_name;

1068 1069
  display = gui_display_get_arg (dpyinfo, parms, Qterminal, 0, 0,
                                 RES_TYPE_STRING);
1070 1071 1072
  if (EQ (display, Qunbound))
    display = Qnil;
  dpyinfo = check_ns_display_info (display);
1073
  kb = dpyinfo->terminal->kboard;
1074 1075 1076 1077

  if (!dpyinfo->terminal->name)
    error ("Terminal is not live, can't create new frames on it");

1078 1079
  name = gui_display_get_arg (dpyinfo, parms, Qname, 0, 0,
                              RES_TYPE_STRING);
1080 1081 1082 1083 1084 1085 1086 1087
  if (!STRINGP (name)
      && ! EQ (name, Qunbound)
      && ! NILP (name))
    error ("Invalid frame name--not a string or nil");

  if (STRINGP (name))
    Vx_resource_name = name;

1088 1089
  parent = gui_display_get_arg (dpyinfo, parms, Qparent_id, 0, 0,
                                RES_TYPE_NUMBER);
1090 1091 1092
  if (EQ (parent, Qunbound))
    parent = Qnil;
  if (! NILP (parent))
1093
    CHECK_FIXNUM (parent);
1094

1095 1096 1097
  /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
  /* No need to protect DISPLAY because that's not used after passing
     it to make_frame_without_minibuffer.  */
1098
  frame = Qnil;
1099 1100 1101
  tem = gui_display_get_arg (dpyinfo, parms, Qminibuffer,
                             "minibuffer", "Minibuffer",
                             RES_TYPE_SYMBOL);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  if (EQ (tem, Qnone) || NILP (tem))
      f = make_frame_without_minibuffer (Qnil, kb, display);
  else if (EQ (tem, Qonly))
    {
      f = make_minibuffer_frame ();
      minibuffer_only = 1;
    }
  else if (WINDOWP (tem))
      f = make_frame_without_minibuffer (tem, kb, display);
  else
      f = make_frame (1);

  XSETFRAME (frame, f);

  f->terminal = dpyinfo->terminal;

  f->output_method = output_ns;
1119
  f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1120 1121 1122

  FRAME_FONTSET (f) = -1;

1123 1124 1125
  fset_icon_name (f, gui_display_get_arg (dpyinfo, parms, Qicon_name,
                                          "iconName", "Title",
                                          RES_TYPE_STRING));
1126
  if (! STRINGP (f->icon_name))
1127
    fset_icon_name (f, Qnil);
1128

1129
  FRAME_DISPLAY_INFO (f) = dpyinfo;
1130

1131
  /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */