summaryrefslogtreecommitdiffstats
path: root/macosx/tkMacOSXSysTray.c
blob: 7b9a897ff351375055c733b86d5921cc7d55ff17 (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
530
/*
 * tkMacOSXSysTray.c --
 *
 *	tkMacOSXSysTray.c implements a "systray" Tcl command which allows 
 *      one to change the system tray/taskbar icon of a Tk toplevel 
 *      window and a "sysnotify" command to post system notifications.
 *
 * Copyright (c) 2020 Kevin Walzer/WordTech Communications LLC.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include <tkInt.h>
#include <tkMacOSXInt.h>
#include "tkMacOSXPrivate.h"

static const char ASSOC_KEY[] = "tk::tktray";

/*
 * Class declarations and implementations for TkStatusItem.
 */

@interface TkStatusItem: NSObject {
    NSStatusItem * statusItem;
    NSStatusBar * statusBar;
    NSImage * icon;
    NSString * tooltip;
    Tcl_Interp * interp;
    Tcl_Obj * b1_callback;
    Tcl_Obj * b2_callback;
}

- (id) init : (Tcl_Interp *) interp;
- (void) setImagewithImage : (NSImage *) image;
- (void) setTextwithString : (NSString *) string;
- (void) setB1Callback : (Tcl_Obj *) callback;
- (void) setB2Callback : (Tcl_Obj *) callback;
- (void) clickOnStatusItem: (id) sender;
- (void) dealloc;


@end

@implementation TkStatusItem : NSObject

- (id) init : (Tcl_Interp *) interpreter {
    [super init];
    statusBar = [NSStatusBar systemStatusBar];
    statusItem = [[statusBar statusItemWithLength:NSVariableStatusItemLength] retain];
    statusItem.button.target = self;
    statusItem.button.action = @selector(clickOnStatusItem: );
    [statusItem.button sendActionOn : NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp];
    statusItem.visible = YES;
    interp = interpreter;
    b1_callback = NULL;
    b2_callback = NULL;
    return self;
}

- (void) setImagewithImage : (NSImage *) image
{
    icon = nil;
    icon = image;
    statusItem.button.image = icon;
}

- (void) setTextwithString : (NSString *) string
{
    tooltip = nil;
    tooltip = string;
    statusItem.button.toolTip = tooltip;
}

- (void) setB1Callback : (Tcl_Obj *) obj
{
    if (obj != NULL) {
	Tcl_IncrRefCount(obj);
    }
    if (b1_callback != NULL) {
	Tcl_DecrRefCount(b1_callback);
    }
    b1_callback = obj;
}

- (void) setB2Callback : (Tcl_Obj *) obj
{
    if (obj != NULL) {
	Tcl_IncrRefCount(obj);
    }
    if (b2_callback != NULL) {
	Tcl_DecrRefCount(b1_callback);
    }
    b2_callback = obj;
}

- (void) clickOnStatusItem: (id) sender
{
    NSEvent *event = [NSApp currentEvent];
    if (([event type] == NSEventTypeLeftMouseUp) && (b1_callback != NULL)) {
	int result = Tcl_EvalObjEx(interp, b1_callback, TCL_EVAL_GLOBAL);
	if (result != TCL_OK) {
	    Tcl_BackgroundException(interp, result);
	}
    } else {
	if (([event type] == NSEventTypeRightMouseUp) && (b2_callback != NULL)) {
	int result = Tcl_EvalObjEx(interp, b2_callback, TCL_EVAL_GLOBAL);
	if (result != TCL_OK) {
	    Tcl_BackgroundException(interp, result);
	}
    }  
}
}
- (void) dealloc
{
    /*
     * We are only doing the minimal amount of deallocation that
     * the superclass cannot handle when it is deallocated, per 
     * https://developer.apple.com/documentation/objectivec/nsobject/
     * 1571947-dealloc. The compiler may offer warnings, but disregard.
     * Putting too much here can cause unpredictable crashes, especially
     * in the Tk test suite.
     */
    [statusBar removeStatusItem: statusItem];
    if (b1_callback != NULL) {
	Tcl_DecrRefCount(b1_callback);
    }
    if (b2_callback != NULL) {
	Tcl_DecrRefCount(b2_callback);
    }
}

@end

/*
 * Class declarations and implementations for TkNotifyItem.
 */

@interface TkNotifyItem: NSObject {

    NSUserNotification *tk_notification;
    NSString *header;
    NSString *info;
}

- (id) init;
- (void) postNotificationWithTitle : (NSString *) title message: (NSString *) detail;
- (BOOL) userNotificationCenter:(NSUserNotificationCenter *)center
      shouldPresentNotification:(NSUserNotification *)notification;
- (void) dealloc;


@end

@implementation TkNotifyItem : NSObject

-  (id) init
{
    [super init];
    tk_notification = [[NSUserNotification alloc] init];
    return self;
}

-  (void) postNotificationWithTitle : (NSString * ) title message: (NSString * ) detail
{
    header = title;
    tk_notification.title = header;
    info = detail;
    tk_notification.informativeText = info;
    tk_notification.soundName = NSUserNotificationDefaultSoundName;

    NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
    
    /*
     * This API requires an app delegate to function correctly. 
     * The compiler may complain that setting TkNotificationItem is an 
     * incompatible type, but disregard. Setting to something else will
     * either cause Wish not to build, or the notification not to display.
     */
    [center setDelegate: self];
    
    [center deliverNotification:tk_notification];
}

- (BOOL) userNotificationCenter: (NSUserNotificationCenter * ) center
      shouldPresentNotification: (NSUserNotification * ) notification
{
    return YES;
}

-  (void) dealloc
{
    /*
     * We are only doing the minimal amount of deallocation that
     * the superclass cannot handle when it is deallocated, per 
     * https://developer.apple.com/documentation/objectivec/nsobject/
     * 1571947-dealloc. The compiler may offer warnings, but disregard.
     * Putting too much here can cause unpredictable crashes, especially
     * in the Tk test suite.
     */
    tk_notification = nil;
}

@end

/*
 * Main objects of this file.
 */

typedef struct {
    TkStatusItem *tk_item;
    TkNotifyItem *notify_item;
} TrayInfo;

/*
 *----------------------------------------------------------------------
 *
 * MacSystrayObjCmd --
 *
 * 	Main command for creating, displaying, and removing icons from status menu.
 *
 * Results:
 *	Management of icon display in status menu.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */


static int
MacSystrayObjCmd(
		 void *clientData,
		 Tcl_Interp * interp,
		 int objc,
		 Tcl_Obj *const *objv)
{
    Tk_Image tk_image;
    TrayInfo *info = (TrayInfo *)clientData;
    int result, idx;
    static const char *options[] =
	{"create",	"modify", "destroy", NULL};
    typedef enum {TRAY_CREATE, TRAY_MODIFY, TRAY_DESTROY} optionsEnum;

    static const char *modifyOptions[] =
	{"image",  "text", "b1_callback", "b2_callback", NULL};
    typedef enum {TRAY_IMAGE, TRAY_TEXT, TRAY_B1_CALLBACK, TRAY_B2_CALLBACK} modifyOptionsEnum;

    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "create | modify | destroy");
	return TCL_ERROR;
    }

    result = Tcl_GetIndexFromObjStruct(interp, objv[1], options,
				       sizeof(char *), "command", 0, &idx);

    if (result != TCL_OK) {
    	return TCL_ERROR;
    }
    switch((optionsEnum)idx) {
    case TRAY_CREATE: {

	if (objc < 6) {
	    Tcl_WrongNumArgs(interp, 1, objv, "create image ?text? ?b1_callback? b2_callback?");
	    return TCL_ERROR;
	}

	if (info->tk_item == NULL) {
	    info->tk_item = [[TkStatusItem alloc] init: interp];
	} else {
	    Tcl_AppendResult(interp, "Only one system tray icon supported per interpeter", NULL);
	    return TCL_ERROR;
	}

	/*
	 * Create the icon.
	 */

	int width, height;
	Tk_Window tkwin = Tk_MainWindow(interp);
	TkWindow *winPtr = (TkWindow *)tkwin;
	Display *d = winPtr->display;
	NSImage *icon;

	tk_image = Tk_GetImage(interp, tkwin, Tcl_GetString(objv[2]), NULL, NULL);
	if (tk_image == NULL) {
	    return TCL_ERROR;
	}

	Tk_SizeOfImage(tk_image, &width, &height);
	if (width != 0 && height != 0) {
	    icon = TkMacOSXGetNSImageFromTkImage(d, tk_image,
						 width, height);
	    [info->tk_item setImagewithImage: icon];
	    Tk_FreeImage(tk_image);
	}

	/*
	 * Set the text for the tooltip.
	 */

	NSString *tooltip = [NSString stringWithUTF8String: Tcl_GetString(objv[3])];
	if (tooltip == nil) {
	    Tcl_AppendResult(interp, " unable to set tooltip for systray icon", NULL);
	    return TCL_ERROR;
	}

	[info->tk_item setTextwithString: tooltip];

	/*
	 * Set the proc for the callback.
	 */

	[info->tk_item setB1Callback : objv[4]];
	[info->tk_item setB2Callback : objv[5]];
	break;

    }
    case TRAY_MODIFY: {
	if (objc < 5) {
	    Tcl_WrongNumArgs(interp, 1, objv, "modify object item");
	    return TCL_ERROR;
	}

	/*
	 * Modify the icon.
	 */

	result = Tcl_GetIndexFromObjStruct(interp, objv[2], modifyOptions,
					   sizeof(char *), "option", 0, &idx);

	if (result != TCL_OK) {
	    return TCL_ERROR;
	}
	switch ((modifyOptionsEnum)idx) {
	case TRAY_IMAGE: {
	    Tk_Window tkwin = Tk_MainWindow(interp);
	    TkWindow *winPtr = (TkWindow *)tkwin;
	    Display *d = winPtr -> display;
	    NSImage *icon;
	    int width, height;

	    tk_image = Tk_GetImage(interp, tkwin, Tcl_GetString(objv[3]), NULL, NULL);
	    if (tk_image == NULL) {
		Tcl_AppendResult(interp, " unable to obtain image for systray icon", (char * ) NULL);
		return TCL_ERROR;
	    }

	    Tk_SizeOfImage(tk_image, &width, &height);
	    if (width != 0 && height != 0) {
		icon = TkMacOSXGetNSImageFromTkImage(d, tk_image,
						     width, height);
		[info->tk_item setImagewithImage: icon];
	    }
	    Tk_FreeImage(tk_image);
	    break;
	}

	    /*
	     * Modify the text for the tooltip.
	     */

	case TRAY_TEXT: {
	    NSString *tooltip = [NSString stringWithUTF8String:Tcl_GetString(objv[3])];
	    if (tooltip == nil) {
		Tcl_AppendResult(interp, "unable to set tooltip for systray icon", NULL);
		return TCL_ERROR;
	    }

	    [info->tk_item setTextwithString: tooltip];
	    break;
	}

	    /*
	     * Modify the proc for the callback.
	     */

	case TRAY_B1_CALLBACK: {
	    [info->tk_item setB1Callback : objv[3]];
	    break;
	}
	case TRAY_B2_CALLBACK: {
	    [info->tk_item setB2Callback : objv[4]];
	    break; 
	}
	    break;
	}

	case TRAY_DESTROY: {
	    /* we don't really distroy, just reset the image, text and callback */
	    [info->tk_item setImagewithImage: nil];
	    [info->tk_item setTextwithString: nil];
	    [info->tk_item setB1Callback : NULL];
	    [info->tk_item setB2Callback : NULL];
	    // /* do nothing */
	    break;
	}
	    break;
    }
	return TCL_OK;
    }
}


