~ctwm/ctwm/trunk

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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
/*
 *       Copyright 1988 by Evans & Sutherland Computer Corporation,
 *                          Salt Lake City, Utah
 *  Portions Copyright 1989 by the Massachusetts Institute of Technology
 *                        Cambridge, Massachusetts
 *
 * Copyright 1992 Claude Lecommandeur.
 */

/***********************************************************************
 *
 * $XConsortium: util.c,v 1.47 91/07/14 13:40:37 rws Exp $
 *
 * utility routines for twm
 *
 * 28-Oct-87 Thomas E. LaStrange        File created
 *
 * Do the necessary modification to be integrated in ctwm.
 * Can no longer be used for the standard twm.
 *
 * 22-April-92 Claude Lecommandeur.
 *
 * Changed behavior of DontMoveOff/MoveOffResistance to allow
 * moving a window off screen less than #MoveOffResistance pixels.
 * New code will no longer "snap" windows to #MoveOffResistance
 * pixels off screen and instead movements will just be stopped and
 * then resume once movement of #MoveOffResistance have been attempted.
 *
 * 15-December-02 Bjorn Knutsson
 *
 ***********************************************************************/

#include "ctwm.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include <signal.h>
#include <sys/time.h>

#include "animate.h"
#include "add_window.h"
#include "cursor.h"
#include "drawing.h"
#include "gram.tab.h"
#include "iconmgr.h"
#include "icons.h"
#include "image.h"
#include "screen.h"
#include "util.h"
#include "vscreen.h"
#include "win_decorations.h"
#include "win_resize.h"


/* Handle for debug tracing */
FILE *tracefile = NULL;


/*
 * Rewrite this, possibly in terms of replace_substr().  Alternately, the
 * places it's being used might be better served by being preprocessed
 * into arrays anyway.
 */
char *ExpandFilePath(char *path)
{
	char *ret, *colon, *p;
	int  len;

	len = 0;
	p   = path;
	while((colon = strchr(p, ':'))) {
		len += colon - p + 1;
		if(*p == '~') {
			len += HomeLen - 1;
		}
		p = colon + 1;
	}
	if(*p == '~') {
		len += HomeLen - 1;
	}
	len += strlen(p);
	ret = malloc(len + 1);
	*ret = 0;

	p   = path;
	while((colon = strchr(p, ':'))) {
		*colon = '\0';
		if(*p == '~') {
			strcat(ret, Home);
			strcat(ret, p + 1);
		}
		else {
			strcat(ret, p);
		}
		*colon = ':';
		strcat(ret, ":");
		p = colon + 1;
	}
	if(*p == '~') {
		strcat(ret, Home);
		strcat(ret, p + 1);
	}
	else {
		strcat(ret, p);
	}
	return ret;
}

/***********************************************************************
 *
 *  Procedure:
 *      ExpandFilename - expand the tilde character to HOME
 *              if it is the first character of the filename
 *
 *  Returned Value:
 *      a pointer to the new name
 *
 *  Inputs:
 *      name    - the filename to expand
 *
 ***********************************************************************
 *
 * Currently only used in one place in image_bitmap.c.  I've left this
 * here instead of moving it into images at the moment on the assumption
 * that there might be other places in the codebase where it's useful.
 */
char *
ExpandFilename(const char *name)
{
	char *newname;

	/* If it doesn't start with ~/ then it's not our concern */
	if(name[0] != '~' || name[1] != '/') {
		return strdup(name);
	}

	asprintf(&newname, "%s/%s", Home, &name[1]);

	return newname;
}



/*
 * Some color utils
 */
/**
 * Get info from the server about a given color.
 */
