#include <QtGui>

#include <AppKit/AppKit.h>
#include <crt_externs.h>

class Object : public QObject
{
public:
    Object(const char *name) {
        setObjectName(name);
        qDebug() << __FUNCTION__ << this;
        deleteLater();
    }
    ~Object() { qDebug() << __FUNCTION__ << this; }
};

class Window : public QWindow
{
protected:
    void mousePressEvent(QMouseEvent *) { new Object(__FUNCTION__); }
    void keyPressEvent(QKeyEvent *) { new Object(__FUNCTION__); }
};

void setupQtApplication()
{
    new QGuiApplication(*_NSGetArgc(), *_NSGetArgv());
    auto *window = new Window;
    window->show();
    
    new Object(__FUNCTION__);
}

@interface ApplicationDelegate : NSObject <NSApplicationDelegate>
@end

@implementation ApplicationDelegate
- (void)applicationDidFinishLaunching: (NSNotification *)notification
{
    setupQtApplication();
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    return YES; 
}
@end

int main(int argc, const char** argv)
{
#if 1
    @autoreleasepool {
        [NSApplication sharedApplication].delegate = [[ApplicationDelegate new] autorelease];
        return NSApplicationMain(argc, argv);
    }
#else
    setupQtApplication();
    return qGuiApp->exec();
#endif
}
