summaryrefslogtreecommitdiff
path: root/src/wcmConfig.c
blob: 7b85b8f681ecd4d5c343253207f6474cbb64500f (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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
/*
 * Copyright 1995-2002 by Frederic Lepied, France. <Lepied@XFree86.org>
 * Copyright 2002-2013 by Ping Cheng, Wacom. <pingc@wacom.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <config.h>

#include "xf86Wacom.h"
#include "wcmFilter.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <wacom-properties.h>

/*****************************************************************************
 * wcmAllocate --
 * Allocate the generic bits needed by any wacom device, regardless of type.
 ****************************************************************************/

WacomDevicePtr wcmAllocate(InputInfoPtr pInfo, const char *name)
{
	WacomDevicePtr   priv   = NULL;
	WacomCommonPtr   common = NULL;
	WacomToolPtr     tool   = NULL;
	int i;

	priv = calloc(1, sizeof(WacomDeviceRec));
	if (!priv)
		goto error;

	common = wcmNewCommon();
	if (!common)
		goto error;

	tool = calloc(1, sizeof(WacomTool));
	if(!tool)
		goto error;

	priv->next = NULL;
	priv->name = strdup(name);
	priv->pInfo = pInfo;
	priv->common = common;       /* common info pointer */
	priv->oldCursorHwProx = 0;   /* previous cursor hardware proximity */
	priv->maxCurve = FILTER_PRESSURE_RES;
	priv->nPressCtrl [0] = 0;    /* pressure curve x0 */
	priv->nPressCtrl [1] = 0;    /* pressure curve y0 */
	priv->nPressCtrl [2] = 100;  /* pressure curve x1 */
	priv->nPressCtrl [3] = 100;  /* pressure curve y1 */

	/* Default button and expresskey values, offset buttons 4 and higher
	 * by the 4 scroll buttons. */
	for (i=0; i<WCM_MAX_BUTTONS; i++)
		priv->button_default[i] = (i < 3) ? i + 1 : i + 5;

	priv->nbuttons = WCM_MAX_BUTTONS;       /* Default number of buttons */
	priv->wheel_default[WHEEL_REL_UP] = 5;
	priv->wheel_default[WHEEL_REL_DN] = 4;
	/* wheel events are set to 0, but the pad overwrites this default
	 * later in wcmParseOptions, when we have IsPad() available */
	priv->wheel_default[WHEEL_ABS_UP] = 0;
	priv->wheel_default[WHEEL_ABS_DN] = 0;
	priv->wheel_default[WHEEL2_ABS_UP] = 0;
	priv->wheel_default[WHEEL2_ABS_DN] = 0;
	priv->strip_default[STRIP_LEFT_UP] = 4;
	priv->strip_default[STRIP_LEFT_DN] = 5;
	priv->strip_default[STRIP_RIGHT_UP] = 4;
	priv->strip_default[STRIP_RIGHT_DN] = 5;
	priv->naxes = 6;			/* Default number of axes */

	common->wcmDevices = priv;

	/* tool */
	priv->tool = tool;
	common->wcmTool = tool;
	tool->next = NULL;          /* next tool in list */
	tool->device = priv;
	/* tool->typeid is set once we know the type - see wcmSetType */

	/* timers */
	priv->serial_timer = TimerSet(NULL, 0, 0, NULL, NULL);
	priv->tap_timer = TimerSet(NULL, 0, 0, NULL, NULL);
	priv->touch_timer = TimerSet(NULL, 0, 0, NULL, NULL);

	return priv;

error:
	free(tool);
	wcmFreeCommon(&common);
	if (priv) {
		free(priv->name);
	}
	free(priv);
	return NULL;
}

/*****************************************************************************
 * wcmFree --
 * Free the memory allocated by wcmAllocate
 ****************************************************************************/

static void wcmFree(WacomDevicePtr priv)
{
	if (!priv)
		return;

	TimerFree(priv->serial_timer);
	TimerFree(priv->tap_timer);
	TimerFree(priv->touch_timer);
	free(priv->tool);
	wcmFreeCommon(&priv->common);
	free(priv->name);
	free(priv);
}

TEST_NON_STATIC int
wcmSetType(WacomDevicePtr priv, const char *type)
{
	InputInfoPtr pInfo = priv->pInfo;

	if (!type)
		goto invalid;

	if (strcasecmp(type, "stylus") == 0)
	{
		priv->flags = ABSOLUTE_FLAG|STYLUS_ID;
		pInfo->type_name = WACOM_PROP_XI_TYPE_STYLUS;
	} else if (strcasecmp(type, "touch") == 0)
	{
		int flags = TOUCH_ID;

		if (TabletHasFeature(priv->common, WCM_LCD))
			flags |= ABSOLUTE_FLAG;

		priv->flags = flags;
		pInfo->type_name = WACOM_PROP_XI_TYPE_TOUCH;
	} else if (strcasecmp(type, "cursor") == 0)
	{
		priv->flags = CURSOR_ID;
		pInfo->type_name = WACOM_PROP_XI_TYPE_CURSOR;
	} else if (strcasecmp(type, "eraser") == 0)
	{
		priv->flags = ABSOLUTE_FLAG|ERASER_ID;
		pInfo->type_name = WACOM_PROP_XI_TYPE_ERASER;
	} else if (strcasecmp(type, "pad") == 0)
	{
		priv->flags = ABSOLUTE_FLAG|PAD_ID;
		pInfo->type_name = WACOM_PROP_XI_TYPE_PAD;
	} else
		goto invalid;

	/* Set the device id of the "last seen" device on this tool */
	priv->oldState.device_id = wcmGetPhyDeviceID(priv);

	if (!priv->tool)
		return 0;

	priv->tool->typeid = DEVICE_ID(priv->flags); /* tool type (stylus/touch/eraser/cursor/pad) */

	return 1;

invalid:
	wcmLog(priv, W_ERROR,
		    "No type or invalid type specified.\n"
		    "Must be one of stylus, touch, cursor, eraser, or pad\n");

	return 0;
}

int wcmGetPhyDeviceID(WacomDevicePtr priv)
{
	if (IsStylus(priv))
		return STYLUS_DEVICE_ID;
	else if (IsEraser(priv))
		return ERASER_DEVICE_ID;
	else if (IsCursor(priv))
		return CURSOR_DEVICE_ID;
	else if (IsTouch(priv))
		return TOUCH_DEVICE_ID;
	else
		return PAD_DEVICE_ID;
}

void wcmUnInit(WacomDevicePtr priv)
{
	WacomDevicePtr dev;
	WacomDevicePtr *prev;
	WacomCommonPtr common;

	if (!priv)
		goto out;

	common = priv->common;

	DBG(1, priv, "\n");

	wcmRemoveActive(priv);

	if (priv->tool)
	{
		WacomToolPtr *prev_tool = &common->wcmTool;
		WacomToolPtr tool = *prev_tool;
		while (tool)
		{
			if (tool == priv->tool)
			{
				*prev_tool = tool->next;
				break;
			}
			prev_tool = &tool->next;
			tool = tool->next;
		}
	}

	prev = &common->wcmDevices;
	dev = *prev;
	while(dev)
	{
		if (dev == priv)
		{
			*prev = dev->next;
			break;
		}
		prev = &dev->next;
		dev = dev->next;
	}

out:
	wcmFree(priv);
}

static void wcmEnableDisableTool(WacomDevicePtr priv, Bool enable)
{
	WacomToolPtr	tool	= priv->tool;

	tool->enabled = enable;
}

void wcmEnableTool(WacomDevicePtr priv)
{
	wcmEnableDisableTool(priv, TRUE);
}
void wcmDisableTool(WacomDevicePtr priv)
{
	wcmEnableDisableTool(priv, FALSE);
}

/**
 * Unlink the touch tool from the pen of the same device
 */
void wcmUnlinkTouchAndPen(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;
	InputInfoPtr device = xf86FirstLocalDevice();
	WacomCommonPtr tmpcommon = NULL;
	WacomDevicePtr tmppriv = NULL;
	Bool touch_device = FALSE;

	if (!TabletHasFeature(common, WCM_PENTOUCH))
		return;

	/* Lookup to find the associated pen and touch */
	for (; device != NULL; device = device->next)
	{
		if (!strcmp(device->drv->driverName, "wacom"))
		{
			tmppriv = (WacomDevicePtr) device->private;
			tmpcommon = tmppriv->common;
			touch_device = (common->wcmTouchDevice ||
						tmpcommon->wcmTouchDevice);

			/* skip the same tool or unlinked devices */
			if ((tmppriv == priv) || !touch_device)
				continue;

			if (tmpcommon->tablet_id == common->tablet_id)
			{
				common->wcmTouchDevice = NULL;
				tmpcommon->wcmTouchDevice = NULL;
				common->tablet_type &= ~WCM_PENTOUCH;
				tmpcommon->tablet_type &= ~WCM_PENTOUCH;
				return;
			}
		}
	}
}

/**
 * Splits a wacom device name into its constituent pieces. For instance,
 * "Wacom Intuos Pro Finger touch" would be split into "Wacom Intuos Pro"
 * (the base kernel device name), "Finger" (an descriptor of the specific
 * event interface), and "touch" (a suffix added by this driver to indicate
 * the specific tool).
 */
static void wcmSplitName(char* devicename, char *basename, char *subdevice, char *tool, size_t len)
{
	char *name = strdupa(devicename);
	char *a, *b;

	*basename = *subdevice = *tool = '\0';

	a = strrchr(name, ' ');
	if (a)
	{
		*a = '\0';
		b = strrchr(name, ' ');

		while (b)
		{
			if (!strcmp(b, " Pen") || !strcmp(b, " Finger") ||
			    !strcmp(b, " Pad") || !strcmp(b, " Touch"))
			{
				*b = '\0';
				strncpy(subdevice, b+1, len-1);
				subdevice[len-1] = '\0';
				b = strrchr(name, ' ');
			}
			else
				b = NULL;
		}
		strncat(tool, a+1, len-1);
	}
	strncat(basename, name, len-1);
}

/**
 * Determines if two input devices represent independent parts (stylus,
 * eraser, pad) of the same underlying device. If the 'logical_only'
 * flag is set, the function will only return true if the two devices
 * are represented by the same logical device (i.e., share the same
 * input device node). Otherwise, the function will attempt to determine
 * if the two devices are part of the same physical tablet, such as
 * when a tablet reports 'pen' and 'touch' through separate device
 * nodes.
 */
static Bool wcmIsSiblingDevice(InputInfoPtr a, InputInfoPtr b, Bool logical_only)
{
	WacomDevicePtr privA = (WacomDevicePtr)a->private;
	WacomDevicePtr privB = (WacomDevicePtr)b->private;

	if (strcmp(a->drv->driverName, "wacom") || strcmp(b->drv->driverName, "wacom"))
		return FALSE;

	if (privA == privB)
		return FALSE;

	if (DEVICE_ID(privA->flags) == DEVICE_ID(privB->flags))
		return FALSE;

	if (!strcmp(privA->common->device_path, privB->common->device_path))
		return TRUE;

	if (!logical_only)
	{
		// TODO: Udev might provide more accurate data, but this should
		// be good enough in practice.
		const int len = 50;
		char baseA[len], subA[len], toolA[len];
		char baseB[len], subB[len], toolB[len];
		wcmSplitName(privA->name, baseA, subA, toolA, len);
		wcmSplitName(privB->name, baseB, subB, toolB, len);

		if (strcmp(baseA, baseB))
		{
			// Fallback for (arbitrary) static xorg.conf device names
			return (privA->common->tablet_id == privB->common->tablet_id);
		}

		if (strlen(subA) != 0 && strlen(subB) != 0)
			return TRUE;
	}

	return FALSE;
}

/* wcmMatchDevice - locate matching device and merge common structure. If an
 * already initialized device shares the same device file and driver, remove
 * the new device's "common" struct and point to the one of the already
 * existing one instead.
 * Then add the new device to the now-shared common struct.
 *
 * Returns 1 on a found match or 0 otherwise.
 * Common_return is set to the common struct in use by this device.
 */
static Bool wcmMatchDevice(WacomDevicePtr priv, WacomCommonPtr *common_return)
{
	InputInfoPtr pLocal = priv->pInfo;
	WacomCommonPtr common = priv->common;
	InputInfoPtr pMatch = xf86FirstLocalDevice();

	*common_return = common;

	if (!common->device_path)
		return 0;

	for (; pMatch != NULL; pMatch = pMatch->next)
	{
		WacomDevicePtr privMatch = (WacomDevicePtr)pMatch->private;

		if (wcmIsSiblingDevice(pLocal, pMatch, TRUE))
		{
			DBG(2, priv, "port share between %s and %s\n",
					pLocal->name, pMatch->name);
			/* FIXME: we loose the common->wcmTool here but it
			 * gets re-added during wcmParseOptions. This is
			 * currently required by the code, adding the tool
			 * again here means we trigger the duplicate tool
			 * detection */
			wcmFreeCommon(&priv->common);
			priv->common = wcmRefCommon(privMatch->common);
			priv->next = priv->common->wcmDevices;
			priv->common->wcmDevices = priv;
			*common_return = priv->common;
			return 1;
		}
	}
	return 0;
}

/**
 * Detect the device's device class. We only support two classes right now,
 * USB and ISDV4. Let each class try to detect the type by checking what's
 * behind the fd.
 */
static Bool
wcmDetectDeviceClass(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;

	if (common->wcmDevCls)
		return TRUE;

	/* Bluetooth is also considered as USB */
	if (gWacomISDV4Device.Detect(priv))
		common->wcmDevCls = &gWacomISDV4Device;
	else if (gWacomUSBDevice.Detect(priv))
		common->wcmDevCls = &gWacomUSBDevice;
	else
		wcmLog(priv, W_ERROR, "cannot identify device class.\n");

	return (common->wcmDevCls != NULL);
}

static Bool
wcmInitModel(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;

	/* Initialize the tablet */
	if(common->wcmDevCls->Init(priv) != Success ||
		wcmInitTablet(priv) != Success)
		return FALSE;

	return TRUE;
}

/**
 * Lookup to find the associated pen and touch for the same device.
 * Store touch tool in wcmTouchDevice for pen and touch, respectively,
 * of the same device. Update TabletFeature to indicate it is a hybrid
 * of touch and pen.
 *
 * @return True if found a touch tool for hybrid devices.
 * false otherwise.
 */
static Bool wcmLinkTouchAndPen(WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	WacomCommonPtr common = priv->common;
	InputInfoPtr device = xf86FirstLocalDevice();
	WacomCommonPtr tmpcommon = NULL;
	WacomDevicePtr tmppriv = NULL;

	if (IsPad(priv))
	{
		DBG(4, priv, "No need to link up pad devices.\n");
		return FALSE;
	}

	/* Lookup to find the associated pen and touch */
	for (; device != NULL; device = device->next)
	{
		if (!wcmIsSiblingDevice(pInfo, device, FALSE))
			continue;

		tmppriv = (WacomDevicePtr) device->private;
		tmpcommon = tmppriv->common;

		DBG(4, priv, "Considering link with %s...\n", tmppriv->name);

		/* already linked devices */
		if (tmpcommon->wcmTouchDevice)
		{
			DBG(4, priv, "A link is already in place. Ignoring.\n");
			continue;
		}

		if (IsTouch(tmppriv))
		{
			common->wcmTouchDevice = tmppriv;
			tmpcommon->wcmTouchDevice = tmppriv;
		}
		else if (IsTouch(priv))
		{
			common->wcmTouchDevice = priv;
			tmpcommon->wcmTouchDevice = priv;
		}
		else
		{
			DBG(4, priv, "A link is not necessary. Ignoring.\n");
		}

		if ((common->wcmTouchDevice && IsTablet(priv)) ||
			(tmpcommon->wcmTouchDevice && IsTablet(tmppriv)))
		{
			TabletSetFeature(common, WCM_PENTOUCH);
			TabletSetFeature(tmpcommon, WCM_PENTOUCH);
		}

		if (common->wcmTouchDevice)
		{
			DBG(4, priv, "Link created!\n");
			return TRUE;
		}
	}
	DBG(4, priv, "No suitable device to link with found.\n");
	return FALSE;
}

/**
 * Check if this device was hotplugged by the driver by checking the _source
 * option.
 *
 * Must be called before wcmNeedAutoHotplug()
 *
 * @return True if the source for this device is the wacom driver itself or
 * false otherwise.
 */
static int wcmIsHotpluggedDevice(WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	char *source = xf86CheckStrOption(pInfo->options, "_source", "");
	int matches = (strcmp(source, "_driver/wacom") == 0);
	free(source);
	return matches;
}

static Bool wcmIsWacomDevice (char* fname)
{
	int fd = -1;
	struct input_id id;

	SYSCALL(fd = open(fname, O_RDONLY));
	if (fd < 0)
		return FALSE;

	if (ioctl(fd, EVIOCGID, &id) < 0)
	{
		SYSCALL(close(fd));
		return FALSE;
	}

	SYSCALL(close(fd));

	switch(id.vendor)
	{
		case WACOM_VENDOR_ID:
		case WALTOP_VENDOR_ID:
		case HANWANG_VENDOR_ID:
		case LENOVO_VENDOR_ID:
			return TRUE;
		default:
			break;
	}
	return FALSE;
}

/*****************************************************************************
 * wcmEventAutoDevProbe -- Probe for right input device
 ****************************************************************************/
#define DEV_INPUT_EVENT "/dev/input/event%d"
#define EVDEV_MINORS    32
char *wcmEventAutoDevProbe (WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	/* We are trying to find the right eventX device */
	int i = 0, wait = 0;
	const int max_wait = 2000;

	/* If device is not available after Resume, wait some ms */
	while (wait <= max_wait)
	{
		for (i = 0; i < EVDEV_MINORS; i++)
		{
			char fname[64];
			Bool is_wacom;

			sprintf(fname, DEV_INPUT_EVENT, i);
			is_wacom = wcmIsWacomDevice(fname);
			if (is_wacom)
			{
				wcmLog(priv, W_PROBED, "probed device is %s (waited %d msec)\n", fname, wait);
				xf86ReplaceStrOption(pInfo->options, "Device", fname);

				/* this assumes there is only one Wacom device on the system */
				return xf86CheckStrOption(pInfo->options, "Device", NULL);
			}
		}
		wait += 100;
		wcmLog(priv, W_ERROR, "waiting 100 msec (total %dms) for device to become ready\n", wait);
		usleep(100*1000);
	}
	wcmLog(priv, W_ERROR,
		    "no Wacom event device found (checked %d nodes, waited %d msec)\n", i + 1, wait);
	wcmLog(priv, W_ERROR, "unable to probe device\n");
	return NULL;
}

/*****************************************************************************
 * wcmInitialToolSize --
 *    Initialize logical size and resolution for individual tool.
 ****************************************************************************/

TEST_NON_STATIC void
wcmInitialToolSize(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;

	/* assign max and resolution here since we don't get them during
	 * the configuration stage */
	if (IsTouch(priv))
	{
		priv->maxX = common->wcmMaxTouchX;
		priv->maxY = common->wcmMaxTouchY;
		priv->resolX = common->wcmTouchResolX;
		priv->resolY = common->wcmTouchResolY;
	}
	else
	{
		priv->minX = common->wcmMinX;
		priv->minY = common->wcmMinY;
		priv->maxX = common->wcmMaxX;
		priv->maxY = common->wcmMaxY;
		priv->resolX = common->wcmResolX;
		priv->resolY = common->wcmResolY;
	}

	if (!priv->topX)
		priv->topX = priv->minX;
	if (!priv->topY)
		priv->topY = priv->minY;
	if (!priv->bottomX)
		priv->bottomX = priv->maxX;
	if (!priv->bottomY)
		priv->bottomY = priv->maxY;

	return;
}

static void wcmInitActions(WacomDevicePtr priv)
{
	int i;

	for (i = 0; i < priv->nbuttons; i++)
		wcmResetButtonAction(priv, i);

	if (IsPad(priv)) {
		for (i = 0; i < 4; i++)
			wcmResetStripAction(priv, i);
	}

	if (IsPad(priv) || IsCursor(priv))
	{
		for (i = 0; i < 6; i++)
			wcmResetWheelAction(priv, i);
	}
}

/* wcmPreInit - called for each input devices with the driver set to
 * "wacom" */
int wcmPreInit(WacomDevicePtr priv)
{
	InputInfoPtr   pInfo = priv->pInfo;
	WacomCommonPtr common = NULL;
	char		*type = NULL, *device = NULL;
	char		*oldname = NULL;
	int		need_hotplug = 0, is_dependent = 0;
	int		fd = -1;

	/*
	   Init process:
	   - if no device is given, auto-probe for one (find a wacom device
	     in /dev/input/event?
	   - open the device file
	   - probe the device
	   - remove duplicate devices if needed
	   - set the device type
	   - hotplug dependent devices if needed
	 */

	device = xf86SetStrOption(pInfo->options, "Device", NULL);
	type = xf86SetStrOption(pInfo->options, "Type", NULL);
	if (!device && !(device = wcmEventAutoDevProbe(priv)))
		goto SetupProc_fail;

	priv->common->device_path = device;
	priv->debugLevel = xf86SetIntOption(pInfo->options,
					    "DebugLevel", priv->debugLevel);

	/* check if the same device file has been added already */
	if (wcmIsDuplicate(device, priv))
		goto SetupProc_fail;

	if ((fd = wcmOpen(priv)) < 0)
		goto SetupProc_fail;
	pInfo->fd = fd;

	/* Try to guess whether it's USB or ISDV4 */
	if (!wcmDetectDeviceClass(priv))
		goto SetupProc_fail;

	/* check if this is the first tool on the port */
	if (!wcmMatchDevice(priv, &common))
		/* initialize supported keys with the first tool on the port */
		wcmDeviceTypeKeys(priv);

	common->debugLevel = xf86SetIntOption(pInfo->options,
					      "CommonDBG", common->debugLevel);
	oldname = strdup(pInfo->name);

	if (wcmIsHotpluggedDevice(priv))
		is_dependent = 1;
	else if ((need_hotplug = wcmNeedAutoHotplug(priv, &type)))
	{
		/* we need subdevices, change the name so all of them have a
		   type. */
		char *new_name;
		if (asprintf(&new_name, "%s %s", pInfo->name, type) == -1)
			new_name = strdup(pInfo->name);
		free(pInfo->name);
		free(priv->name);
		pInfo->name = new_name;
		priv->name = strdup(new_name);
	}

	/* check if the type is valid for those don't need hotplug */
	if(!need_hotplug && !wcmIsAValidType(priv, type)) {
		wcmLog(priv, W_ERROR, "Invalid type '%s' for this device.\n", type);
		goto SetupProc_fail;
	}

	if (!wcmSetType(priv, type))
		goto SetupProc_fail;

	if (!wcmPreInitParseOptions(priv, need_hotplug, is_dependent))
		goto SetupProc_fail;

	if (!wcmInitModel(priv))
		goto SetupProc_fail;

	if (!wcmPostInitParseOptions(priv, need_hotplug, is_dependent))
		goto SetupProc_fail;

	if (!IsPad(priv))
		wcmInitialToolSize(priv);

	wcmInitActions(priv);

	if (need_hotplug)
	{
		priv->isParent = 1;
		wcmHotplugOthers(priv, oldname);
	}

	wcmClose(priv);

	/* only link them once per port. We need to try for both tablet tool
	 * and touch since we do not know which tool will be added first.
	 */
	if (IsTouch(priv) || (IsTablet(priv) && !common->wcmTouchDevice))
		wcmLinkTouchAndPen(priv);

	free(type);
	free(oldname);

	return Success;

SetupProc_fail:
	/* restart the device list from the next one */
	if (common && priv)
		common->wcmDevices = priv->next;

	wcmClose(priv);
	free(type);
	free(oldname);
	return BadMatch;
}


/*****************************************************************************
 * wcmDevOpen --
 *    Open the physical device and init information structs.
 ****************************************************************************/

int wcmDevOpen(WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	WacomCommonPtr common = priv->common;
	struct stat st;

	DBG(10, priv, "\n");

	/* open file, if not already open */
	if (common->fd_refs == 0)
	{
		int fd = -1;

		if (!common->device_path) {
			DBG(1, priv, "Missing common device path\n");
			return FALSE;
		}
		if ((fd = wcmOpen(priv)) < 0)
			return FALSE;

		if (fstat(fd, &st) == -1)
		{
			/* can not access major/minor */
			DBG(1, priv, "stat failed (%s).\n", strerror(errno));

			/* older systems don't support the required ioctl.
			 * So, we have to let it pass */
			common->min_maj = 0;
		}
		else
			common->min_maj = st.st_rdev;
		common->fd = fd;
		common->fd_refs = 1;
	}

	/* Grab the common descriptor, if it's available */
	if (pInfo->fd < 0)
	{
		pInfo->fd = common->fd;
		common->fd_refs++;
	}

	return TRUE;
}

/**
 * Initialize the device axes with their proper attributes.
 *
 * For each axis on the device, we need to provide X with its attributes
 * so that its values can be interpreted properly. To support older X
 * servers without axis labels, each axis index has a de-facto meaning.
 * Any de-facto defined axis index left unused is initialized with default
 * attributes.
 */
static int wcmInitAxes(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;
	int min, max, res;

	/* first valuator: x */
	min = priv->topX;
	max = priv->bottomX;
	res = priv->resolX;
	wcmInitAxis(priv, WACOM_AXIS_X, min, max, res);


	/* second valuator: y */
	min = priv->topY;
	max = priv->bottomY;
	res = priv->resolY;
	wcmInitAxis(priv, WACOM_AXIS_Y, min, max, res);

	/* third valuator: pressure */
	if (!IsPad(priv))
	{
		res = 0;
		min = 0;
		max = priv->maxCurve;
		wcmInitAxis(priv, WACOM_AXIS_PRESSURE, min, max, res);
	}
	/* FIXME: how to set up this axis on the pad? */

	/* fourth valuator: tilt-x, cursor:z-rotation, pad:strip-x */
	res = 0;
	if (IsPen(priv))
	{
		res = round(TILT_RES);
		min = TILT_MIN;
		max = TILT_MAX;
		wcmInitAxis(priv, WACOM_AXIS_TILT_X, min, max, res);
	}
	else if (IsCursor(priv))
	{
		min = MIN_ROTATION;
		max = MIN_ROTATION + MAX_ROTATION_RANGE - 1;
		wcmInitAxis(priv, WACOM_AXIS_ROTATION, min, max, res);
	}
	else if (IsPad(priv) && TabletHasFeature(common, WCM_STRIP))
	{
		min = 0;
		max = common->wcmMaxStripX;
		wcmInitAxis(priv, WACOM_AXIS_STRIP_X, min, max, res);
	}

	/* fifth valuator: tilt-y, cursor:throttle, pad:strip-y */
	res = 0;
	if (IsPen(priv))
	{
		res = round(TILT_RES);
		min = TILT_MIN;
		max = TILT_MAX;
		wcmInitAxis(priv, WACOM_AXIS_TILT_Y, min, max, res);
	}
	else if (IsCursor(priv))
	{
		min = -1023;
		max = 1023;
		wcmInitAxis(priv, WACOM_AXIS_THROTTLE, min, max, res);
	}
	else if (IsPad(priv) && TabletHasFeature(common, WCM_STRIP))
	{
		min = 0;
		max = common->wcmMaxStripY;
		wcmInitAxis(priv, WACOM_AXIS_STRIP_Y, min, max, res);
	}

	/* sixth valuator: airbrush: abs-wheel, artpen: rotation, pad:abs-wheel */
	res = 0;
	if (IsStylus(priv))
	{
		max = MAX_ROTATION_RANGE + MIN_ROTATION - 1;
		min = MIN_ROTATION;
		wcmInitAxis(priv, WACOM_AXIS_WHEEL, min, max, res);
	}
	else if ((TabletHasFeature(common, WCM_RING)) && IsPad(priv))
	{
		/* Touch ring */
		min = common->wcmMinRing;
		max = common->wcmMaxRing;
		wcmInitAxis(priv, WACOM_AXIS_RING, min, max, res);
	}

	/* seventh valuator: abswheel2 */
	if ((TabletHasFeature(common, WCM_DUALRING)) && IsPad(priv))
	{
		res = 0;
		min = common->wcmMinRing;
		max = common->wcmMaxRing;
		wcmInitAxis(priv, WACOM_AXIS_RING2, min, max, res);
	}

	return TRUE;
}

int wcmDevInit(WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	WacomCommonPtr common =	priv->common;
	int nbaxes, nbbuttons, nbkeys;

	/* Detect tablet configuration, if possible */
	if (priv->common->wcmModel->DetectConfig)
		priv->common->wcmModel->DetectConfig (priv);

	nbaxes = priv->naxes;       /* X, Y, Pressure, Tilt-X, Tilt-Y, Wheel */
	if (!nbaxes || nbaxes > 7)
		nbaxes = priv->naxes = 7;
	nbbuttons = priv->nbuttons; /* Use actual number of buttons, if possible */

	if (IsPad(priv) && TabletHasFeature(priv->common, WCM_DUALRING))
		nbaxes = priv->naxes = nbaxes + 1; /* ABS wheel 2 */

	/* if more than 3 buttons, offset by the four scroll buttons,
	 * otherwise, alloc 7 buttons for scroll wheel. */
	nbbuttons = min(max(nbbuttons + 4, 7), WCM_MAX_BUTTONS);
	nbkeys = nbbuttons;         /* Same number of keys since any button may be
	                             * configured as an either mouse button or key */

	DBG(10, priv,
		"(%s) %d buttons, %d keys, %d axes\n",
		pInfo->type_name,
		nbbuttons, nbkeys, nbaxes);

	if (!wcmInitButtons(priv, nbbuttons))
	{
		wcmLog(priv, W_ERROR, "unable to allocate Button class device\n");
		return FALSE;
	}

	if (!wcmInitKeyboard(priv))
	{
		wcmLog(priv, W_ERROR, "unable to init Focus class device\n");
		return FALSE;
	}

	if (!wcmInitPointer(priv, nbaxes, is_absolute(priv) ? Absolute : Relative))
	{
		wcmLog(priv, W_ERROR, "unable to init Pointer class device\n");
		return FALSE;
	}

	if (IsTouch(priv)) {
		if (!wcmInitTouch(priv, common->wcmMaxContacts,
				  TabletHasFeature(common, WCM_LCD)))
		{
			wcmLog(priv, W_ERROR, "Unable to init touch class device struct!\n");
			return FALSE;
		}
		priv->common->touch_mask = valuator_mask_new(2);
	}

	if (!wcmInitAxes(priv))
		return FALSE;

	return TRUE;
}

Bool wcmDevStart(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;
	WacomModelPtr model = common->wcmModel;

	/* start the tablet data */
	if (model->Start && (model->Start(priv) != Success))
		return FALSE;

	wcmEnableTool(priv);

	return TRUE;
}

void wcmDevStop(WacomDevicePtr priv)
{

	TimerCancel(priv->tap_timer);
	TimerCancel(priv->serial_timer);
	TimerCancel(priv->touch_timer);
	wcmDisableTool(priv);
	wcmUnlinkTouchAndPen(priv);
}

/*****************************************************************************
 * wcmDevClose --
 ****************************************************************************/

void wcmDevClose(WacomDevicePtr priv)
{
	InputInfoPtr pInfo = priv->pInfo;
	WacomCommonPtr common = priv->common;

	DBG(4, priv, "Wacom number of open devices = %d\n", common->fd_refs);

	if (pInfo->fd >= 0)
	{
		if (!--common->fd_refs)
			wcmClose(priv);
		pInfo->fd = -1;
	}
}

/* vim: set noexpandtab tabstop=8 shiftwidth=8: */