xref: /haiku/src/add-ons/input_server/devices/mouse/MouseInputDevice.cpp (revision 25f1ddecf7c81f9fd03fbd9463aa6566b8d01fc4)
1 /*
2  * Copyright 2004-2011, Haiku.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Stefano Ceccherini (stefano.ceccherini@gmail.com)
7  *		Jérôme Duval
8  *		Axel Dörfler, axeld@pinc-software.de
9  *		Clemens Zeidler, haiku@clemens-zeidler.de
10  *		Stephan Aßmus, superstippi@gmx.de
11  */
12 
13 
14 #include "MouseInputDevice.h"
15 
16 #include <errno.h>
17 #include <new>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 
22 #include <Autolock.h>
23 #include <Debug.h>
24 #include <Directory.h>
25 #include <Entry.h>
26 #include <File.h>
27 #include <FindDirectory.h>
28 #include <NodeMonitor.h>
29 #include <Path.h>
30 #include <String.h>
31 #include <View.h>
32 
33 #include <kb_mouse_settings.h>
34 #include <keyboard_mouse_driver.h>
35 #include <touchpad_settings.h>
36 
37 
38 #undef TRACE
39 //#define TRACE_MOUSE_DEVICE
40 #ifdef TRACE_MOUSE_DEVICE
41 
42 	class FunctionTracer {
43 	public:
44 		FunctionTracer(const void* pointer, const char* className,
45 				const char* functionName,
46 				int32& depth)
47 			: fFunctionName(),
48 			  fPrepend(),
49 			  fFunctionDepth(depth),
50 			  fPointer(pointer)
51 		{
52 			fFunctionDepth++;
53 			fPrepend.Append(' ', fFunctionDepth * 2);
54 			fFunctionName << className << "::" << functionName << "()";
55 
56 			debug_printf("%p -> %s%s {\n", fPointer, fPrepend.String(),
57 				fFunctionName.String());
58 		}
59 
60 		 ~FunctionTracer()
61 		{
62 			debug_printf("%p -> %s}\n", fPointer, fPrepend.String());
63 			fFunctionDepth--;
64 		}
65 
66 	private:
67 		BString	fFunctionName;
68 		BString	fPrepend;
69 		int32&	fFunctionDepth;
70 		const void* fPointer;
71 	};
72 
73 
74 	static int32 sFunctionDepth = -1;
75 #	define MD_CALLED(x...)	FunctionTracer _ft(this, "MouseDevice", \
76 								__FUNCTION__, sFunctionDepth)
77 #	define MID_CALLED(x...)	FunctionTracer _ft(this, "MouseInputDevice", \
78 								__FUNCTION__, sFunctionDepth)
79 #	define TRACE(x...)	do { BString _to; \
80 							_to.Append(' ', (sFunctionDepth + 1) * 2); \
81 							debug_printf("%p -> %s", this, _to.String()); \
82 							debug_printf(x); } while (0)
83 #	define LOG_EVENT(text...) do {} while (0)
84 #	define LOG_ERR(text...) TRACE(text)
85 #else
86 #	define TRACE(x...) do {} while (0)
87 #	define MD_CALLED(x...) TRACE(x)
88 #	define MID_CALLED(x...) TRACE(x)
89 #	define LOG_ERR(x...) debug_printf(x)
90 #	define LOG_EVENT(x...) TRACE(x)
91 #endif
92 
93 
94 const static uint32 kMouseThreadPriority = B_FIRST_REAL_TIME_PRIORITY + 4;
95 const static char* kMouseDevicesDirectory = "/dev/input/mouse";
96 const static char* kTouchpadDevicesDirectory = "/dev/input/touchpad";
97 
98 
99 class MouseDevice {
100 public:
101 								MouseDevice(MouseInputDevice& target,
102 									const char* path);
103 								~MouseDevice();
104 
105 			status_t			Start();
106 			void				Stop();
107 
108 			status_t			UpdateSettings();
109 			status_t			UpdateTouchpadSettings(const BMessage* message);
110 
111 			const char*			Path() const { return fPath.String(); }
112 			input_device_ref*	DeviceRef() { return &fDeviceRef; }
113 
114 private:
115 			char*				_BuildShortName() const;
116 
117 	static	status_t			_ControlThreadEntry(void* arg);
118 			void				_ControlThread();
119 			void				_ControlThreadCleanup();
120 			void				_UpdateSettings();
121 
122 			status_t			_GetTouchpadSettingsPath(BPath& path);
123 			status_t			_ReadTouchpadSettingsMsg(BMessage* message);
124 			status_t			_UpdateTouchpadSettings();
125 
126 			BMessage*			_BuildMouseMessage(uint32 what,
127 									uint64 when, uint32 buttons,
128 									int32 deltaX, int32 deltaY) const;
129 			void				_ComputeAcceleration(
130 									const mouse_movement& movements,
131 									int32& deltaX, int32& deltaY,
132 									float& historyDeltaX,
133 									float& historyDeltaY) const;
134 			uint32				_RemapButtons(uint32 buttons) const;
135 
136 private:
137 			MouseInputDevice&	fTarget;
138 			BString				fPath;
139 			int					fDevice;
140 
141 			input_device_ref	fDeviceRef;
142 			mouse_settings		fSettings;
143 			bool				fDeviceRemapsButtons;
144 
145 			thread_id			fThread;
146 	volatile bool				fActive;
147 	volatile bool				fUpdateSettings;
148 
149 			bool				fIsTouchpad;
150 			touchpad_settings	fTouchpadSettings;
151 			BMessage*			fTouchpadSettingsMessage;
152 			BLocker				fTouchpadSettingsLock;
153 };
154 
155 
156 extern "C" BInputServerDevice*
157 instantiate_input_device()
158 {
159 	return new(std::nothrow) MouseInputDevice();
160 }
161 
162 
163 //	#pragma mark -
164 
165 
166 MouseDevice::MouseDevice(MouseInputDevice& target, const char* driverPath)
167 	:
168 	fTarget(target),
169 	fPath(driverPath),
170 	fDevice(-1),
171 	fDeviceRemapsButtons(false),
172 	fThread(-1),
173 	fActive(false),
174 	fUpdateSettings(false),
175 	fIsTouchpad(false),
176 	fTouchpadSettingsMessage(NULL),
177 	fTouchpadSettingsLock("Touchpad settings lock")
178 {
179 	MD_CALLED();
180 
181 	fDeviceRef.name = _BuildShortName();
182 	fDeviceRef.type = B_POINTING_DEVICE;
183 	fDeviceRef.cookie = this;
184 
185 #ifdef HAIKU_TARGET_PLATFORM_HAIKU
186 	for (int i = 0; i < B_MAX_MOUSE_BUTTONS; i++)
187 		fSettings.map.button[i] = B_MOUSE_BUTTON(i + 1);
188 #endif
189 };
190 
191 
192 MouseDevice::~MouseDevice()
193 {
194 	MD_CALLED();
195 	TRACE("delete\n");
196 
197 	if (fActive)
198 		Stop();
199 
200 	free(fDeviceRef.name);
201 	delete fTouchpadSettingsMessage;
202 }
203 
204 
205 status_t
206 MouseDevice::Start()
207 {
208 	MD_CALLED();
209 
210 	fDevice = open(fPath.String(), O_RDWR);
211 		// let the control thread handle any error on opening the device
212 
213 	char threadName[B_OS_NAME_LENGTH];
214 	snprintf(threadName, B_OS_NAME_LENGTH, "%s watcher", fDeviceRef.name);
215 
216 	fThread = spawn_thread(_ControlThreadEntry, threadName,
217 		kMouseThreadPriority, (void*)this);
218 
219 	status_t status;
220 	if (fThread < 0)
221 		status = fThread;
222 	else {
223 		fActive = true;
224 		status = resume_thread(fThread);
225 	}
226 
227 	if (status < B_OK) {
228 		LOG_ERR("%s: can't spawn/resume watching thread: %s\n",
229 			fDeviceRef.name, strerror(status));
230 		if (fDevice >= 0)
231 			close(fDevice);
232 
233 		return status;
234 	}
235 
236 	return fDevice >= 0 ? B_OK : B_ERROR;
237 }
238 
239 
240 void
241 MouseDevice::Stop()
242 {
243 	MD_CALLED();
244 
245 	fActive = false;
246 		// this will stop the thread as soon as it reads the next packet
247 
248 	close(fDevice);
249 	fDevice = -1;
250 
251 	if (fThread >= 0) {
252 		// unblock the thread, which might wait on a semaphore.
253 		suspend_thread(fThread);
254 		resume_thread(fThread);
255 
256 		status_t dummy;
257 		wait_for_thread(fThread, &dummy);
258 	}
259 }
260 
261 
262 status_t
263 MouseDevice::UpdateSettings()
264 {
265 	MD_CALLED();
266 
267 	if (fThread < 0)
268 		return B_ERROR;
269 
270 	// trigger updating the settings in the control thread
271 	fUpdateSettings = true;
272 
273 	return B_OK;
274 }
275 
276 
277 status_t
278 MouseDevice::UpdateTouchpadSettings(const BMessage* message)
279 {
280 	if (!fIsTouchpad)
281 		return B_BAD_TYPE;
282 	if (fThread < 0)
283 		return B_ERROR;
284 
285 	BAutolock _(fTouchpadSettingsLock);
286 
287 	// trigger updating the settings in the control thread
288 	fUpdateSettings = true;
289 
290 	delete fTouchpadSettingsMessage;
291 	fTouchpadSettingsMessage = new BMessage(*message);
292 	if (fTouchpadSettingsMessage == NULL)
293 		return B_NO_MEMORY;
294 
295 	return B_OK;
296 }
297 
298 
299 char*
300 MouseDevice::_BuildShortName() const
301 {
302 	// TODO It would be simpler and better to use B_GET_DEVICE_NAME, but...
303 	// - This is currently called before the device is open
304 	// - We need to implement that in our input drivers first
305 	BString string(fPath);
306 	BString deviceName;
307 	BString name;
308 
309 	int32 slash = string.FindLast("/");
310 	string.CopyInto(deviceName, slash + 1, string.Length() - slash);
311 	// FIXME the device name may be more than just a number (for example
312 	// ibm_trackpoint_0)
313 	int32 index = atoi(deviceName.String()) + 1;
314 
315 	int32 previousSlash = string.FindLast("/", slash);
316 	string.CopyInto(name, previousSlash + 1, slash - previousSlash - 1);
317 
318 	if (name == "ps2")
319 		name = "PS/2";
320 
321 	if (name.Length() <= 4)
322 		name.ToUpper();
323 	else
324 		name.Capitalize();
325 
326 	// Check the whole string for "touchpad" because it's a different directory
327 	// FIXME use MS_IS_TOUCHPAD ioctl instead (or fIsTouchpad which caches its
328 	// result) but this can only be done after the control thread is running
329 	if (string.FindFirst("touchpad") >= 0) {
330 		name << " Touchpad ";
331 	} else if (deviceName.FindFirst("trackpoint") >= 0) {
332 		// That's always PS/2, so don't keep the bus name
333 		name = "Trackpoint ";
334 	} else {
335 		if (deviceName.FindFirst("intelli") >= 0)
336 			name.Prepend("Extended ");
337 
338 		name << " Mouse ";
339 	}
340 	name << index;
341 
342 	return strdup(name.String());
343 }
344 
345 
346 // #pragma mark - control thread
347 
348 
349 status_t
350 MouseDevice::_ControlThreadEntry(void* arg)
351 {
352 	MouseDevice* device = (MouseDevice*)arg;
353 	device->_ControlThread();
354 	return B_OK;
355 }
356 
357 
358 void
359 MouseDevice::_ControlThread()
360 {
361 	MD_CALLED();
362 
363 	if (fDevice < 0) {
364 		_ControlThreadCleanup();
365 		// TOAST!
366 		return;
367 	}
368 
369 	// touchpad settings
370 	if (ioctl(fDevice, MS_IS_TOUCHPAD, NULL) == B_OK) {
371 		TRACE("is touchpad %s\n", fPath.String());
372 		fIsTouchpad = true;
373 
374 		fTouchpadSettings = kDefaultTouchpadSettings;
375 
376 		BPath path;
377 		status_t status = _GetTouchpadSettingsPath(path);
378 		BFile settingsFile(path.Path(), B_READ_ONLY);
379 		if (status == B_OK && settingsFile.InitCheck() == B_OK) {
380 			if (settingsFile.Read(&fTouchpadSettings, sizeof(touchpad_settings))
381 					!= sizeof(touchpad_settings)) {
382 				TRACE("failed to load settings\n");
383 			}
384 		}
385 		_UpdateTouchpadSettings();
386 	}
387 
388 	_UpdateSettings();
389 
390 	uint32 lastButtons = 0;
391 	float historyDeltaX = 0.0;
392 	float historyDeltaY = 0.0;
393 
394 	static const bigtime_t kTransferDelay = 1000000 / 125;
395 		// 125 transfers per second should be more than enough
396 #define USE_REGULAR_INTERVAL 1
397 #if USE_REGULAR_INTERVAL
398 	bigtime_t nextTransferTime = system_time() + kTransferDelay;
399 #endif
400 
401 	while (fActive) {
402 		mouse_movement movements;
403 
404 #if USE_REGULAR_INTERVAL
405 		snooze_until(nextTransferTime, B_SYSTEM_TIMEBASE);
406 		nextTransferTime += kTransferDelay;
407 #endif
408 
409 		if (ioctl(fDevice, MS_READ, &movements, sizeof(movements)) != B_OK) {
410 			LOG_ERR("Mouse device exiting, %s\n", strerror(errno));
411 			_ControlThreadCleanup();
412 			// TOAST!
413 			return;
414 		}
415 
416 		// take care of updating the settings first, if necessary
417 		if (fUpdateSettings) {
418 			fUpdateSettings = false;
419 			if (fIsTouchpad) {
420 				BAutolock _(fTouchpadSettingsLock);
421 				if (fTouchpadSettingsMessage != NULL) {
422 					_ReadTouchpadSettingsMsg(fTouchpadSettingsMessage);
423 					_UpdateTouchpadSettings();
424 					delete fTouchpadSettingsMessage;
425 					fTouchpadSettingsMessage = NULL;
426 				} else
427 					_UpdateSettings();
428 			} else
429 				_UpdateSettings();
430 		}
431 
432 		uint32 buttons = lastButtons ^ movements.buttons;
433 
434 		uint32 remappedButtons = _RemapButtons(movements.buttons);
435 		int32 deltaX, deltaY;
436 		_ComputeAcceleration(movements, deltaX, deltaY, historyDeltaX,
437 			historyDeltaY);
438 
439 		LOG_EVENT("%s: buttons: 0x%lx, x: %ld, y: %ld, clicks:%ld, "
440 			"wheel_x:%ld, wheel_y:%ld\n",
441 			fDeviceRef.name, movements.buttons,
442 			movements.xdelta, movements.ydelta, movements.clicks,
443 			movements.wheel_xdelta, movements.wheel_ydelta);
444 		LOG_EVENT("%s: x: %ld, y: %ld (%.4f, %.4f)\n", fDeviceRef.name,
445 			deltaX, deltaY, historyDeltaX, historyDeltaY);
446 
447 		// Send single messages for each event
448 
449 		if (buttons != 0) {
450 			bool pressedButton = (buttons & movements.buttons) > 0;
451 			BMessage* message = _BuildMouseMessage(
452 				pressedButton ? B_MOUSE_DOWN : B_MOUSE_UP,
453 				movements.timestamp, remappedButtons, deltaX, deltaY);
454 			if (message != NULL) {
455 				if (pressedButton) {
456 					message->AddInt32("clicks", movements.clicks);
457 					LOG_EVENT("B_MOUSE_DOWN\n");
458 				} else
459 					LOG_EVENT("B_MOUSE_UP\n");
460 
461 				fTarget.EnqueueMessage(message);
462 				lastButtons = movements.buttons;
463 			}
464 		}
465 
466 		if (movements.xdelta != 0 || movements.ydelta != 0) {
467 			BMessage* message = _BuildMouseMessage(B_MOUSE_MOVED,
468 				movements.timestamp, remappedButtons, deltaX, deltaY);
469 			if (message != NULL)
470 				fTarget.EnqueueMessage(message);
471 		}
472 
473 		if (movements.wheel_ydelta != 0 || movements.wheel_xdelta != 0) {
474 			BMessage* message = new BMessage(B_MOUSE_WHEEL_CHANGED);
475 			if (message == NULL)
476 				continue;
477 
478 			if (message->AddInt64("when", movements.timestamp) == B_OK
479 				&& message->AddFloat("be:wheel_delta_x",
480 					movements.wheel_xdelta) == B_OK
481 				&& message->AddFloat("be:wheel_delta_y",
482 					movements.wheel_ydelta) == B_OK)
483 				fTarget.EnqueueMessage(message);
484 			else
485 				delete message;
486 		}
487 
488 #if !USE_REGULAR_INTERVAL
489 		snooze(kTransferDelay);
490 #endif
491 	}
492 }
493 
494 
495 void
496 MouseDevice::_ControlThreadCleanup()
497 {
498 	// NOTE: Only executed when the control thread detected an error
499 	// and from within the control thread!
500 
501 	if (fActive) {
502 		fThread = -1;
503 		fTarget._RemoveDevice(fPath.String());
504 	} else {
505 		// In case active is already false, another thread
506 		// waits for this thread to quit, and may already hold
507 		// locks that _RemoveDevice() wants to acquire. In other
508 		// words, the device is already being removed, so we simply
509 		// quit here.
510 	}
511 }
512 
513 
514 void
515 MouseDevice::_UpdateSettings()
516 {
517 	MD_CALLED();
518 
519 	// retrieve current values
520 
521 	if (get_mouse_map(&fSettings.map) != B_OK)
522 		LOG_ERR("error when get_mouse_map\n");
523 	else {
524 		fDeviceRemapsButtons
525 			= ioctl(fDevice, MS_SET_MAP, &fSettings.map) == B_OK;
526 	}
527 
528 	if (get_click_speed(&fSettings.click_speed) != B_OK)
529 		LOG_ERR("error when get_click_speed\n");
530 	else
531 		ioctl(fDevice, MS_SET_CLICKSPEED, &fSettings.click_speed);
532 
533 	if (get_mouse_speed(&fSettings.accel.speed) != B_OK)
534 		LOG_ERR("error when get_mouse_speed\n");
535 	else {
536 		if (get_mouse_acceleration(&fSettings.accel.accel_factor) != B_OK)
537 			LOG_ERR("error when get_mouse_acceleration\n");
538 		else {
539 			mouse_accel accel;
540 			ioctl(fDevice, MS_GET_ACCEL, &accel);
541 			accel.speed = fSettings.accel.speed;
542 			accel.accel_factor = fSettings.accel.accel_factor;
543 			ioctl(fDevice, MS_SET_ACCEL, &fSettings.accel);
544 		}
545 	}
546 
547 	if (get_mouse_type(&fSettings.type) != B_OK)
548 		LOG_ERR("error when get_mouse_type\n");
549 	else
550 		ioctl(fDevice, MS_SET_TYPE, &fSettings.type);
551 }
552 
553 
554 status_t
555 MouseDevice::_GetTouchpadSettingsPath(BPath& path)
556 {
557 	status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, &path);
558 	if (status < B_OK)
559 		return status;
560 	return path.Append(TOUCHPAD_SETTINGS_FILE);
561 }
562 
563 
564 status_t
565 MouseDevice::_ReadTouchpadSettingsMsg(BMessage* message)
566 {
567 	message->FindBool("scroll_twofinger", &fTouchpadSettings.scroll_twofinger);
568 	message->FindBool("scroll_twofinger_horizontal",
569 		&fTouchpadSettings.scroll_twofinger_horizontal);
570 	message->FindFloat("scroll_rightrange",
571 		&fTouchpadSettings.scroll_rightrange);
572 	message->FindFloat("scroll_bottomrange",
573 		&fTouchpadSettings.scroll_bottomrange);
574 
575 	message->FindInt16("scroll_xstepsize",
576 		(int16*)&fTouchpadSettings.scroll_xstepsize);
577 	message->FindInt16("scroll_ystepsize",
578 		(int16*)&fTouchpadSettings.scroll_ystepsize);
579 	message->FindInt8("scroll_acceleration",
580 		(int8*)&fTouchpadSettings.scroll_acceleration);
581 	message->FindInt8("tapgesture_sensibility",
582 		(int8*)&fTouchpadSettings.tapgesture_sensibility);
583 
584 	return B_OK;
585 }
586 
587 
588 status_t
589 MouseDevice::_UpdateTouchpadSettings()
590 {
591 	if (fIsTouchpad) {
592 		ioctl(fDevice, MS_SET_TOUCHPAD_SETTINGS, &fTouchpadSettings);
593 		return B_OK;
594 	}
595 	return B_ERROR;
596 }
597 
598 
599 BMessage*
600 MouseDevice::_BuildMouseMessage(uint32 what, uint64 when, uint32 buttons,
601 	int32 deltaX, int32 deltaY) const
602 {
603 	BMessage* message = new BMessage(what);
604 	if (message == NULL)
605 		return NULL;
606 
607 	if (message->AddInt64("when", when) < B_OK
608 		|| message->AddInt32("buttons", buttons) < B_OK
609 		|| message->AddInt32("x", deltaX) < B_OK
610 		|| message->AddInt32("y", deltaY) < B_OK) {
611 		delete message;
612 		return NULL;
613 	}
614 
615 	return message;
616 }
617 
618 
619 void
620 MouseDevice::_ComputeAcceleration(const mouse_movement& movements,
621 	int32& _deltaX, int32& _deltaY, float& historyDeltaX,
622 	float& historyDeltaY) const
623 {
624 	// basic mouse speed
625 	float deltaX = (float)movements.xdelta * fSettings.accel.speed / 65536.0
626 		+ historyDeltaX;
627 	float deltaY = (float)movements.ydelta * fSettings.accel.speed / 65536.0
628 		+ historyDeltaY;
629 
630 	// acceleration
631 	double acceleration = 1;
632 	if (fSettings.accel.accel_factor) {
633 		acceleration = 1 + sqrt(deltaX * deltaX + deltaY * deltaY)
634 			* fSettings.accel.accel_factor / 524288.0;
635 	}
636 
637 	deltaX *= acceleration;
638 	deltaY *= acceleration;
639 
640 	if (deltaX >= 0)
641 		_deltaX = (int32)floorf(deltaX);
642 	else
643 		_deltaX = (int32)ceilf(deltaX);
644 
645 	if (deltaY >= 0)
646 		_deltaY = (int32)floorf(deltaY);
647 	else
648 		_deltaY = (int32)ceilf(deltaY);
649 
650 	historyDeltaX = deltaX - _deltaX;
651 	historyDeltaY = deltaY - _deltaY;
652 }
653 
654 
655 uint32
656 MouseDevice::_RemapButtons(uint32 buttons) const
657 {
658 	if (fDeviceRemapsButtons)
659 		return buttons;
660 
661 	uint32 newButtons = 0;
662 	for (int32 i = 0; buttons; i++) {
663 		if (buttons & 0x1) {
664 #if defined(HAIKU_TARGET_PLATFORM_HAIKU) || defined(HAIKU_TARGET_PLATFORM_DANO)
665 			newButtons |= fSettings.map.button[i];
666 #else
667 			if (i == 0)
668 				newButtons |= fSettings.map.left;
669 			if (i == 1)
670 				newButtons |= fSettings.map.right;
671 			if (i == 2)
672 				newButtons |= fSettings.map.middle;
673 #endif
674 		}
675 		buttons >>= 1;
676 	}
677 
678 	return newButtons;
679 }
680 
681 
682 //	#pragma mark -
683 
684 
685 MouseInputDevice::MouseInputDevice()
686 	:
687 	fDevices(2, true),
688 	fDeviceListLock("MouseInputDevice list")
689 {
690 	MID_CALLED();
691 
692 	StartMonitoringDevice(kMouseDevicesDirectory);
693 	StartMonitoringDevice(kTouchpadDevicesDirectory);
694 	_RecursiveScan(kMouseDevicesDirectory);
695 	_RecursiveScan(kTouchpadDevicesDirectory);
696 }
697 
698 
699 MouseInputDevice::~MouseInputDevice()
700 {
701 	MID_CALLED();
702 
703 	StopMonitoringDevice(kTouchpadDevicesDirectory);
704 	StopMonitoringDevice(kMouseDevicesDirectory);
705 	fDevices.MakeEmpty();
706 }
707 
708 
709 status_t
710 MouseInputDevice::InitCheck()
711 {
712 	MID_CALLED();
713 
714 	return BInputServerDevice::InitCheck();
715 }
716 
717 
718 status_t
719 MouseInputDevice::Start(const char* name, void* cookie)
720 {
721 	MID_CALLED();
722 
723 	MouseDevice* device = (MouseDevice*)cookie;
724 
725 	return device->Start();
726 }
727 
728 
729 status_t
730 MouseInputDevice::Stop(const char* name, void* cookie)
731 {
732 	TRACE("%s(%s)\n", __PRETTY_FUNCTION__, name);
733 
734 	MouseDevice* device = (MouseDevice*)cookie;
735 	device->Stop();
736 
737 	return B_OK;
738 }
739 
740 
741 status_t
742 MouseInputDevice::Control(const char* name, void* cookie,
743 	uint32 command, BMessage* message)
744 {
745 	TRACE("%s(%s, code: %lu)\n", __PRETTY_FUNCTION__, name, command);
746 
747 	MouseDevice* device = (MouseDevice*)cookie;
748 
749 	if (command == B_NODE_MONITOR)
750 		return _HandleMonitor(message);
751 
752 	if (command == MS_SET_TOUCHPAD_SETTINGS)
753 		return device->UpdateTouchpadSettings(message);
754 
755 	if (command >= B_MOUSE_TYPE_CHANGED
756 		&& command <= B_MOUSE_ACCELERATION_CHANGED)
757 		return device->UpdateSettings();
758 
759 	return B_BAD_VALUE;
760 }
761 
762 
763 status_t
764 MouseInputDevice::_HandleMonitor(BMessage* message)
765 {
766 	MID_CALLED();
767 
768 	const char* path;
769 	int32 opcode;
770 	if (message->FindInt32("opcode", &opcode) != B_OK
771 		|| (opcode != B_ENTRY_CREATED && opcode != B_ENTRY_REMOVED)
772 		|| message->FindString("path", &path) != B_OK)
773 		return B_BAD_VALUE;
774 
775 	if (opcode == B_ENTRY_CREATED)
776 		return _AddDevice(path);
777 
778 #if 0
779 	return _RemoveDevice(path);
780 #else
781 	// Don't handle B_ENTRY_REMOVED, let the control thread take care of it.
782 	return B_OK;
783 #endif
784 }
785 
786 
787 void
788 MouseInputDevice::_RecursiveScan(const char* directory)
789 {
790 	MID_CALLED();
791 
792 	BEntry entry;
793 	BDirectory dir(directory);
794 	while (dir.GetNextEntry(&entry) == B_OK) {
795 		BPath path;
796 		entry.GetPath(&path);
797 
798 		if (!strcmp(path.Leaf(), "serial")) {
799 			// skip serial
800 			continue;
801 		}
802 
803 		if (entry.IsDirectory())
804 			_RecursiveScan(path.Path());
805 		else
806 			_AddDevice(path.Path());
807 	}
808 }
809 
810 
811 MouseDevice*
812 MouseInputDevice::_FindDevice(const char* path) const
813 {
814 	MID_CALLED();
815 
816 	for (int32 i = fDevices.CountItems() - 1; i >= 0; i--) {
817 		MouseDevice* device = fDevices.ItemAt(i);
818 		if (strcmp(device->Path(), path) == 0)
819 			return device;
820 	}
821 
822 	return NULL;
823 }
824 
825 
826 status_t
827 MouseInputDevice::_AddDevice(const char* path)
828 {
829 	MID_CALLED();
830 
831 	BAutolock _(fDeviceListLock);
832 
833 	_RemoveDevice(path);
834 
835 	MouseDevice* device = new(std::nothrow) MouseDevice(*this, path);
836 	if (device == NULL) {
837 		TRACE("No memory\n");
838 		return B_NO_MEMORY;
839 	}
840 
841 	if (!fDevices.AddItem(device)) {
842 		TRACE("No memory in list\n");
843 		delete device;
844 		return B_NO_MEMORY;
845 	}
846 
847 	input_device_ref* devices[2];
848 	devices[0] = device->DeviceRef();
849 	devices[1] = NULL;
850 
851 	TRACE("adding path: %s, name: %s\n", path, devices[0]->name);
852 
853 	return RegisterDevices(devices);
854 }
855 
856 
857 status_t
858 MouseInputDevice::_RemoveDevice(const char* path)
859 {
860 	MID_CALLED();
861 
862 	BAutolock _(fDeviceListLock);
863 
864 	MouseDevice* device = _FindDevice(path);
865 	if (device == NULL) {
866 		TRACE("%s not found\n", path);
867 		return B_ENTRY_NOT_FOUND;
868 	}
869 
870 	input_device_ref* devices[2];
871 	devices[0] = device->DeviceRef();
872 	devices[1] = NULL;
873 
874 	TRACE("removing path: %s, name: %s\n", path, devices[0]->name);
875 
876 	UnregisterDevices(devices);
877 
878 	fDevices.RemoveItem(device);
879 
880 	return B_OK;
881 }
882