Skip to content

Casting to NSView* from getNativeWindowHandle() #7460

Closed

Description

@0x61726b
  • Electron version: 1.4.2 x64
  • Operating system: OSX Yosemite 10.10

I've been trying to get NSView* from getNativeWindowHandle() in a C++ addon, as the docs suggest the handle is NSView* on MacOS, but with no luck, I've been getting seg faults. I've seen #4369 and thought maybe the pointer returned on Mac is invalid too ? If someone did this successfully, I'd like to know how you can retrieve NSView* from getNativeWindowHandle().

Here is my code

Nodejs

require('some-native-module').test(browserWindow.getNativeWindowHandle())

C++ (compiled against electron, x64)

v8::Local<v8::Object> bufferObj = info[0].As<v8::Object>(); 
unsigned char* bufferData = (unsigned char*)node::Buffer::Data(bufferObj);

NSView* view = reinterpret_cast<NSView*>(bufferData);

//Seg fault if you try to do anything with the NSView*

I've converted the buffer to hex using toString('hex') and then print hex on C++ side to verify that they are the same.

NSData *dataData = [NSData dataWithBytes:bufferData length:sizeof(bufferData)];
NSLog(@"%@",dataData);

NSLog prints 2016-10-03 03:40:33.734 node[1816:18569] <50255153 e07f0000>,
and the developer console when you type require('electron').remote.getCurrentWindow().getNativeWindowHandle().toString('hex') prints 50255153e07f0000.

The same code for Windows works.

unsigned long handle = *reinterpret_cast<unsigned long*>(bufferData);
HWND hwnd = (HWND)handle;  //Valid

I'm thinking that casting to NSView* is problem,rather than the char* buffer returned from node::Buffer::Data. Did anyone succesfully do this before?

