Search code examples
javascriptwindowalignmentsciter

How to fit a window to its contents and center it on the screen in Sciter?


When trying out GUI software for the first time, the first thing I want to do is center the window and fit it to its contents. I personally believe this should be as easy to do as possible, and preferably explained in the official documentation.

The ability to center the main window of one's program on the screen is, in my opinion, a very fundamental requirement of any GUI library.

However, I was unable to find these instructions in the official documentation.


Solution

  • I cannot recall exactly where I found instructions from the author, but here they are for "vanilla" Sciter, using TIScript:

    const w = self.intrinsicWidthMax();
    const h = self.intrinsicHeight();
    const (sw, sh) = view.screenBox(#frame, #dimension);
    view.move((sw / 2) - (w / 2), (sh / 2) - (h / 2), w, h, true);
    

    #frame refers to the entire screen, or monitor, here. #dimension specifies that its width and height shall be returned (there are other symbols for returning coordinates of certain aspects of the screen).

    view.move is an unfortunately-named overloaded method because it allows resizing the window in addition to moving it. The last boolean parameter specifies whether the size of the window frame and caption should be considered as part of the total window size.

    In an official example it's recommended to place this inside function self.ready() { ... } but I have not encountered any problems putting it at the top of my main script file.

    Here is the JavaScript port for Sciter.JS:

    // https://github.com/c-smile/sciter-js-sdk/discussions/39#discussioncomment-377697
    const [ _, w ] = document.state.contentWidths();
    const h = document.state.contentHeight(w);
    const [ sw, sh ] = Window.this.screenBox('frame', 'dimension');
    Window.this.move((sw - w) / 2, (sh - h) / 2, w, h, true);