void
GetColor(int kind, Pixel *what, const char *name)
{
	XColor color;
	Colormap cmap = Scr->RootColormaps.cwins[0]->colormap->c;

	// If we have no valid X connection (generally means a --cfgchk or
	// similar run; wont' happen in normal operations), just stub out.
	if(dpy == NULL) {
		*what = 0;
		return;
	}

#ifndef TOM
	if(!Scr->FirstTime) {
		return;
	}
#endif

	if(Scr->Monochrome != kind) {
		return;
	}

	if(! XParseColor(dpy, cmap, name, &color)) {
		fprintf(stderr, "%s:  invalid color name \"%s\"\n", ProgramName, name);
		return;
	}
	if(! XAllocColor(dpy, cmap, &color)) {
		/* if we could not allocate the color, let's see if this is a
		 * standard colormap
		 */
		XStandardColormap *stdcmap = NULL;

		if(! XParseColor(dpy, cmap, name, &color)) {
			fprintf(stderr, "%s:  invalid color name \"%s\"\n", ProgramName, name);
			return;
		}

		/*
		 * look through the list of standard colormaps (check cache first)
		 */
		if(Scr->StdCmapInfo.mru && Scr->StdCmapInfo.mru->maps &&
		                (Scr->StdCmapInfo.mru->maps[Scr->StdCmapInfo.mruindex].colormap ==
		                 cmap)) {
			stdcmap = &(Scr->StdCmapInfo.mru->maps[Scr->StdCmapInfo.mruindex]);
		}
		else {
			StdCmap *sc;

			for(sc = Scr->StdCmapInfo.head; sc; sc = sc->next) {
				int i;

				for(i = 0; i < sc->nmaps; i++) {
					if(sc->maps[i].colormap == cmap) {
						Scr->StdCmapInfo.mru = sc;
						Scr->StdCmapInfo.mruindex = i;
						stdcmap = &(sc->maps[i]);
						goto gotit;
					}
				}
			}
		}

gotit:
		if(stdcmap) {
			color.pixel = (stdcmap->base_pixel +
			               ((Pixel)(((float)color.red / 65535.0) *
			                        stdcmap->red_max + 0.5) *
			                stdcmap->red_mult) +
			               ((Pixel)(((float)color.green / 65535.0) *
			                        stdcmap->green_max + 0.5) *
			                stdcmap->green_mult) +
			               ((Pixel)(((float)color.blue  / 65535.0) *
			                        stdcmap->blue_max + 0.5) *
			                stdcmap->blue_mult));
		}
		else {
			fprintf(stderr, "%s:  unable to allocate color \"%s\"\n",
			        ProgramName, name);
			return;
		}
	}

	*what = color.pixel;
	return;
}


/**
 * Try and create a 'shaded' version of a color for prettier UI.
 */
void
GetShadeColors(ColorPair *cp)
{
	XColor      xcol;
	Colormap    cmap = Scr->RootColormaps.cwins[0]->colormap->c;
	bool        save;
	float       clearfactor;
	float       darkfactor;
	char        clearcol [32], darkcol [32];

	// If we have no valid X connection (generally means a --cfgchk or
	// similar run; wont' happen in normal operations), just stub out.
	if(dpy == NULL) {
		cp->shadc = 0;
		cp->shadd = 0;
		return;
	}

	clearfactor = (float) Scr->ClearShadowContrast / 100.0;
	darkfactor  = (100.0 - (float) Scr->DarkShadowContrast)  / 100.0;
	xcol.pixel = cp->back;
	XQueryColor(dpy, cmap, &xcol);

	sprintf(clearcol, "#%04x%04x%04x",
	        xcol.red   + (unsigned short)((65535 -   xcol.red) * clearfactor),
	        xcol.green + (unsigned short)((65535 - xcol.green) * clearfactor),
	        xcol.blue  + (unsigned short)((65535 -  xcol.blue) * clearfactor));
	sprintf(darkcol,  "#%04x%04x%04x",
	        (unsigned short)(xcol.red   * darkfactor),
	        (unsigned short)(xcol.green * darkfactor),
	        (unsigned short)(xcol.blue  * darkfactor));

	save = Scr->FirstTime;
	Scr->FirstTime = true;
	GetColor(Scr->Monochrome, &cp->shadc, clearcol);
	GetColor(Scr->Monochrome, &cp->shadd,  darkcol);
	Scr->FirstTime = save;
}



/*
 * Various font utils
 */
/**
 * Try adjusting a font's height.  Used in drawing the icon manager.
 */
bool
UpdateFont(MyFont *font, int height)
{
	int prev = font->avg_height;
	font->avg_fheight = (font->avg_fheight * font->avg_count + height)
	                    / (font->avg_count + 1);
	font->avg_count++;
	/* Arbitrary limit.  */
	if(font->avg_count >= 256) {
		font->avg_count = 256;
	}
	font->avg_height = (int)(font->avg_fheight + 0.5);
	/* fprintf (stderr, "Updating avg with %d(%d) + %d -> %d(%f)\n",
	 *       prev, font->avg_count, height,
	 *       font->avg_height, font->avg_fheight); */
	return (prev != font->avg_height);
}


/**
 * Load up fontsets from the X server.  Only used by CreateFonts() below.
 */
static void
GetFont(MyFont *font)
{
	char *deffontname = "fixed,*";
	char **missing_charset_list_return;
	int missing_charset_count_return;
	char *def_string_return;
	XFontSetExtents *font_extents;
	XFontStruct **xfonts;
	char **font_names;
	int i;
	int ascent;
	int descent;
	int fnum;
	char *basename2;

	// In special cases where we have no dpy, I don't think we're going
	// to need details here, so just leave things untouched.  We may need
	// to stub in some magic values; deal with that when we run into the
	// case.
	if(dpy == NULL) {
		return;
	}

	if(font->font_set != NULL) {
		XFreeFontSet(dpy, font->font_set);
	}

	asprintf(&basename2, "%s,*", font->basename);
	if((font->font_set = XCreateFontSet(dpy, basename2,
	                                    &missing_charset_list_return,
	                                    &missing_charset_count_return,
	                                    &def_string_return)) == NULL) {
		fprintf(stderr, "Failed to get fontset %s\n", basename2);
		if(Scr->DefaultFont.basename) {
			deffontname = Scr->DefaultFont.basename;
		}
		if((font->font_set = XCreateFontSet(dpy, deffontname,
		                                    &missing_charset_list_return,
		                                    &missing_charset_count_return,
		                                    &def_string_return)) == NULL) {
			fprintf(stderr, "%s:  unable to open fonts \"%s\" or \"%s\"\n",
			        ProgramName, font->basename, deffontname);
			exit(1);
		}
	}
	free(basename2);
	font_extents = XExtentsOfFontSet(font->font_set);

	fnum = XFontsOfFontSet(font->font_set, &xfonts, &font_names);
	for(i = 0, ascent = 0, descent = 0; i < fnum; i++) {
		ascent = MaxSize(ascent, (*xfonts)->ascent);
		descent = MaxSize(descent, (*xfonts)->descent);
		xfonts++;
	}

	font->height = font_extents->max_logical_extent.height;
	font->y = ascent;
	font->ascent = ascent;
	font->descent = descent;
	font->avg_height = 0;
	font->avg_fheight = 0.0;
	font->avg_count = 0;
}


/**
 * Load up our various defined fonts
 */
void
CreateFonts(ScreenInfo *scr)
{
#define LOADFONT(fld) (GetFont(&scr->fld##Font))
	LOADFONT(TitleBar);
	LOADFONT(Menu);
	LOADFONT(Icon);
	LOADFONT(Size);
	LOADFONT(IconManager);
	LOADFONT(Default);
	LOADFONT(workSpaceMgr.window);
#undef LOADFONT

	scr->HaveFonts = true;
}



#if 0
static void move_to_head(TwmWindow *t)
{
	if(t == NULL) {
		return;
	}
	if(Scr->FirstWindow == t) {
		return;
	}

	/* Unlink t from current position */
	if(t->prev) {
		t->prev->next = t->next;
	}
	if(t->next) {
		t->next->prev = t->prev;
	}

	/* Re-link t at head */
	t->next = Scr->FirstWindow;
	if(Scr->FirstWindow != NULL) {
		Scr->FirstWindow->prev = t;
	}
	t->prev = NULL;
	Scr->FirstWindow = t;
}

/*
 * Moves window 't' after window 'after'.
 *
 * If 'after' == NULL, puts it at the head.
 * If 't' == NULL, does nothing.
 * If the 't' is already after 'after', does nothing.
 */

void move_to_after(TwmWindow *t, TwmWindow *after)
{
	if(after == NULL) {
		move_to_head(t);
		return;
	}
	if(t == NULL) {
		return;
	}
	if(after->next == t) {
		return;
	}

	/* Unlink t from current position */
	if(t->prev) {
		t->prev->next = t->next;
	}
	if(t->next) {
		t->next->prev = t->prev;
	}

	/* Re-link t after 'after' */
	t->next = after->next;
	if(after->next) {
		after->next->prev = t;
	}
	t->prev = after;
	after->next = t;
}
#endif



/**
 * Backend for f.rescuewindows
 */
void RescueWindows(void)
{
	TwmWindow *twm_win = Scr->FirstWindow;

	while(twm_win) {
		VirtualScreen *vs = twm_win->vs;
		if(vs) {
			/*
			 * Check if this window seems completely out of sight.
			 */
			int x = twm_win->frame_x;
			int y = twm_win->frame_y;
			int w = twm_win->frame_width;
			int h = twm_win->frame_height;
			int bw = twm_win->frame_bw;
			int fullw = w + 2 * bw;
			int fullh = h + 2 * bw;
			int old_x = x, old_y = y;
			struct Icon *i;

#define MARGIN  20

			if(x >= vs->w - MARGIN) {
				x = vs->w - fullw;
			}
			if(y >= vs->h - MARGIN) {
				y = vs->h - fullh;
			}
			if((x + fullw <= MARGIN)) {
				x = 0;
			}
			if((y + fullh <= MARGIN)) {
				y = 0;
			}

			if(x != old_x || y != old_y) {
				SetupWindow(twm_win, x, y, w, h, -1);
			}

			/*
			 * If there is an icon, check it too.
			 */
			i = twm_win->icon;
			if(i != NULL) {
				x = i->w_x;
				y = i->w_y;
				w = i->w_width;
				h = i->w_height;
				old_x = x;
				old_y = y;

				if(x >= vs->w - MARGIN) {
					x = vs->w - w;
				}
				if(y >= vs->h - MARGIN) {
					y = vs->h - h;
				}
				if((x + w <= MARGIN)) {
					x = 0;
				}
				if((y + h <= MARGIN)) {
					y = 0;
				}

				if(x != old_x || y != old_y) {
					XMoveWindow(dpy, i->w, x, y);
					i->w_x = x;
					i->w_y = y;
				}
			}
#undef MARGIN
		}
		twm_win = twm_win->next;
	}
}



/**
 * Backend for f.trace
 */
void
DebugTrace(char *file)
{
	if(!file) {
		return;
	}
	if(tracefile) {
		fprintf(stderr, "stop logging events\n");
		if(tracefile != stderr) {
			fclose(tracefile);
		}
		tracefile = NULL;
	}
	else {
		if(strcmp(file, "stderr")) {
			tracefile = fopen(file, "w");
		}
		else {
			tracefile = stderr;
		}
		fprintf(stderr, "logging events to : %s\n", file);
	}
}



/*
 * A safe strncpy(), which always ensures NUL-termination.
 *
 * XXX This is really just a slightly pessimized implementation of
 * strlcpy().  Maybe we should use that instead, with a local
 * implementation for systems like glibc-users that lack it?
 */
void
safe_strncpy(char *dest, const char *src, size_t size)
{
	strncpy(dest, src, size - 1);
	dest[size - 1] = '\0';
}