macosassemblysystem-callsapple-m1apple-silicon

Get screen resolution with system calls in macOS M1 Arm64


I am learning arm64 assembly and want to make a console game. I got info on how to delay using nanosleep and print some characters into the console.

Now I want to get the width and height of my screen. This is the only resource I have about macOS System calls, but I don't seem to find any one regarding screen resolution.

Please Help.


Solution

  • To find the size of the terminal window, call ioctl with the TIOCGWINSZ call on the terminal's file descriptor (e.g. file descriptor 0). This example is in C, but you should be able to translate it into assembly easily. I would have preferred to show you an assembly example, but I don't have macOS at hand right now to make sure it is correct.

    #include <sys/ioctl.h>
    #include <unistd.h>
    
    struct winsize sz;
    
    /* get the size of the terminal */
    ioctl(STDIN_FILENO, TIOCGWINSZ, &sz);
    
    printf("the terminal has %d rows and %d columns\n", sz.ws_row, sz.ws_col);
    

    The layout of the window size structure is four halfwords, in this order:

    ws_row     number of rows
    ws_col     number of columns
    ws_xpixel  number of horizontal pixels
    ws_ypixel  number of vertical pixels
    

    Note that the ws_xpixel and ws_ypixel fields may not be reliable.

    When the terminal window is resized, a SIGWINCH (window change) signal will be delivered to all processes in the foreground process group of the terminal. You can handle SIGWINCH to update your game's knowledge about the current size of the terminal window. In the SIGWINCH handler, call the TIOCGWINSZ call again to get the updated terminal size.