Activity

  1. zcbenz commented on Oct 20, 2016

    @zcbenz
    Contributor

    I think it should be NSView* view = *reinterpret_cast<NSView**>(bufferData).

  2. Qix- commented on Sep 9, 2018

    @Qix-

    Sorry to necro but this doesn't work. The following test code compiles fine but segfaults.

    module/binding.gyp

    {
      "targets": [
        {
          "target_name": "addon",
          "sources": [ "hello.mm" ],
          "include_dirs" : [
            "<!(node -e \"require('nan')\")"
          ],
          "conditions": [
            ['OS=="mac"',
              {
                'defines': [
                  '__MACOSX_CORE__'
                ],
                'link_settings': {
                    'libraries': [
                      '-framework CoreAudio',
                      '-framework CoreFoundation',
                    ]
                },
                'xcode_settings': {
                    'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
                    'CLANG_CXX_LIBRARY': 'libc++',
    
                    'OTHER_CFLAGS': [
                      '-ObjC++',
                      '-std=c++11'
                    ],
                },
              }
            ],
          ],
        }
      ]
    }
    

    module/hello.mm

    #include <nan.h>
    #include <string>
    
    #import <CoreFoundation/CoreFoundation.h>
    #import <Cocoa/Cocoa.h>
    
    using namespace Nan;
    using namespace v8;
    using namespace std;
    
    NAN_METHOD(getTitle) {
    	string result;
    	NSString *title = NULL;
    
    	v8::Local<v8::Object> bufferObj = info[0].As<v8::Object>(); 
    	unsigned char* bufferData = (unsigned char*)node::Buffer::Data(bufferObj);
    
    	// NSView *view = reinterpret_cast<NSView*>(bufferData);
    	NSView *view = *reinterpret_cast<NSView**>(bufferData);
    
    	NSWindow *win = [view window];
    	if (win == NULL) goto set_ret;
    
    	title = [win title];
    	if (title == NULL) goto set_ret;
    
    	result = [title UTF8String];
    
    set_ret:
    	info.GetReturnValue().Set(New<String>(result).ToLocalChecked());
    }
    
    NAN_MODULE_INIT(Init) {
    	Nan::Set(target, New<String>("getTitle").ToLocalChecked(),
    		GetFunction(New<FunctionTemplate>(getTitle)).ToLocalChecked());
    }
    
    NODE_MODULE(buffer_example, Init)

    module/index.js

    const addon = require('./build/Release/addon');
    
    module.exports = addon.getTitle;

    app/index.html

    <!doctype html>
    <html>
    	<body>
    		<div id="output"></div>
    		<script>
    			const getTitle = require('test-native');
    			const remote = require('electron').remote;
    			const update = () => {
    				const handle = remote.getCurrentWindow().getNativeWindowHandle();
    				const title = getTitle(handle);
    				document.body.querySelector('#output').innerHTML = `<strong>title:</strong> ${title}`;
    			};
    			setTimeout(update, 100);
    		</script>
    	</body>
    </html>

    Note that everything works if I short-circuit the C++ function by setting the result and jumping to set_ret (meaning the result shows up in the HTML view).

    How is anyone getting this to work?

    Worth mentioning this is impossible to debug seeing as how Electron outputs nothing to the terminal and LLDB can't attach to it.

  3. 0x61726b commented on Sep 9, 2018

    @0x61726b
    Author

    Can you try my native module and see if it works? Because it worked unless a recent electron update broke it?

    https://github.com/arkenthera/electron-vibrancy/

  4. Qix- commented on Sep 9, 2018

    @Qix-

    @arkenthera Doesn't work for me, same thing happens.

    image

    Is this because I'm trying to use the NSView* from within the browser window using require('electron').remote? Is that not supported? I didn't think you could modify the window of another process (since electron is multi-process, right?) directly using a pointer to an NSView on MacOS, hence why I'm doing it this way. The documentation doesn't specify either way.


    EDIT: Yeah getNativeWindowHandle() should only be called by the main electron process. It cannot be called from the browser windows (well, it can, but you can't use the result reliably). This seems like something that should be included in the documentation. Would you agree @zcbenz?

  5. 0x61726b commented on Sep 9, 2018

    @0x61726b
    Author

    I think it's kind of obvious that the actual OS window that is created is done so in the main process.

  6. Qix- commented on Sep 9, 2018

    @Qix-

    It's not, though. I was under the assumption that, like Chrome, each window is created in its own process. That would mean there's a good change the NSWindow is created in the child process, thus resulting in a process-specific pointer that can't be shared like a windows HWND or something.

    Further, I didn't know that cocoa windows could be modified between processes, since the main process can still manipulate the child process's window after it forks. Hence why I thought it was a pretty natural assumption that you had to use the pointer from within the browser process.

  7. 0x61726b commented on Sep 9, 2018

    @0x61726b
    Author

    I always thought like if we are creating a BrowserWindow on the main process' js file, then the actual pointer address will be in main process as well, thus calling it obvious.

  8. Qix- commented on Sep 9, 2018

    @Qix-

    @arkenthera but like I said, it's not obvious - because that's not how pointers work. The window belongs to the child process, so referencing the window handle by pointer in the parent process shouldn't work since the window isn't in the parent process.

    There's some other sort of IPC going on here.

    EDIT: and even if the window is created prior to forking, which means the pointer would be valid in the child process, you'd expect that the pointer would work if referenced in the child process too. It does not. So I'm not sure how it's working.

  9. Lijian1122 commented on Jan 26, 2022

    @Lijian1122

    Hi, Has the problem been solved? If so, could you please tell me how it was solved? Thank you very much. I am looking forward for your reply.

  10. nornagon commented on Jan 26, 2022

    @nornagon
    Contributor

    If using a module like objc, see lukaskollmer/objc#16 (comment):

    const handle = mainWindow.getNativeWindowHandle().readPointer()
    const nsview = objc.wrap(handle)
    nsview.window().invalidateShadow()
  11. BB-fat commented on Mar 29, 2022

    @BB-fat

    This is my solution.

    // ts
    const handle = window.getNativeWindowHandle();
    testNativeWindow(handle);
    
    // mm
    auto buffer = info[0].As<Napi::Buffer<uint8_t>>();
    void **handle = reinterpret_cast<void **>(buffer);
    NSView* electronView = (__bridge NSView *)*handle;
    
  12. ZeroMax-dev commented on Mar 28, 2023

    @ZeroMax-dev

    @BB-fat Your solution gives me an

    error: reinterpret_cast from 'Napi::Buffer<unsigned char>' to 'void **' is not allowed
    void **handle = reinterpret_cast<void **>(buffer);
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

    However, I managed with a lot of try and error to produce a solution that works! (tested with "node-addon-api": "^6.0.0"):

    Napi::String GetWindowTitle(const Napi::CallbackInfo& info) {
      Napi::Env env = info.Env();
      NSView** viewp = reinterpret_cast<NSView**>(info[0].As<Napi::Buffer<NSView**>>().Data());
      NSView* view = *viewp;
      NSWindow* window = [view window];
      NSString* title = [window title];
      return Napi::String::New(env, [title UTF8String]);
    }
    

    It should be able to return the title of your BrowserWindow without crashing:
    console.log( nativeAddon.GetWindowTitle(window.getNativeWindowHandle()) );

  13. lockieluke commented on May 20, 2023

    @lockieluke

    i'm trying to pass the C++ value to Swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions