cocoa_event.m 16.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * MACDRV Cocoa event queue code
 *
 * Copyright 2011, 2012, 2013 Ken Thomases for CodeWeavers Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <libkern/OSAtomic.h>

#include "macdrv_cocoa.h"
#import "cocoa_event.h"
#import "cocoa_app.h"
#import "cocoa_window.h"


32 33 34
static NSString* const WineEventQueueThreadDictionaryKey = @"WineEventQueueThreadDictionaryKey";


35 36 37
@interface MacDrvEvent : NSObject
{
@public
38
    macdrv_event* event;
39 40
}

41
    - (id) initWithEvent:(macdrv_event*)event;
42 43 44 45 46

@end

@implementation MacDrvEvent

47
    - (id) initWithEvent:(macdrv_event*)inEvent
48 49 50 51
    {
        self = [super init];
        if (self)
        {
52
            event = macdrv_retain_event(inEvent);
53 54 55 56
        }
        return self;
    }

57 58 59 60 61 62
    - (void) dealloc
    {
        if (event) macdrv_release_event(event);
        [super dealloc];
    }

63 64 65 66 67 68 69
@end


@implementation WineEventQueue

    - (id) init
    {
70 71 72 73 74 75 76 77 78
        [self doesNotRecognizeSelector:_cmd];
        [self release];
        return nil;
    }

    - (id) initWithEventHandler:(macdrv_event_handler)handler
    {
        NSParameterAssert(handler != nil);

79 80 81
        self = [super init];
        if (self != nil)
        {
82 83 84 85
            struct kevent kev;
            int rc;

            fds[0] = fds[1] = kq = -1;
86

87
            event_handler = handler;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
            events = [[NSMutableArray alloc] init];
            eventsLock = [[NSLock alloc] init];

            if (!events || !eventsLock)
            {
                [self release];
                return nil;
            }

            if (pipe(fds) ||
                fcntl(fds[0], F_SETFD, 1) == -1 ||
                fcntl(fds[0], F_SETFL, O_NONBLOCK) == -1 ||
                fcntl(fds[1], F_SETFD, 1) == -1 ||
                fcntl(fds[1], F_SETFL, O_NONBLOCK) == -1)
            {
                [self release];
                return nil;
            }
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

            kq = kqueue();
            if (kq < 0)
            {
                [self release];
                return nil;
            }

            EV_SET(&kev, fds[0], EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0);
            do
            {
                rc = kevent(kq, &kev, 1, NULL, 0, NULL);
            } while (rc == -1 && errno == EINTR);
            if (rc == -1)
            {
                [self release];
                return nil;
            }
124 125 126 127 128 129 130 131 132
        }
        return self;
    }

    - (void) dealloc
    {
        [events release];
        [eventsLock release];

133
        if (kq != -1) close(kq);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        if (fds[0] != -1) close(fds[0]);
        if (fds[1] != -1) close(fds[1]);

        [super dealloc];
    }

    - (void) signalEventAvailable
    {
        char junk = 1;
        int rc;

        do
        {
            rc = write(fds[1], &junk, 1);
        } while (rc < 0 && errno == EINTR);

        if (rc < 0 && errno != EAGAIN)
            ERR(@"%@: got error writing to event queue signaling pipe: %s\n", self, strerror(errno));
    }

    - (void) postEventObject:(MacDrvEvent*)event
    {
156 157
        MacDrvEvent* lastEvent;

158
        [eventsLock lock];
159

160 161
        if ((event->event->type == MOUSE_MOVED ||
             event->event->type == MOUSE_MOVED_ABSOLUTE) &&
162
            (lastEvent = [events lastObject]) &&
163 164
            (lastEvent->event->type == MOUSE_MOVED ||
             lastEvent->event->type == MOUSE_MOVED_ABSOLUTE) &&
165 166
            lastEvent->event->window == event->event->window &&
            lastEvent->event->mouse_moved.drag == event->event->mouse_moved.drag)
167
        {
168
            if (event->event->type == MOUSE_MOVED)
169
            {
170 171
                lastEvent->event->mouse_moved.x += event->event->mouse_moved.x;
                lastEvent->event->mouse_moved.y += event->event->mouse_moved.y;
172 173 174
            }
            else
            {
175 176 177
                lastEvent->event->type = MOUSE_MOVED_ABSOLUTE;
                lastEvent->event->mouse_moved.x = event->event->mouse_moved.x;
                lastEvent->event->mouse_moved.y = event->event->mouse_moved.y;
178 179
            }

180
            lastEvent->event->mouse_moved.time_ms = event->event->mouse_moved.time_ms;
181 182 183 184
        }
        else
            [events addObject:event];

185 186 187 188 189
        [eventsLock unlock];

        [self signalEventAvailable];
    }

190
    - (void) postEvent:(macdrv_event*)inEvent
191 192 193 194 195 196 197 198 199 200 201
    {
        MacDrvEvent* event = [[MacDrvEvent alloc] initWithEvent:inEvent];
        [self postEventObject:event];
        [event release];
    }

    - (MacDrvEvent*) getEventMatchingMask:(macdrv_event_mask)mask
    {
        char buf[512];
        int rc;
        NSUInteger index;
202
        MacDrvEvent* ret = nil;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

        /* Clear the pipe which signals there are pending events. */
        do
        {
            rc = read(fds[0], buf, sizeof(buf));
        } while (rc > 0 || (rc < 0 && errno == EINTR));
        if (rc == 0 || (rc < 0 && errno != EAGAIN))
        {
            if (rc == 0)
                ERR(@"%@: event queue signaling pipe unexpectedly closed\n", self);
            else
                ERR(@"%@: got error reading from event queue signaling pipe: %s\n", self, strerror(errno));
            return nil;
        }

        [eventsLock lock];

        index = 0;
221
        while (index < [events count])
222
        {
223
            MacDrvEvent* event = [events objectAtIndex:index];
224
            if (event_mask_for_type(event->event->type) & mask)
225 226 227 228 229 230 231 232 233 234 235 236 237
            {
                [[event retain] autorelease];
                [events removeObjectAtIndex:index];

                if (event->event->deliver == INT_MAX ||
                    OSAtomicDecrement32Barrier(&event->event->deliver) >= 0)
                {
                    ret = event;
                    break;
                }
            }
            else
                index++;
238 239 240
        }

        [eventsLock unlock];
241
        return ret;
242 243 244 245
    }

    - (void) discardEventsMatchingMask:(macdrv_event_mask)mask forWindow:(NSWindow*)window
    {
246
        NSIndexSet* indexes;
247 248 249

        [eventsLock lock];

250
        indexes = [events indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
251
            MacDrvEvent* event = obj;
252 253
            return ((event_mask_for_type(event->event->type) & mask) &&
                    (!window || event->event->window == (macdrv_window)window));
254 255 256 257 258 259 260
        }];

        [events removeObjectsAtIndexes:indexes];

        [eventsLock unlock];
    }

261
    - (BOOL) query:(macdrv_query*)query timeout:(NSTimeInterval)timeout processEvents:(BOOL)processEvents
262
    {
263
        macdrv_event* event;
264 265 266
        NSDate* timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeout];
        BOOL timedout;

267 268
        event = macdrv_create_event(QUERY_EVENT, (WineWindow*)query->window);
        event->query_event.query = macdrv_retain_query(query);
269 270
        query->done = FALSE;

271 272
        [self postEvent:event];
        macdrv_release_event(event);
273 274 275
        timedout = ![[WineApplicationController sharedController] waitUntilQueryDone:&query->done
                                                                             timeout:timeoutDate
                                                                       processEvents:processEvents];
276 277 278
        return !timedout && query->status;
    }

279 280 281 282 283
    - (BOOL) query:(macdrv_query*)query timeout:(NSTimeInterval)timeout
    {
        return [self query:query timeout:timeout processEvents:FALSE];
    }

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    - (void) resetMouseEventPositions:(CGPoint)pos
    {
        MacDrvEvent* event;

        [eventsLock lock];

        for (event in events)
        {
            if (event->event->type == MOUSE_BUTTON)
            {
                event->event->mouse_button.x = pos.x;
                event->event->mouse_button.y = pos.y;
            }
            else if (event->event->type == MOUSE_SCROLL)
            {
                event->event->mouse_scroll.x = pos.x;
                event->event->mouse_scroll.y = pos.y;
            }
        }

        [eventsLock unlock];
    }

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

/***********************************************************************
 *              OnMainThread
 *
 * Run a block on the main thread synchronously.
 */
void OnMainThread(dispatch_block_t block)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
    WineEventQueue* queue = [threadDict objectForKey:WineEventQueueThreadDictionaryKey];
    __block BOOL finished;

    if (!queue)
    {
        /* Fall back to synchronous dispatch without handling query events. */
        dispatch_sync(dispatch_get_main_queue(), block);
        [pool release];
        return;
    }

    finished = FALSE;
    OnMainThreadAsync(^{
        block();
        finished = TRUE;
        [queue signalEventAvailable];
    });

    while (!finished)
    {
        MacDrvEvent* macDrvEvent;
        struct kevent kev;

        while (!finished &&
               (macDrvEvent = [queue getEventMatchingMask:event_mask_for_type(QUERY_EVENT)]))
        {
343
            queue->event_handler(macDrvEvent->event);
344 345 346
        }

        if (!finished)
347 348 349 350
        {
            [pool release];
            pool = [[NSAutoreleasePool alloc] init];

351
            kevent(queue->kq, NULL, 0, &kev, 1, NULL);
352
        }
353 354 355 356 357
    }

    [pool release];
}

358 359 360 361 362 363 364

/***********************************************************************
 *              macdrv_create_event_queue
 *
 * Register this thread with the application on the main thread, and set
 * up an event queue on which it can deliver events to this thread.
 */
365
macdrv_event_queue macdrv_create_event_queue(macdrv_event_handler handler)
366 367
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
368
    NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
369

370 371
    WineEventQueue* queue = [threadDict objectForKey:WineEventQueueThreadDictionaryKey];
    if (!queue)
372
    {
373 374 375
        queue = [[[WineEventQueue alloc] initWithEventHandler:handler] autorelease];
        if (queue)
        {
376
            if ([[WineApplicationController sharedController] registerEventQueue:queue])
377 378 379 380
                [threadDict setObject:queue forKey:WineEventQueueThreadDictionaryKey];
            else
                queue = nil;
        }
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    }

    [pool release];
    return (macdrv_event_queue)queue;
}

/***********************************************************************
 *              macdrv_destroy_event_queue
 *
 * Tell the application that this thread is exiting and destroy the
 * associated event queue.
 */
void macdrv_destroy_event_queue(macdrv_event_queue queue)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineEventQueue* q = (WineEventQueue*)queue;
397
    NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
398

399
    [[WineApplicationController sharedController] unregisterEventQueue:q];
400
    [threadDict removeObjectForKey:WineEventQueueThreadDictionaryKey];
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417

    [pool release];
}

/***********************************************************************
 *              macdrv_get_event_queue_fd
 *
 * Get the file descriptor whose readability signals that there are
 * events on the event queue.
 */
int macdrv_get_event_queue_fd(macdrv_event_queue queue)
{
    WineEventQueue* q = (WineEventQueue*)queue;
    return q->fds[0];
}

/***********************************************************************
418
 *              macdrv_copy_event_from_queue
419 420 421 422 423
 *
 * Pull an event matching the event mask from the event queue and store
 * it in the event record pointed to by the event parameter.  If a
 * matching event was found, return non-zero; otherwise, return 0.
 *
424
 * The caller is responsible for calling macdrv_release_event on any
425 426
 * event returned by this function.
 */
427 428
int macdrv_copy_event_from_queue(macdrv_event_queue queue,
        macdrv_event_mask mask, macdrv_event **event)
429 430 431 432 433 434
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineEventQueue* q = (WineEventQueue*)queue;

    MacDrvEvent* macDrvEvent = [q getEventMatchingMask:mask];
    if (macDrvEvent)
435
        *event = macdrv_retain_event(macDrvEvent->event);
436 437 438 439 440 441

    [pool release];
    return (macDrvEvent != nil);
}

/***********************************************************************
442
 *              macdrv_create_event
443
 */
444
macdrv_event* macdrv_create_event(int type, WineWindow* window)
445
{
446 447 448 449
    macdrv_event *event;

    event = calloc(1, sizeof(*event));
    event->refs = 1;
450
    event->deliver = INT_MAX;
451 452 453 454
    event->type = type;
    event->window = (macdrv_window)[window retain];
    return event;
}
455

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
/***********************************************************************
 *              macdrv_retain_event
 */
macdrv_event* macdrv_retain_event(macdrv_event *event)
{
    OSAtomicIncrement32Barrier(&event->refs);
    return event;
}

/***********************************************************************
 *              macdrv_release_event
 *
 * Decrements the reference count of an event.  If the count falls to
 * zero, cleans up any resources, such as allocated memory or retained
 * objects, held by the event and deallocates it
 */
void macdrv_release_event(macdrv_event *event)
{
    if (OSAtomicDecrement32Barrier(&event->refs) <= 0)
475
    {
476
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
477

478 479
        switch (event->type)
        {
480 481 482 483
            case IM_SET_TEXT:
                if (event->im_set_text.text)
                    CFRelease(event->im_set_text.text);
                break;
484 485 486 487 488 489 490 491 492 493
            case KEYBOARD_CHANGED:
                CFRelease(event->keyboard_changed.uchr);
                break;
            case QUERY_EVENT:
                macdrv_release_query(event->query_event.query);
                break;
            case WINDOW_GOT_FOCUS:
                [(NSMutableSet*)event->window_got_focus.tried_windows release];
                break;
        }
494

495 496 497 498 499
        [(WineWindow*)event->window release];
        free(event);

        [pool release];
    }
500 501
}

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
/***********************************************************************
 *              macdrv_create_query
 */
macdrv_query* macdrv_create_query(void)
{
    macdrv_query *query;

    query = calloc(1, sizeof(*query));
    query->refs = 1;
    return query;
}

/***********************************************************************
 *              macdrv_retain_query
 */
macdrv_query* macdrv_retain_query(macdrv_query *query)
{
    OSAtomicIncrement32Barrier(&query->refs);
    return query;
}

/***********************************************************************
 *              macdrv_release_query
 */
void macdrv_release_query(macdrv_query *query)
{
    if (OSAtomicDecrement32Barrier(&query->refs) <= 0)
    {
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        switch (query->type)
        {
            case QUERY_DRAG_OPERATION:
                if (query->drag_operation.pasteboard)
                    CFRelease(query->drag_operation.pasteboard);
                break;
            case QUERY_DRAG_DROP:
                if (query->drag_drop.pasteboard)
                    CFRelease(query->drag_drop.pasteboard);
                break;
            case QUERY_PASTEBOARD_DATA:
                if (query->pasteboard_data.type)
                    CFRelease(query->pasteboard_data.type);
                break;
        }
545 546 547 548 549 550 551 552 553 554 555 556 557
        [(WineWindow*)query->window release];
        free(query);
    }
}

/***********************************************************************
 *              macdrv_set_query_done
 */
void macdrv_set_query_done(macdrv_query *query)
{
    macdrv_retain_query(query);

    OnMainThreadAsync(^{
558 559
        NSEvent* event;

560 561
        query->done = TRUE;
        macdrv_release_query(query);
562 563 564 565 566 567 568 569 570 571 572

        event = [NSEvent otherEventWithType:NSApplicationDefined
                                   location:NSZeroPoint
                              modifierFlags:0
                                  timestamp:[[NSProcessInfo processInfo] systemUptime]
                               windowNumber:0
                                    context:nil
                                    subtype:WineApplicationEventWakeQuery
                                      data1:0
                                      data2:0];
        [NSApp postEvent:event atStart:TRUE];
573 574 575
    });
}

576
@end