/*
 *----------------------------------------------------------------------
 *
 * MacSystrayDestroy --
 *
 * 	Deletes icon from display.
 *
 * Results:
 *	Icon/window removed and memory freed.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
MacSystrayDestroy(
		  void *clientData,
		  TCL_UNUSED(Tcl_Interp *))
{
    TrayInfo *info = (TrayInfo *)clientData;

    if (info->tk_item != NULL) {
	[info->tk_item dealloc];
	info->tk_item = NULL;
    }
    if (info->notify_item != NULL) {
	[info->notify_item dealloc];
	info->notify_item = NULL;
    }
    ckfree(info);
}


/*
 *----------------------------------------------------------------------
 *
 * SysNotifyCreateCmd --
 *
 *      Create tray command and (unreal) window.
 *
 * Results:
 *	Icon tray and hidden window created.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------z---------------------------------------
 */


static int SysNotifyObjCmd(
			   void *clientData,
			   Tcl_Interp * interp,
			   int objc,
			   Tcl_Obj *const *objv)
{
    TrayInfo *info = (TrayInfo *) clientData;

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 1, objv, "title message");
	return TCL_ERROR;
    }

    if (info->notify_item == NULL) {
	info->notify_item = [[TkNotifyItem alloc] init];
    }

    NSString *title = [NSString stringWithUTF8String: Tcl_GetString(objv[1])];
    NSString *message = [NSString stringWithUTF8String: Tcl_GetString(objv[2])];
    [info->notify_item postNotificationWithTitle : title message: message];

    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * MacSystrayInit --
 *
 * 	Initialize this package and create script-level commands.
 *
 * Results:
 *	Initialization of code.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
MacSystrayInit(Tcl_Interp *interp)
{

    /*
     * Initialize TkStatusItem and TkNotifyItem.
     */

    TrayInfo *info = (TrayInfo *)ckalloc(sizeof(TrayInfo));

    memset(info, 0, sizeof(TrayInfo));
    Tcl_SetAssocData(interp, ASSOC_KEY, MacSystrayDestroy, info);

    if ([NSApp macOSVersion] < 101000) {
	Tcl_AppendResult(interp, "Statusitem icons not supported on versions of macOS lower than 10.10", NULL);
	return TCL_OK;
    }

    Tcl_CreateObjCommand(interp, "_systray", MacSystrayObjCmd, info, NULL);
    Tcl_CreateObjCommand(interp, "_sysnotify", SysNotifyObjCmd, info, NULL);

    return TCL_OK;
}

/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */