xref: /haiku/src/servers/app/ServerWindow.cpp (revision 675ffabd70492a962f8c0288a32208c22ce5de18)
1 /*
2  * Copyright 2001-2010, Haiku.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		DarkWyrm <bpmagic@columbus.rr.com>
7  *		Adrian Oanca <adioanca@gmail.com>
8  *		Stephan Aßmus <superstippi@gmx.de>
9  *		Stefano Ceccherini <stefano.ceccherini@gmail.com>
10  *		Axel Dörfler <axeld@pinc-software.de>
11  *		Artur Wyszynski <harakash@gmail.com>
12  *		Philippe Saint-Pierre <stpere@gmail.com>
13  *		Brecht Machiels <brecht@mos6581.org>
14  */
15 
16 
17 /*!	\class ServerWindow
18 
19 	The ServerWindow class handles all BWindow messaging; it forwards all
20 	BWindow requests to the corresponding app_server classes, that is Desktop,
21 	Window, and View.
22 	Furthermore, it also sends app_server requests/notices to its BWindow. There
23 	is one ServerWindow per BWindow.
24 */
25 
26 
27 #include "ServerWindow.h"
28 
29 #include <syslog.h>
30 #include <new>
31 
32 #include <AppDefs.h>
33 #include <Autolock.h>
34 #include <Debug.h>
35 #include <DirectWindow.h>
36 #include <TokenSpace.h>
37 #include <View.h>
38 #include <GradientLinear.h>
39 #include <GradientRadial.h>
40 #include <GradientRadialFocus.h>
41 #include <GradientDiamond.h>
42 #include <GradientConic.h>
43 
44 #include <MessagePrivate.h>
45 #include <PortLink.h>
46 #include <ServerProtocolStructs.h>
47 #include <ViewPrivate.h>
48 #include <WindowInfo.h>
49 #include <WindowPrivate.h>
50 
51 #include "clipping.h"
52 #include "utf8_functions.h"
53 
54 #include "AppServer.h"
55 #include "AutoDeleter.h"
56 #include "Desktop.h"
57 #include "DirectWindowInfo.h"
58 #include "DrawingEngine.h"
59 #include "DrawState.h"
60 #include "HWInterface.h"
61 #include "Overlay.h"
62 #include "ProfileMessageSupport.h"
63 #include "RenderingBuffer.h"
64 #include "ServerApp.h"
65 #include "ServerBitmap.h"
66 #include "ServerPicture.h"
67 #include "ServerProtocol.h"
68 #include "Window.h"
69 #include "WorkspacesView.h"
70 
71 
72 using std::nothrow;
73 
74 
75 //#define TRACE_SERVER_WINDOW
76 #ifdef TRACE_SERVER_WINDOW
77 #	include <stdio.h>
78 #	define STRACE(x) debug_printf x
79 #else
80 #	define STRACE(x) ;
81 #endif
82 
83 //#define TRACE_SERVER_WINDOW_MESSAGES
84 #ifdef TRACE_SERVER_WINDOW_MESSAGES
85 #	include <stdio.h>
86 static const char* kDrawingModeMap[] = {
87 	"B_OP_COPY",
88 	"B_OP_OVER",
89 	"B_OP_ERASE",
90 	"B_OP_INVERT",
91 	"B_OP_ADD",
92 	"B_OP_SUBTRACT",
93 	"B_OP_BLEND",
94 	"B_OP_MIN",
95 	"B_OP_MAX",
96 	"B_OP_SELECT",
97 	"B_OP_ALPHA",
98 
99 	"fix kDrawingModeMap",
100 	"fix kDrawingModeMap",
101 	"fix kDrawingModeMap",
102 	"fix kDrawingModeMap",
103 	"fix kDrawingModeMap",
104 };
105 #	define DTRACE(x) debug_printf x
106 #else
107 #	define DTRACE(x) ;
108 #endif
109 
110 //#define TRACE_SERVER_GRADIENTS
111 #ifdef TRACE_SERVER_GRADIENTS
112 #	include <OS.h>
113 #	define GTRACE(x) debug_printf x
114 #else
115 #	define GTRACE(x) ;
116 #endif
117 
118 //#define PROFILE_MESSAGE_LOOP
119 #ifdef PROFILE_MESSAGE_LOOP
120 struct profile { int32 code; int32 count; bigtime_t time; };
121 static profile sMessageProfile[AS_LAST_CODE];
122 static profile sRedrawProcessingTime;
123 //static profile sNextMessageTime;
124 #endif
125 
126 
127 //	#pragma mark -
128 
129 
130 #ifdef PROFILE_MESSAGE_LOOP
131 static int
132 compare_message_profiles(const void* _a, const void* _b)
133 {
134 	profile* a = (profile*)*(void**)_a;
135 	profile* b = (profile*)*(void**)_b;
136 	if (a->time < b->time)
137 		return 1;
138 	if (a->time > b->time)
139 		return -1;
140 	return 0;
141 }
142 #endif
143 
144 
145 //	#pragma mark -
146 
147 
148 /*!	Sets up the basic BWindow counterpart - you have to call Init() before
149 	you can actually use it, though.
150 */
151 ServerWindow::ServerWindow(const char* title, ServerApp* app,
152 		port_id clientPort, port_id looperPort, int32 clientToken)
153 	:
154 	MessageLooper(title && *title ? title : "Unnamed Window"),
155 	fTitle(NULL),
156 	fDesktop(app->GetDesktop()),
157 	fServerApp(app),
158 	fWindow(NULL),
159 	fWindowAddedToDesktop(false),
160 
161 	fClientTeam(app->ClientTeam()),
162 
163 	fMessagePort(-1),
164 	fClientReplyPort(clientPort),
165 	fClientLooperPort(looperPort),
166 
167 	fClientToken(clientToken),
168 
169 	fCurrentView(NULL),
170 	fCurrentDrawingRegion(),
171 	fCurrentDrawingRegionValid(false),
172 
173 	fDirectWindowInfo(NULL),
174 	fIsDirectlyAccessing(false)
175 {
176 	STRACE(("ServerWindow(%s)::ServerWindow()\n", title));
177 
178 	SetTitle(title);
179 	fServerToken = BPrivate::gDefaultTokens.NewToken(B_SERVER_TOKEN, this);
180 
181 	BMessenger::Private(fFocusMessenger).SetTo(fClientTeam,
182 		looperPort, B_PREFERRED_TOKEN);
183 	BMessenger::Private(fHandlerMessenger).SetTo(fClientTeam,
184 		looperPort, clientToken);
185 
186 	fEventTarget.SetTo(fFocusMessenger);
187 
188 	fDeathSemaphore = create_sem(0, "window death");
189 }
190 
191 
192 /*! Tears down all connections the main app_server objects, and deletes some
193 	internals.
194 */
195 ServerWindow::~ServerWindow()
196 {
197 	STRACE(("ServerWindow(%s@%p):~ServerWindow()\n", fTitle, this));
198 
199 	if (!fWindow->IsOffscreenWindow()) {
200 		fWindowAddedToDesktop = false;
201 		fDesktop->RemoveWindow(fWindow);
202 	}
203 
204 	if (App() != NULL) {
205 		App()->RemoveWindow(this);
206 		fServerApp = NULL;
207 	}
208 
209 	delete fWindow;
210 
211 	free(fTitle);
212 	delete_port(fMessagePort);
213 
214 	BPrivate::gDefaultTokens.RemoveToken(fServerToken);
215 
216 	delete fDirectWindowInfo;
217 	STRACE(("ServerWindow(%p) will exit NOW\n", this));
218 
219 	delete_sem(fDeathSemaphore);
220 
221 #ifdef PROFILE_MESSAGE_LOOP
222 	BList profiles;
223 	for (int32 i = 0; i < AS_LAST_CODE; i++) {
224 		if (sMessageProfile[i].count == 0)
225 			continue;
226 		sMessageProfile[i].code = i;
227 		profiles.AddItem(&sMessageProfile[i]);
228 	}
229 
230 	profiles.SortItems(compare_message_profiles);
231 
232 	BString codeName;
233 	int32 count = profiles.CountItems();
234 	for (int32 i = 0; i < count; i++) {
235 		profile* p = (profile*)profiles.ItemAtFast(i);
236 		string_for_message_code(p->code, codeName);
237 		printf("[%s] called %ld times, %g secs (%Ld usecs per call)\n",
238 			codeName.String(), p->count, p->time / 1000000.0,
239 			p->time / p->count);
240 	}
241 	if (sRedrawProcessingTime.count > 0) {
242 		printf("average redraw processing time: %g secs, count: %ld (%lld "
243 			"usecs per call)\n", sRedrawProcessingTime.time / 1000000.0,
244 			sRedrawProcessingTime.count,
245 			sRedrawProcessingTime.time / sRedrawProcessingTime.count);
246 	}
247 //	if (sNextMessageTime.count > 0) {
248 //		printf("average NextMessage() time: %g secs, count: %ld (%lld usecs per call)\n",
249 //			sNextMessageTime.time / 1000000.0, sNextMessageTime.count,
250 //			sNextMessageTime.time / sNextMessageTime.count);
251 //	}
252 #endif
253 }
254 
255 
256 status_t
257 ServerWindow::Init(BRect frame, window_look look, window_feel feel,
258 	uint32 flags, uint32 workspace)
259 {
260 	if (!App()->AddWindow(this)) {
261 		fServerApp = NULL;
262 		return B_NO_MEMORY;
263 	}
264 
265 	if (fTitle == NULL)
266 		return B_NO_MEMORY;
267 
268 	// fMessagePort is the port to which the app sends messages for the server
269 	fMessagePort = create_port(100, fTitle);
270 	if (fMessagePort < B_OK)
271 		return fMessagePort;
272 
273 	fLink.SetSenderPort(fClientReplyPort);
274 	fLink.SetReceiverPort(fMessagePort);
275 
276 	// We cannot call MakeWindow in the constructor, since it
277 	// is a virtual function!
278 	fWindow = MakeWindow(frame, fTitle, look, feel, flags, workspace);
279 	if (!fWindow || fWindow->InitCheck() != B_OK) {
280 		delete fWindow;
281 		fWindow = NULL;
282 		return B_NO_MEMORY;
283 	}
284 
285 	if (!fWindow->IsOffscreenWindow()) {
286 		fDesktop->AddWindow(fWindow);
287 		fWindowAddedToDesktop = true;
288 	}
289 
290 	return B_OK;
291 }
292 
293 
294 /*!	Returns the ServerWindow's Window, if it exists and has been
295 	added to the Desktop already.
296 	In other words, you cannot assume this method will always give you
297 	a valid pointer.
298 */
299 Window*
300 ServerWindow::Window() const
301 {
302 	ASSERT_MULTI_LOCKED(fDesktop->WindowLocker());
303 
304 	if (!fWindowAddedToDesktop)
305 		return NULL;
306 
307 	return fWindow;
308 }
309 
310 
311 void
312 ServerWindow::_PrepareQuit()
313 {
314 	if (fThread == find_thread(NULL)) {
315 		// make sure we're hidden
316 		fDesktop->LockSingleWindow();
317 		_Hide();
318 		fDesktop->UnlockSingleWindow();
319 	} else if (fThread >= B_OK)
320 		PostMessage(AS_HIDE_WINDOW);
321 }
322 
323 
324 void
325 ServerWindow::_GetLooperName(char* name, size_t length)
326 {
327 	const char *title = Title();
328 	if (title == NULL || !title[0])
329 		title = "Unnamed Window";
330 
331 	snprintf(name, length, "w:%ld:%s", ClientTeam(), title);
332 }
333 
334 
335 /*! Shows the window's Window.
336 */
337 void
338 ServerWindow::_Show()
339 {
340 	// NOTE: if you do something else, other than sending a port message, PLEASE lock
341 	STRACE(("ServerWindow %s: _Show\n", Title()));
342 
343 	if (fQuitting || fWindow->IsMinimized() || !fWindow->IsHidden()
344 		|| fWindow->IsOffscreenWindow() || fWindow->TopView() == NULL)
345 		return;
346 
347 	// TODO: Maybe we need to dispatch a message to the desktop to show/hide us
348 	// instead of doing it from this thread.
349 	fDesktop->UnlockSingleWindow();
350 	fDesktop->ShowWindow(fWindow);
351 	if (fDirectWindowInfo && fDirectWindowInfo->IsFullScreen())
352 		_ResizeToFullScreen();
353 
354 	fDesktop->LockSingleWindow();
355 }
356 
357 
358 /*! Hides the window's Window. You need to have all windows locked when
359 	calling this function.
360 */
361 void
362 ServerWindow::_Hide()
363 {
364 	STRACE(("ServerWindow %s: _Hide\n", Title()));
365 
366 	if (fWindow->IsHidden() || fWindow->IsOffscreenWindow())
367 		return;
368 
369 	fDesktop->UnlockSingleWindow();
370 	fDesktop->HideWindow(fWindow);
371 	fDesktop->LockSingleWindow();
372 }
373 
374 
375 void
376 ServerWindow::RequestRedraw()
377 {
378 	PostMessage(AS_REDRAW, 0);
379 		// we don't care if this fails - it's only a notification, and if
380 		// it fails, there are obviously enough messages in the queue
381 		// already
382 
383 	atomic_add(&fRedrawRequested, 1);
384 }
385 
386 
387 void
388 ServerWindow::SetTitle(const char* newTitle)
389 {
390 	char* oldTitle = fTitle;
391 
392 	if (newTitle == NULL)
393 		newTitle = "";
394 
395 	fTitle = strdup(newTitle);
396 	if (fTitle == NULL) {
397 		// out of memory condition
398 		fTitle = oldTitle;
399 		return;
400 	}
401 
402 	free(oldTitle);
403 
404 	if (Thread() >= B_OK) {
405 		char name[B_OS_NAME_LENGTH];
406 		_GetLooperName(name, sizeof(name));
407 		rename_thread(Thread(), name);
408 	}
409 
410 	if (fWindow != NULL)
411 		fDesktop->SetWindowTitle(fWindow, newTitle);
412 }
413 
414 
415 //! Requests that the ServerWindow's BWindow quit
416 void
417 ServerWindow::NotifyQuitRequested()
418 {
419 	// NOTE: if you do something else, other than sending a port message,
420 	// PLEASE lock
421 	STRACE(("ServerWindow %s: Quit\n", fTitle));
422 
423 	BMessage msg(B_QUIT_REQUESTED);
424 	SendMessageToClient(&msg);
425 }
426 
427 
428 void
429 ServerWindow::NotifyMinimize(bool minimize)
430 {
431 	if (fWindow->Feel() != B_NORMAL_WINDOW_FEEL)
432 		return;
433 
434 	// The client is responsible for the actual minimization
435 
436 	BMessage msg(B_MINIMIZE);
437 	msg.AddInt64("when", real_time_clock_usecs());
438 	msg.AddBool("minimize", minimize);
439 
440 	SendMessageToClient(&msg);
441 }
442 
443 
444 //! Sends a message to the client to perform a Zoom
445 void
446 ServerWindow::NotifyZoom()
447 {
448 	// NOTE: if you do something else, other than sending a port message,
449 	// PLEASE lock
450 	BMessage msg(B_ZOOM);
451 	SendMessageToClient(&msg);
452 }
453 
454 
455 void
456 ServerWindow::GetInfo(window_info& info)
457 {
458 	info.team = ClientTeam();
459 	info.server_token = ServerToken();
460 
461 	info.thread = Thread();
462 	info.client_token = ClientToken();
463 	info.client_port = fClientLooperPort;
464 	info.workspaces = fWindow->Workspaces();
465 
466 	// logic taken from Switcher comments and experiments
467 	if (fWindow->IsHidden())
468 		info.layer = 0;
469 	else if (fWindow->IsVisible()) {
470 		if (fWindow->Feel() == kDesktopWindowFeel)
471 			info.layer = 2;
472 		else if (fWindow->IsFloating() || fWindow->IsModal())
473 			info.layer = 4;
474 		else
475 			info.layer = 3;
476 	} else
477 		info.layer = 1;
478 
479 	info.feel = fWindow->Feel();
480 	info.flags = fWindow->Flags();
481 	info.window_left = (int)floor(fWindow->Frame().left);
482 	info.window_top = (int)floor(fWindow->Frame().top);
483 	info.window_right = (int)floor(fWindow->Frame().right);
484 	info.window_bottom = (int)floor(fWindow->Frame().bottom);
485 
486 	info.show_hide_level = fWindow->IsHidden() ? 1 : 0; // ???
487 	info.is_mini = fWindow->IsMinimized();
488 }
489 
490 
491 void
492 ServerWindow::ResyncDrawState()
493 {
494 	_UpdateDrawState(fCurrentView);
495 }
496 
497 
498 View*
499 ServerWindow::_CreateView(BPrivate::LinkReceiver& link, View** _parent)
500 {
501 	// NOTE: no need to check for a lock. This is a private method.
502 
503 	int32 token;
504 	BRect frame;
505 	uint32 resizeMask;
506 	uint32 eventMask;
507 	uint32 eventOptions;
508 	uint32 flags;
509 	bool hidden;
510 	int32 parentToken;
511 	char* name = NULL;
512 	rgb_color viewColor;
513 	BPoint scrollingOffset;
514 
515 	link.Read<int32>(&token);
516 	link.ReadString(&name);
517 	link.Read<BRect>(&frame);
518 	link.Read<BPoint>(&scrollingOffset);
519 	link.Read<uint32>(&resizeMask);
520 	link.Read<uint32>(&eventMask);
521 	link.Read<uint32>(&eventOptions);
522 	link.Read<uint32>(&flags);
523 	link.Read<bool>(&hidden);
524 	link.Read<rgb_color>(&viewColor);
525 	link.Read<int32>(&parentToken);
526 
527 	STRACE(("ServerWindow(%s)::_CreateView()-> view %s, token %ld\n",
528 		fTitle, name, token));
529 
530 	View* newView;
531 
532 	if ((flags & kWorkspacesViewFlag) != 0) {
533 		newView = new (nothrow) WorkspacesView(frame, scrollingOffset, name,
534 			token, resizeMask, flags);
535 	} else {
536 		newView = new (nothrow) View(frame, scrollingOffset, name, token,
537 			resizeMask, flags);
538 	}
539 
540 	free(name);
541 
542 	if (newView == NULL)
543 		return NULL;
544 
545 	if (newView->InitCheck() != B_OK) {
546 		delete newView;
547 		return NULL;
548 	}
549 
550 	// there is no way of setting this, other than manually :-)
551 	newView->SetViewColor(viewColor);
552 	newView->SetHidden(hidden);
553 	newView->SetEventMask(eventMask, eventOptions);
554 
555 	if (eventMask != 0 || eventOptions != 0) {
556 //		fDesktop->UnlockSingleWindow();
557 //		fDesktop->LockAllWindows();
558 fDesktop->UnlockAllWindows();
559 		// TODO: possible deadlock
560 		fDesktop->EventDispatcher().AddListener(EventTarget(),
561 			newView->Token(), eventMask, eventOptions);
562 fDesktop->LockAllWindows();
563 //		fDesktop->UnlockAllWindows();
564 //		fDesktop->LockSingleWindow();
565 	}
566 
567 	// Initialize the view with the current application plain font.
568 	// NOTE: This might be out of sync with the global app_server plain
569 	// font, but that is so on purpose! The client needs to resync itself
570 	// with the app_server fonts upon notification, but if we just use
571 	// the current font here, the be_plain_font on the client may still
572 	// hold old values. So this needs to be an update initiated by the
573 	// client application.
574 	newView->CurrentState()->SetFont(App()->PlainFont());
575 
576 	if (_parent) {
577 		View *parent;
578 		if (App()->ViewTokens().GetToken(parentToken, B_HANDLER_TOKEN,
579 				(void**)&parent) != B_OK
580 			|| parent->Window()->ServerWindow() != this) {
581 			debug_printf("View token not found!\n");
582 			parent = NULL;
583 		}
584 
585 		*_parent = parent;
586 	}
587 
588 	return newView;
589 }
590 
591 
592 /*!	Dispatches all window messages, and those view messages that
593 	don't need a valid fCurrentView (ie. view creation).
594 */
595 void
596 ServerWindow::_DispatchMessage(int32 code, BPrivate::LinkReceiver& link)
597 {
598 	switch (code) {
599 		case AS_SHOW_WINDOW:
600 			DTRACE(("ServerWindow %s: Message AS_SHOW_WINDOW\n", Title()));
601 			_Show();
602 			break;
603 
604 		case AS_HIDE_WINDOW:
605 			DTRACE(("ServerWindow %s: Message AS_HIDE_WINDOW\n", Title()));
606 			_Hide();
607 			break;
608 
609 		case AS_MINIMIZE_WINDOW:
610 		{
611 			int32 showLevel;
612 			bool minimize;
613 
614 			link.Read<bool>(&minimize);
615 			if (link.Read<int32>(&showLevel) == B_OK) {
616 				DTRACE(("ServerWindow %s: Message AS_MINIMIZE_WINDOW, "
617 					"showLevel: %ld, minimize: %d\n", Title(), showLevel,
618 					minimize));
619 
620 				if (showLevel <= 0) {
621 					// window is currently hidden - ignore the minimize request
622 					fWindow->SetMinimized(minimize);
623 						// TODO: commenting this out makes BWindow::fMinimized
624 						// and Window::fMinimized go out of sync. However, not
625 						// doing it currently causes #4127.
626 					break;
627 				}
628 
629 				fDesktop->UnlockSingleWindow();
630 				fDesktop->MinimizeWindow(fWindow, minimize);
631 				fDesktop->LockSingleWindow();
632 			}
633 			break;
634 		}
635 
636 		case AS_ACTIVATE_WINDOW:
637 		{
638 			bool activate = true;
639 			if (link.Read<bool>(&activate) != B_OK)
640 				break;
641 
642 			DTRACE(("ServerWindow %s: Message AS_ACTIVATE_WINDOW: activate: "
643 				"%d\n", Title(), activate));
644 
645 			fDesktop->UnlockSingleWindow();
646 
647 			if (activate)
648 				fDesktop->SelectWindow(fWindow);
649 			else
650 				fDesktop->SendWindowBehind(fWindow, NULL);
651 
652 			fDesktop->LockSingleWindow();
653 			break;
654 		}
655 		case AS_SEND_BEHIND:
656 		{
657 			// Has the all-window lock
658 			int32 token;
659 			team_id teamID;
660 			status_t status = B_ERROR;
661 
662 			link.Read<int32>(&token);
663 			if (link.Read<team_id>(&teamID) == B_OK) {
664 				::Window* behindOf = fDesktop->FindWindowByClientToken(token,
665 					teamID);
666 
667 				DTRACE(("ServerWindow %s: Message AS_SEND_BEHIND %s\n",
668 					Title(), behindOf != NULL ? behindOf->Title() : "NULL"));
669 
670 				if (behindOf != NULL || token == -1) {
671 					fDesktop->SendWindowBehind(fWindow, behindOf);
672 					status = B_OK;
673 				} else
674 					status = B_NAME_NOT_FOUND;
675 			}
676 
677 			fLink.StartMessage(status);
678 			fLink.Flush();
679 			break;
680 		}
681 
682 		case B_QUIT_REQUESTED:
683 			DTRACE(("ServerWindow %s received quit request\n", Title()));
684 			NotifyQuitRequested();
685 			break;
686 
687 		case AS_ENABLE_UPDATES:
688 			DTRACE(("ServerWindow %s: Message AS_ENABLE_UPDATES\n", Title()));
689 			fWindow->EnableUpdateRequests();
690 			break;
691 
692 		case AS_DISABLE_UPDATES:
693 			DTRACE(("ServerWindow %s: Message AS_DISABLE_UPDATES\n", Title()));
694 			fWindow->DisableUpdateRequests();
695 			break;
696 
697 		case AS_NEEDS_UPDATE:
698 			DTRACE(("ServerWindow %s: Message AS_NEEDS_UPDATE: %d\n",
699 				Title(), fWindow->NeedsUpdate()));
700 			if (fWindow->NeedsUpdate())
701 				fLink.StartMessage(B_OK);
702 			else
703 				fLink.StartMessage(B_ERROR);
704 			fLink.Flush();
705 			break;
706 
707 		case AS_SET_WINDOW_TITLE:
708 		{
709 			char* newTitle;
710 			if (link.ReadString(&newTitle) == B_OK) {
711 				DTRACE(("ServerWindow %s: Message AS_SET_WINDOW_TITLE: %s\n",
712 					Title(), newTitle));
713 
714 				SetTitle(newTitle);
715 				free(newTitle);
716 			}
717 			break;
718 		}
719 
720 		case AS_ADD_TO_SUBSET:
721 		{
722 			// Has the all-window lock
723 			DTRACE(("ServerWindow %s: Message AS_ADD_TO_SUBSET\n", Title()));
724 			status_t status = B_ERROR;
725 
726 			int32 token;
727 			if (link.Read<int32>(&token) == B_OK) {
728 				::Window* window = fDesktop->FindWindowByClientToken(token,
729 					App()->ClientTeam());
730 				if (window == NULL || window->Feel() != B_NORMAL_WINDOW_FEEL) {
731 					status = B_BAD_VALUE;
732 				} else {
733 					status = fDesktop->AddWindowToSubset(fWindow, window)
734 						? B_OK : B_NO_MEMORY;
735 				}
736 			}
737 
738 			fLink.StartMessage(status);
739 			fLink.Flush();
740 			break;
741 		}
742 		case AS_REMOVE_FROM_SUBSET:
743 		{
744 			// Has the all-window lock
745 			DTRACE(("ServerWindow %s: Message AS_REM_FROM_SUBSET\n", Title()));
746 			status_t status = B_ERROR;
747 
748 			int32 token;
749 			if (link.Read<int32>(&token) == B_OK) {
750 				::Window* window = fDesktop->FindWindowByClientToken(token,
751 					App()->ClientTeam());
752 				if (window != NULL) {
753 					fDesktop->RemoveWindowFromSubset(fWindow, window);
754 					status = B_OK;
755 				} else
756 					status = B_BAD_VALUE;
757 			}
758 
759 			fLink.StartMessage(status);
760 			fLink.Flush();
761 			break;
762 		}
763 
764 		case AS_SET_LOOK:
765 		{
766 			// Has the all-window look
767 			DTRACE(("ServerWindow %s: Message AS_SET_LOOK\n", Title()));
768 
769 			status_t status = B_ERROR;
770 			int32 look;
771 			if (link.Read<int32>(&look) == B_OK) {
772 				// test if look is valid
773 				status = Window::IsValidLook((window_look)look)
774 					? B_OK : B_BAD_VALUE;
775 			}
776 
777 			if (status == B_OK && !fWindow->IsOffscreenWindow())
778 				fDesktop->SetWindowLook(fWindow, (window_look)look);
779 
780 			fLink.StartMessage(status);
781 			fLink.Flush();
782 			break;
783 		}
784 		case AS_SET_FEEL:
785 		{
786 			// Has the all-window look
787 			DTRACE(("ServerWindow %s: Message AS_SET_FEEL\n", Title()));
788 
789 			status_t status = B_ERROR;
790 			int32 feel;
791 			if (link.Read<int32>(&feel) == B_OK) {
792 				// test if feel is valid
793 				status = Window::IsValidFeel((window_feel)feel)
794 					? B_OK : B_BAD_VALUE;
795 			}
796 
797 			if (status == B_OK && !fWindow->IsOffscreenWindow())
798 				fDesktop->SetWindowFeel(fWindow, (window_feel)feel);
799 
800 			fLink.StartMessage(status);
801 			fLink.Flush();
802 			break;
803 		}
804 		case AS_SET_FLAGS:
805 		{
806 			// Has the all-window look
807 			DTRACE(("ServerWindow %s: Message AS_SET_FLAGS\n", Title()));
808 
809 			status_t status = B_ERROR;
810 			uint32 flags;
811 			if (link.Read<uint32>(&flags) == B_OK) {
812 				// test if flags are valid
813 				status = (flags & ~Window::ValidWindowFlags()) == 0
814 					? B_OK : B_BAD_VALUE;
815 			}
816 
817 			if (status == B_OK && !fWindow->IsOffscreenWindow())
818 				fDesktop->SetWindowFlags(fWindow, flags);
819 
820 			fLink.StartMessage(status);
821 			fLink.Flush();
822 			break;
823 		}
824 #if 0
825 		case AS_SET_ALIGNMENT:
826 		{
827 			// TODO: Implement AS_SET_ALIGNMENT
828 			DTRACE(("ServerWindow %s: Message Set_Alignment unimplemented\n",
829 				Title()));
830 			break;
831 		}
832 		case AS_GET_ALIGNMENT:
833 		{
834 			// TODO: Implement AS_GET_ALIGNMENT
835 			DTRACE(("ServerWindow %s: Message Get_Alignment unimplemented\n",
836 				Title()));
837 			break;
838 		}
839 #endif
840 		case AS_IS_FRONT_WINDOW:
841 		{
842 			bool isFront = fDesktop->FrontWindow() == fWindow;
843 			DTRACE(("ServerWindow %s: Message AS_IS_FRONT_WINDOW: %d\n",
844 				Title(), isFront));
845 			fLink.StartMessage(isFront ? B_OK : B_ERROR);
846 			fLink.Flush();
847 			break;
848 		}
849 
850 		case AS_GET_WORKSPACES:
851 		{
852 			DTRACE(("ServerWindow %s: Message AS_GET_WORKSPACES\n", Title()));
853 			fLink.StartMessage(B_OK);
854 			fLink.Attach<uint32>(fWindow->Workspaces());
855 			fLink.Flush();
856 			break;
857 		}
858 		case AS_SET_WORKSPACES:
859 		{
860 			// Has the all-window lock (but would actually not need to lock at
861 			// all)
862 			uint32 newWorkspaces;
863 			if (link.Read<uint32>(&newWorkspaces) != B_OK)
864 				break;
865 
866 			DTRACE(("ServerWindow %s: Message AS_SET_WORKSPACES %lx\n",
867 				Title(), newWorkspaces));
868 
869 			fDesktop->SetWindowWorkspaces(fWindow, newWorkspaces);
870 			break;
871 		}
872 		case AS_WINDOW_RESIZE:
873 		{
874 			// Has the all-window look
875 			float xResizeTo;
876 			float yResizeTo;
877 			link.Read<float>(&xResizeTo);
878 			if (link.Read<float>(&yResizeTo) != B_OK)
879 				break;
880 
881 			DTRACE(("ServerWindow %s: Message AS_WINDOW_RESIZE %.1f, %.1f\n",
882 				Title(), xResizeTo, yResizeTo));
883 
884 			// comment this code for the time being, as some apps rely
885 			// on the programmatically resize behavior during user resize
886 //			if (fWindow->IsResizing()) {
887 				// While the user resizes the window, we ignore
888 				// pragmatically set window bounds
889 //				fLink.StartMessage(B_BUSY);
890 //			} else {
891 				fDesktop->ResizeWindowBy(fWindow,
892 					xResizeTo - fWindow->Frame().Width(),
893 					yResizeTo - fWindow->Frame().Height());
894 				fLink.StartMessage(B_OK);
895 //			}
896 			fLink.Flush();
897 			break;
898 		}
899 		case AS_WINDOW_MOVE:
900 		{
901 			// Has the all-window look
902 			float xMoveTo;
903 			float yMoveTo;
904 			link.Read<float>(&xMoveTo);
905 			if (link.Read<float>(&yMoveTo) != B_OK)
906 				break;
907 
908 			DTRACE(("ServerWindow %s: Message AS_WINDOW_MOVE: %.1f, %.1f\n",
909 				Title(), xMoveTo, yMoveTo));
910 
911 			if (fWindow->IsDragging()) {
912 				// While the user moves the window, we ignore
913 				// pragmatically set window positions
914 				fLink.StartMessage(B_BUSY);
915 			} else {
916 				fDesktop->MoveWindowBy(fWindow, xMoveTo - fWindow->Frame().left,
917 					yMoveTo - fWindow->Frame().top);
918 				fLink.StartMessage(B_OK);
919 			}
920 			fLink.Flush();
921 			break;
922 		}
923 		case AS_SET_SIZE_LIMITS:
924 		{
925 			// Has the all-window look
926 
927 			// Attached Data:
928 			// 1) float minimum width
929 			// 2) float maximum width
930 			// 3) float minimum height
931 			// 4) float maximum height
932 
933 			// TODO: for now, move the client to int32 as well!
934 			int32 minWidth, maxWidth, minHeight, maxHeight;
935 			float value;
936 			link.Read<float>(&value);	minWidth = (int32)value;
937 			link.Read<float>(&value);	maxWidth = (int32)value;
938 			link.Read<float>(&value);	minHeight = (int32)value;
939 			link.Read<float>(&value);	maxHeight = (int32)value;
940 /*
941 			link.Read<int32>(&minWidth);
942 			link.Read<int32>(&maxWidth);
943 			link.Read<int32>(&minHeight);
944 			link.Read<int32>(&maxHeight);
945 */
946 			DTRACE(("ServerWindow %s: Message AS_SET_SIZE_LIMITS: "
947 				"x: %ld-%ld, y: %ld-%ld\n",
948 				Title(), minWidth, maxWidth, minHeight, maxHeight));
949 
950 			fWindow->SetSizeLimits(minWidth, maxWidth, minHeight, maxHeight);
951 
952 			// and now, sync the client to the limits that we were able to enforce
953 			fWindow->GetSizeLimits(&minWidth, &maxWidth,
954 				&minHeight, &maxHeight);
955 
956 			fLink.StartMessage(B_OK);
957 			fLink.Attach<BRect>(fWindow->Frame());
958 			fLink.Attach<float>((float)minWidth);
959 			fLink.Attach<float>((float)maxWidth);
960 			fLink.Attach<float>((float)minHeight);
961 			fLink.Attach<float>((float)maxHeight);
962 
963 			fLink.Flush();
964 
965 			fDesktop->NotifySizeLimitsChanged(fWindow, minWidth, maxWidth,
966 				minHeight, maxHeight);
967 			break;
968 		}
969 
970 		case AS_SET_DECORATOR_SETTINGS:
971 		{
972 			// Has the all-window look
973 			DTRACE(("ServerWindow %s: Message AS_SET_DECORATOR_SETTINGS\n",
974 				Title()));
975 
976 			int32 size;
977 			if (fWindow && link.Read<int32>(&size) == B_OK) {
978 				char buffer[size];
979 				if (link.Read(buffer, size) == B_OK) {
980 					BMessage settings;
981 					if (settings.Unflatten(buffer) == B_OK)
982 						fDesktop->SetWindowDecoratorSettings(fWindow, settings);
983 				}
984 			}
985 			break;
986 		}
987 
988 		case AS_GET_DECORATOR_SETTINGS:
989 		{
990 			DTRACE(("ServerWindow %s: Message AS_GET_DECORATOR_SETTINGS\n",
991 				Title()));
992 
993 			bool success = false;
994 
995 			BMessage settings;
996 			if (fWindow->GetDecoratorSettings(&settings)) {
997 				int32 size = settings.FlattenedSize();
998 				char buffer[size];
999 				if (settings.Flatten(buffer, size) == B_OK) {
1000 					success = true;
1001 					fLink.StartMessage(B_OK);
1002 					fLink.Attach<int32>(size);
1003 					fLink.Attach(buffer, size);
1004 				}
1005 			}
1006 
1007 			if (!success)
1008 				fLink.StartMessage(B_ERROR);
1009 
1010 			fLink.Flush();
1011 			break;
1012 		}
1013 
1014 		case AS_SYSTEM_FONT_CHANGED:
1015 		{
1016 			// Has the all-window look
1017 			fDesktop->FontsChanged(fWindow);
1018 			// TODO: tell client about this, too, and relayout...
1019 			break;
1020 		}
1021 
1022 		case AS_REDRAW:
1023 			// Nothing to do here - the redraws are actually handled by looking
1024 			// at the fRedrawRequested member variable in _MessageLooper().
1025 			break;
1026 
1027 		case AS_SYNC:
1028 			DTRACE(("ServerWindow %s: Message AS_SYNC\n", Title()));
1029 			// the synchronisation works by the fact that the client
1030 			// window is waiting for this reply, after having received it,
1031 			// client and server queues are in sync (earlier, the client
1032 			// may have pushed drawing commands at the server and now it
1033 			// knows they have all been carried out)
1034 			fLink.StartMessage(B_OK);
1035 			fLink.Flush();
1036 			break;
1037 
1038 		case AS_BEGIN_UPDATE:
1039 			DTRACE(("ServerWindow %s: Message AS_BEGIN_UPDATE\n", Title()));
1040 			fWindow->BeginUpdate(fLink);
1041 			break;
1042 
1043 		case AS_END_UPDATE:
1044 			DTRACE(("ServerWindow %s: Message AS_END_UPDATE\n", Title()));
1045 			fWindow->EndUpdate();
1046 			break;
1047 
1048 		case AS_GET_MOUSE:
1049 		{
1050 			// Has the all-window look
1051 			DTRACE(("ServerWindow %s: Message AS_GET_MOUSE\n", fTitle));
1052 
1053 			// Returns
1054 			// 1) BPoint mouse location
1055 			// 2) int32 button state
1056 
1057 			BPoint where;
1058 			int32 buttons;
1059 			fDesktop->GetLastMouseState(&where, &buttons);
1060 
1061 			fLink.StartMessage(B_OK);
1062 			fLink.Attach<BPoint>(where);
1063 			fLink.Attach<int32>(buttons);
1064 			fLink.Flush();
1065 			break;
1066 		}
1067 
1068 		// BDirectWindow communication
1069 
1070 		case AS_DIRECT_WINDOW_GET_SYNC_DATA:
1071 		{
1072 			status_t status = _EnableDirectWindowMode();
1073 
1074 			fLink.StartMessage(status);
1075 			if (status == B_OK) {
1076 				struct direct_window_sync_data syncData;
1077 				fDirectWindowInfo->GetSyncData(syncData);
1078 
1079 				fLink.Attach(&syncData, sizeof(syncData));
1080 			}
1081 
1082 			fLink.Flush();
1083 			break;
1084 		}
1085 		case AS_DIRECT_WINDOW_SET_FULLSCREEN:
1086 		{
1087 			// Has the all-window look
1088 			bool enable;
1089 			link.Read<bool>(&enable);
1090 
1091 			status_t status = B_OK;
1092 			if (fDirectWindowInfo != NULL)
1093 				_DirectWindowSetFullScreen(enable);
1094 			else
1095 				status = B_BAD_TYPE;
1096 
1097 			fLink.StartMessage(status);
1098 			fLink.Flush();
1099 			break;
1100 		}
1101 
1102 		// View creation and destruction (don't need a valid fCurrentView)
1103 
1104 		case AS_SET_CURRENT_VIEW:
1105 		{
1106 			int32 token;
1107 			if (link.Read<int32>(&token) != B_OK)
1108 				break;
1109 
1110 			View *current;
1111 			if (App()->ViewTokens().GetToken(token, B_HANDLER_TOKEN,
1112 					(void**)&current) != B_OK
1113 				|| current->Window()->ServerWindow() != this) {
1114 				// TODO: if this happens, we probably want to kill the app and
1115 				// clean up
1116 				debug_printf("ServerWindow %s: Message "
1117 					"\n\n\nAS_SET_CURRENT_VIEW: view not found, token %ld\n",
1118 					fTitle, token);
1119 				current = NULL;
1120 			} else {
1121 				DTRACE(("\n\n\nServerWindow %s: Message AS_SET_CURRENT_VIEW: %s, "
1122 					"token %ld\n", fTitle, current->Name(), token));
1123 				_SetCurrentView(current);
1124 			}
1125 			break;
1126 		}
1127 
1128 		case AS_VIEW_CREATE_ROOT:
1129 		{
1130 			DTRACE(("ServerWindow %s: Message AS_VIEW_CREATE_ROOT\n", fTitle));
1131 
1132 			// Start receiving top_view data -- pass NULL as the parent view.
1133 			// This should be the *only* place where this happens.
1134 			if (fCurrentView != NULL) {
1135 				debug_printf("ServerWindow %s: Message "
1136 					"AS_VIEW_CREATE_ROOT: fCurrentView already set!!\n",
1137 					fTitle);
1138 				break;
1139 			}
1140 
1141 			_SetCurrentView(_CreateView(link, NULL));
1142 			fWindow->SetTopView(fCurrentView);
1143 			break;
1144 		}
1145 
1146 		case AS_VIEW_CREATE:
1147 		{
1148 			DTRACE(("ServerWindow %s: Message AS_VIEW_CREATE: View name: "
1149 				"%s\n", fTitle, fCurrentView->Name()));
1150 
1151 			View* parent = NULL;
1152 			View* newView = _CreateView(link, &parent);
1153 			if (parent != NULL && newView != NULL)
1154 				parent->AddChild(newView);
1155 			else {
1156 				debug_printf("ServerWindow %s: Message AS_VIEW_CREATE: "
1157 					"parent or newView NULL!!\n", fTitle);
1158 			}
1159 			break;
1160 		}
1161 
1162 		case AS_TALK_TO_DESKTOP_LISTENER:
1163 		{
1164 			if (fDesktop->MessageForListener(fWindow, fLink))
1165 				break;
1166 			// unhandled message at least send an error if needed
1167 			if (link.NeedsReply()) {
1168 				fLink.StartMessage(B_ERROR);
1169 				fLink.Flush();
1170 			}
1171 			break;
1172 		}
1173 
1174 		default:
1175 			if (fCurrentView == NULL) {
1176 				BString codeName;
1177 				string_for_message_code(code, codeName);
1178 				debug_printf("ServerWindow %s received unexpected code - "
1179 					"message '%s' before top_view attached.\n",
1180 					Title(), codeName.String());
1181 				if (link.NeedsReply()) {
1182 					fLink.StartMessage(B_ERROR);
1183 					fLink.Flush();
1184 				}
1185 				return;
1186 			}
1187 
1188 			_DispatchViewMessage(code, link);
1189 			break;
1190 	}
1191 }
1192 
1193 
1194 /*!
1195 	Dispatches all view messages that need a valid fCurrentView.
1196 */
1197 void
1198 ServerWindow::_DispatchViewMessage(int32 code,
1199 	BPrivate::LinkReceiver &link)
1200 {
1201 	if (_DispatchPictureMessage(code, link))
1202 		return;
1203 
1204 	switch (code) {
1205 		case AS_VIEW_SCROLL:
1206 		{
1207 			float dh;
1208 			float dv;
1209 			link.Read<float>(&dh);
1210 			if (link.Read<float>(&dv) != B_OK)
1211 				break;
1212 
1213 			DTRACE(("ServerWindow %s: Message AS_VIEW_SCROLL: View name: "
1214 				"%s, %.1f x %.1f\n", fTitle, fCurrentView->Name(), dh, dv));
1215 			fWindow->ScrollViewBy(fCurrentView, dh, dv);
1216 			break;
1217 		}
1218 		case AS_VIEW_COPY_BITS:
1219 		{
1220 			BRect src;
1221 			BRect dst;
1222 
1223 			link.Read<BRect>(&src);
1224 			if (link.Read<BRect>(&dst) != B_OK)
1225 				break;
1226 
1227 			DTRACE(("ServerWindow %s: Message AS_VIEW_COPY_BITS: View name: "
1228 				"%s, BRect(%.1f, %.1f, %.1f, %.1f) -> "
1229 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", fTitle,
1230 				fCurrentView->Name(), src.left, src.top, src.right, src.bottom,
1231 				dst.left, dst.top, dst.right, dst.bottom));
1232 
1233 			BRegion contentRegion;
1234 			// TODO: avoid copy operation maybe?
1235 			fWindow->GetContentRegion(&contentRegion);
1236 			fCurrentView->CopyBits(src, dst, contentRegion);
1237 			break;
1238 		}
1239 		case AS_VIEW_DELETE:
1240 		{
1241 			// Received when a view is detached from a window
1242 
1243 			int32 token;
1244 			if (link.Read<int32>(&token) != B_OK)
1245 				break;
1246 
1247 			View *view;
1248 			if (App()->ViewTokens().GetToken(token, B_HANDLER_TOKEN,
1249 					(void**)&view) == B_OK
1250 				&& view->Window()->ServerWindow() == this) {
1251 				View* parent = view->Parent();
1252 
1253 				DTRACE(("ServerWindow %s: AS_VIEW_DELETE view: %p, "
1254 					"parent: %p\n", fTitle, view, parent));
1255 
1256 				if (parent != NULL) {
1257 					parent->RemoveChild(view);
1258 
1259 					if (view->EventMask() != 0) {
1260 						// TODO: possible deadlock (event dispatcher already
1261 						// locked itself, waits for Desktop write lock, but
1262 						// we have it, now we are trying to lock the event
1263 						// dispatcher -> deadlock)
1264 fDesktop->UnlockSingleWindow();
1265 						fDesktop->EventDispatcher().RemoveListener(
1266 							EventTarget(), token);
1267 fDesktop->LockSingleWindow();
1268 					}
1269 					if (fCurrentView == view)
1270 						_SetCurrentView(parent);
1271 					delete view;
1272 				} // else we don't delete the root view
1273 			}
1274 			break;
1275 		}
1276 		case AS_VIEW_SET_STATE:
1277 		{
1278 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_STATE: "
1279 				"View name: %s\n", fTitle, fCurrentView->Name()));
1280 
1281 			fCurrentView->CurrentState()->ReadFromLink(link);
1282 			// TODO: When is this used?!?
1283 			fCurrentView->RebuildClipping(true);
1284 			_UpdateDrawState(fCurrentView);
1285 
1286 			break;
1287 		}
1288 		case AS_VIEW_SET_FONT_STATE:
1289 		{
1290 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_FONT_STATE: "
1291 				"View name: %s\n", fTitle, fCurrentView->Name()));
1292 
1293 			fCurrentView->CurrentState()->ReadFontFromLink(link);
1294 			fWindow->GetDrawingEngine()->SetFont(
1295 				fCurrentView->CurrentState());
1296 			break;
1297 		}
1298 		case AS_VIEW_GET_STATE:
1299 		{
1300 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_STATE: "
1301 				"View name: %s\n", fTitle, fCurrentView->Name()));
1302 
1303 			fLink.StartMessage(B_OK);
1304 
1305 			// attach state data
1306 			fCurrentView->CurrentState()->WriteToLink(fLink.Sender());
1307 			fLink.Flush();
1308 			break;
1309 		}
1310 		case AS_VIEW_SET_EVENT_MASK:
1311 		{
1312 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_EVENT_MASK: "
1313 				"View name: %s\n", fTitle, fCurrentView->Name()));
1314 			uint32 eventMask, options;
1315 
1316 			link.Read<uint32>(&eventMask);
1317 			if (link.Read<uint32>(&options) == B_OK) {
1318 				fCurrentView->SetEventMask(eventMask, options);
1319 
1320 fDesktop->UnlockSingleWindow();
1321 				// TODO: possible deadlock!
1322 				if (eventMask != 0 || options != 0) {
1323 					fDesktop->EventDispatcher().AddListener(EventTarget(),
1324 						fCurrentView->Token(), eventMask, options);
1325 				} else {
1326 					fDesktop->EventDispatcher().RemoveListener(EventTarget(),
1327 						fCurrentView->Token());
1328 				}
1329 fDesktop->LockSingleWindow();
1330 			}
1331 			break;
1332 		}
1333 		case AS_VIEW_SET_MOUSE_EVENT_MASK:
1334 		{
1335 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_MOUSE_EVENT_MASK: "
1336 				"View name: %s\n", fTitle, fCurrentView->Name()));
1337 			uint32 eventMask, options;
1338 
1339 			link.Read<uint32>(&eventMask);
1340 			if (link.Read<uint32>(&options) == B_OK) {
1341 fDesktop->UnlockSingleWindow();
1342 				// TODO: possible deadlock
1343 				if (eventMask != 0 || options != 0) {
1344 					if (options & B_LOCK_WINDOW_FOCUS)
1345 						fDesktop->SetFocusLocked(fWindow);
1346 					fDesktop->EventDispatcher().AddTemporaryListener(EventTarget(),
1347 						fCurrentView->Token(), eventMask, options);
1348 				} else {
1349 					fDesktop->EventDispatcher().RemoveTemporaryListener(EventTarget(),
1350 						fCurrentView->Token());
1351 				}
1352 fDesktop->LockSingleWindow();
1353 			}
1354 
1355 			// TODO: support B_LOCK_WINDOW_FOCUS option in Desktop
1356 			break;
1357 		}
1358 		case AS_VIEW_MOVE_TO:
1359 		{
1360 			float x, y;
1361 			link.Read<float>(&x);
1362 			if (link.Read<float>(&y) != B_OK)
1363 				break;
1364 
1365 			DTRACE(("ServerWindow %s: Message AS_VIEW_MOVE_TO: View name: "
1366 				"%s, x: %.1f, y: %.1f\n", fTitle, fCurrentView->Name(), x, y));
1367 
1368 			float offsetX = x - fCurrentView->Frame().left;
1369 			float offsetY = y - fCurrentView->Frame().top;
1370 
1371 			BRegion dirty;
1372 			fCurrentView->MoveBy(offsetX, offsetY, &dirty);
1373 
1374 			// TODO: think about how to avoid this hack:
1375 			// the parent clipping needs to be updated, it is not
1376 			// done in MoveBy() since it would cause
1377 			// too much computations when children are resized because
1378 			// follow modes
1379 			if (View* parent = fCurrentView->Parent())
1380 				parent->RebuildClipping(false);
1381 
1382 			fWindow->MarkContentDirty(dirty);
1383 			break;
1384 		}
1385 		case AS_VIEW_RESIZE_TO:
1386 		{
1387 			float newWidth, newHeight;
1388 			link.Read<float>(&newWidth);
1389 			if (link.Read<float>(&newHeight) != B_OK)
1390 				break;
1391 
1392 			DTRACE(("ServerWindow %s: Message AS_VIEW_RESIZE_TO: View name: "
1393 				"%s, width: %.1f, height: %.1f\n", fTitle,
1394 				fCurrentView->Name(), newWidth, newHeight));
1395 
1396 			float deltaWidth = newWidth - fCurrentView->Frame().Width();
1397 			float deltaHeight = newHeight - fCurrentView->Frame().Height();
1398 
1399 			BRegion dirty;
1400 			fCurrentView->ResizeBy(deltaWidth, deltaHeight, &dirty);
1401 
1402 			// TODO: see above
1403 			if (View* parent = fCurrentView->Parent())
1404 				parent->RebuildClipping(false);
1405 
1406 			fWindow->MarkContentDirty(dirty);
1407 			break;
1408 		}
1409 		case AS_VIEW_GET_COORD:
1410 		{
1411 			// our offset in the parent -> will be originX and originY
1412 			// in BView
1413 			BPoint parentOffset = fCurrentView->Frame().LeftTop();
1414 
1415 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_COORD: "
1416 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1417 				fCurrentView->Name(), parentOffset.x, parentOffset.y));
1418 
1419 			fLink.StartMessage(B_OK);
1420 			fLink.Attach<BPoint>(parentOffset);
1421 			fLink.Attach<BRect>(fCurrentView->Bounds());
1422 			fLink.Flush();
1423 			break;
1424 		}
1425 		case AS_VIEW_SET_ORIGIN:
1426 		{
1427 			float x, y;
1428 			link.Read<float>(&x);
1429 			if (link.Read<float>(&y) != B_OK)
1430 				break;
1431 
1432 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_ORIGIN: "
1433 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1434 				fCurrentView->Name(), x, y));
1435 
1436 			fCurrentView->SetDrawingOrigin(BPoint(x, y));
1437 			_UpdateDrawState(fCurrentView);
1438 			break;
1439 		}
1440 		case AS_VIEW_GET_ORIGIN:
1441 		{
1442 			BPoint drawingOrigin = fCurrentView->DrawingOrigin();
1443 
1444 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_ORIGIN: "
1445 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1446 				fCurrentView->Name(), drawingOrigin.x, drawingOrigin.y));
1447 
1448 			fLink.StartMessage(B_OK);
1449 			fLink.Attach<BPoint>(drawingOrigin);
1450 			fLink.Flush();
1451 			break;
1452 		}
1453 		case AS_VIEW_RESIZE_MODE:
1454 		{
1455 			uint32 resizeMode;
1456 			if (link.Read<uint32>(&resizeMode) != B_OK)
1457 				break;
1458 
1459 			DTRACE(("ServerWindow %s: Message AS_VIEW_RESIZE_MODE: "
1460 				"View: %s -> %ld\n", Title(), fCurrentView->Name(),
1461 				resizeMode));
1462 
1463 			fCurrentView->SetResizeMode(resizeMode);
1464 			break;
1465 		}
1466 		case AS_VIEW_SET_FLAGS:
1467 		{
1468 			uint32 flags;
1469 			link.Read<uint32>(&flags);
1470 
1471 			// The views clipping changes when the B_DRAW_ON_CHILDREN flag is
1472 			// toggled.
1473 			bool updateClipping = (flags & B_DRAW_ON_CHILDREN)
1474 				^ (fCurrentView->Flags() & B_DRAW_ON_CHILDREN);
1475 
1476 			fCurrentView->SetFlags(flags);
1477 			_UpdateDrawState(fCurrentView);
1478 
1479 			if (updateClipping) {
1480 				fCurrentView->RebuildClipping(false);
1481 				fCurrentDrawingRegionValid = false;
1482 			}
1483 
1484 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_FLAGS: "
1485 				"View: %s -> flags: %lu\n", Title(), fCurrentView->Name(),
1486 				flags));
1487 			break;
1488 		}
1489 		case AS_VIEW_HIDE:
1490 			DTRACE(("ServerWindow %s: Message AS_VIEW_HIDE: View: %s\n",
1491 				Title(), fCurrentView->Name()));
1492 			fCurrentView->SetHidden(true);
1493 			break;
1494 
1495 		case AS_VIEW_SHOW:
1496 			DTRACE(("ServerWindow %s: Message AS_VIEW_SHOW: View: %s\n",
1497 				Title(), fCurrentView->Name()));
1498 			fCurrentView->SetHidden(false);
1499 			break;
1500 
1501 		case AS_VIEW_SET_LINE_MODE:
1502 		{
1503 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_LINE_MODE: "
1504 				"View: %s\n", Title(), fCurrentView->Name()));
1505 			ViewSetLineModeInfo info;
1506 			if (link.Read<ViewSetLineModeInfo>(&info) != B_OK)
1507 				break;
1508 
1509 			fCurrentView->CurrentState()->SetLineCapMode(info.lineCap);
1510 			fCurrentView->CurrentState()->SetLineJoinMode(info.lineJoin);
1511 			fCurrentView->CurrentState()->SetMiterLimit(info.miterLimit);
1512 
1513 			fWindow->GetDrawingEngine()->SetStrokeMode(info.lineCap,
1514 				info.lineJoin, info.miterLimit);
1515 
1516 			break;
1517 		}
1518 		case AS_VIEW_GET_LINE_MODE:
1519 		{
1520 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_LINE_MODE: "
1521 				"View: %s\n", Title(), fCurrentView->Name()));
1522 			ViewSetLineModeInfo info;
1523 			info.lineJoin = fCurrentView->CurrentState()->LineJoinMode();
1524 			info.lineCap = fCurrentView->CurrentState()->LineCapMode();
1525 			info.miterLimit = fCurrentView->CurrentState()->MiterLimit();
1526 
1527 			fLink.StartMessage(B_OK);
1528 			fLink.Attach<ViewSetLineModeInfo>(info);
1529 			fLink.Flush();
1530 
1531 			break;
1532 		}
1533 		case AS_VIEW_PUSH_STATE:
1534 		{
1535 			DTRACE(("ServerWindow %s: Message AS_VIEW_PUSH_STATE: View: "
1536 				"%s\n", Title(), fCurrentView->Name()));
1537 
1538 			fCurrentView->PushState();
1539 			// TODO: is this necessary?
1540 //			_UpdateDrawState(fCurrentView);
1541 			break;
1542 		}
1543 		case AS_VIEW_POP_STATE:
1544 		{
1545 			DTRACE(("ServerWindow %s: Message AS_VIEW_POP_STATE: View: %s\n",
1546 				Title(), fCurrentView->Name()));
1547 
1548 			fCurrentView->PopState();
1549 			_UpdateDrawState(fCurrentView);
1550 			break;
1551 		}
1552 		case AS_VIEW_SET_SCALE:
1553 		{
1554 			float scale;
1555 			if (link.Read<float>(&scale) != B_OK)
1556 				break;
1557 
1558 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_SCALE: "
1559 				"View: %s -> scale: %.2f\n", Title(), fCurrentView->Name(),
1560 				scale));
1561 
1562 			fCurrentView->SetScale(scale);
1563 			_UpdateDrawState(fCurrentView);
1564 			break;
1565 		}
1566 		case AS_VIEW_GET_SCALE:
1567 		{
1568 			float scale = fCurrentView->CurrentState()->Scale();
1569 
1570 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_SCALE: "
1571 				"View: %s -> scale: %.2f\n",
1572 				Title(), fCurrentView->Name(), scale));
1573 
1574 			fLink.StartMessage(B_OK);
1575 			fLink.Attach<float>(scale);
1576 			fLink.Flush();
1577 			break;
1578 		}
1579 		case AS_VIEW_SET_PEN_LOC:
1580 		{
1581 			BPoint location;
1582 			if (link.Read<BPoint>(&location) != B_OK)
1583 				break;
1584 
1585 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PEN_LOC: "
1586 				"View: %s -> BPoint(%.1f, %.1f)\n", Title(),
1587 				fCurrentView->Name(), location.x, location.y));
1588 
1589 			fCurrentView->CurrentState()->SetPenLocation(location);
1590 			break;
1591 		}
1592 		case AS_VIEW_GET_PEN_LOC:
1593 		{
1594 			BPoint location = fCurrentView->CurrentState()->PenLocation();
1595 
1596 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_PEN_LOC: "
1597 				"View: %s -> BPoint(%.1f, %.1f)\n", Title(),
1598 				fCurrentView->Name(), location.x, location.y));
1599 
1600 			fLink.StartMessage(B_OK);
1601 			fLink.Attach<BPoint>(location);
1602 			fLink.Flush();
1603 
1604 			break;
1605 		}
1606 		case AS_VIEW_SET_PEN_SIZE:
1607 		{
1608 			float penSize;
1609 			if (link.Read<float>(&penSize) != B_OK)
1610 				break;
1611 
1612 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PEN_SIZE: "
1613 				"View: %s -> %.1f\n", Title(), fCurrentView->Name(), penSize));
1614 
1615 			fCurrentView->CurrentState()->SetPenSize(penSize);
1616 			fWindow->GetDrawingEngine()->SetPenSize(
1617 				fCurrentView->CurrentState()->PenSize());
1618 			break;
1619 		}
1620 		case AS_VIEW_GET_PEN_SIZE:
1621 		{
1622 			float penSize = fCurrentView->CurrentState()->UnscaledPenSize();
1623 
1624 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_PEN_SIZE: "
1625 				"View: %s -> %.1f\n", Title(), fCurrentView->Name(), penSize));
1626 
1627 			fLink.StartMessage(B_OK);
1628 			fLink.Attach<float>(penSize);
1629 			fLink.Flush();
1630 
1631 			break;
1632 		}
1633 		case AS_VIEW_SET_VIEW_COLOR:
1634 		{
1635 			rgb_color color;
1636 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1637 				break;
1638 
1639 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_VIEW_COLOR: "
1640 				"View: %s -> rgb_color(%d, %d, %d, %d)\n", Title(),
1641 				fCurrentView->Name(), color.red, color.green, color.blue,
1642 				color.alpha));
1643 
1644 			fCurrentView->SetViewColor(color);
1645 			break;
1646 		}
1647 		case AS_VIEW_GET_VIEW_COLOR:
1648 		{
1649 			rgb_color color = fCurrentView->ViewColor();
1650 
1651 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_VIEW_COLOR: "
1652 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1653 				Title(), fCurrentView->Name(), color.red, color.green,
1654 				color.blue, color.alpha));
1655 
1656 			fLink.StartMessage(B_OK);
1657 			fLink.Attach<rgb_color>(color);
1658 			fLink.Flush();
1659 			break;
1660 		}
1661 		case AS_VIEW_SET_HIGH_COLOR:
1662 		{
1663 			rgb_color color;
1664 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1665 				break;
1666 
1667 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_HIGH_COLOR: "
1668 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1669 				Title(), fCurrentView->Name(), color.red, color.green,
1670 				color.blue, color.alpha));
1671 
1672 			fCurrentView->CurrentState()->SetHighColor(color);
1673 			fWindow->GetDrawingEngine()->SetHighColor(color);
1674 			break;
1675 		}
1676 		case AS_VIEW_GET_HIGH_COLOR:
1677 		{
1678 			rgb_color color = fCurrentView->CurrentState()->HighColor();
1679 
1680 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_HIGH_COLOR: "
1681 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1682 				Title(), fCurrentView->Name(), color.red, color.green,
1683 				color.blue, color.alpha));
1684 
1685 			fLink.StartMessage(B_OK);
1686 			fLink.Attach<rgb_color>(color);
1687 			fLink.Flush();
1688 			break;
1689 		}
1690 		case AS_VIEW_SET_LOW_COLOR:
1691 		{
1692 			rgb_color color;
1693 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1694 				break;
1695 
1696 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_LOW_COLOR: "
1697 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1698 				Title(), fCurrentView->Name(), color.red, color.green,
1699 				color.blue, color.alpha));
1700 
1701 			fCurrentView->CurrentState()->SetLowColor(color);
1702 			fWindow->GetDrawingEngine()->SetLowColor(color);
1703 			break;
1704 		}
1705 		case AS_VIEW_GET_LOW_COLOR:
1706 		{
1707 			rgb_color color = fCurrentView->CurrentState()->LowColor();
1708 
1709 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_LOW_COLOR: "
1710 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1711 				Title(), fCurrentView->Name(), color.red, color.green,
1712 				color.blue, color.alpha));
1713 
1714 			fLink.StartMessage(B_OK);
1715 			fLink.Attach<rgb_color>(color);
1716 			fLink.Flush();
1717 			break;
1718 		}
1719 		case AS_VIEW_SET_PATTERN:
1720 		{
1721 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PATTERN: "
1722 				"View: %s\n", fTitle, fCurrentView->Name()));
1723 
1724 			pattern pat;
1725 			if (link.Read(&pat, sizeof(pattern)) != B_OK)
1726 				break;
1727 
1728 			fCurrentView->CurrentState()->SetPattern(Pattern(pat));
1729 			fWindow->GetDrawingEngine()->SetPattern(pat);
1730 			break;
1731 		}
1732 
1733 		case AS_VIEW_SET_BLENDING_MODE:
1734 		{
1735 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_BLEND_MODE: "
1736 				"View: %s\n", Title(), fCurrentView->Name()));
1737 
1738 			ViewBlendingModeInfo info;
1739 			if (link.Read<ViewBlendingModeInfo>(&info) != B_OK)
1740 				break;
1741 
1742 			fCurrentView->CurrentState()->SetBlendingMode(
1743 				info.sourceAlpha, info.alphaFunction);
1744 			fWindow->GetDrawingEngine()->SetBlendingMode(
1745 				info.sourceAlpha, info.alphaFunction);
1746 			break;
1747 		}
1748 		case AS_VIEW_GET_BLENDING_MODE:
1749 		{
1750 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_BLEND_MODE: "
1751 				"View: %s\n", Title(), fCurrentView->Name()));
1752 
1753 			ViewBlendingModeInfo info;
1754 			info.sourceAlpha = fCurrentView->CurrentState()->AlphaSrcMode();
1755 			info.alphaFunction = fCurrentView->CurrentState()->AlphaFncMode();
1756 
1757 			fLink.StartMessage(B_OK);
1758 			fLink.Attach<ViewBlendingModeInfo>(info);
1759 			fLink.Flush();
1760 
1761 			break;
1762 		}
1763 		case AS_VIEW_SET_DRAWING_MODE:
1764 		{
1765 			int8 drawingMode;
1766 			if (link.Read<int8>(&drawingMode) != B_OK)
1767 				break;
1768 
1769 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_DRAW_MODE: "
1770 				"View: %s -> %s\n", Title(), fCurrentView->Name(),
1771 				kDrawingModeMap[drawingMode]));
1772 
1773 			fCurrentView->CurrentState()->SetDrawingMode(
1774 				(drawing_mode)drawingMode);
1775 			fWindow->GetDrawingEngine()->SetDrawingMode(
1776 				(drawing_mode)drawingMode);
1777 			break;
1778 		}
1779 		case AS_VIEW_GET_DRAWING_MODE:
1780 		{
1781 			int8 drawingMode
1782 				= (int8)(fCurrentView->CurrentState()->GetDrawingMode());
1783 
1784 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_DRAW_MODE: "
1785 				"View: %s -> %s\n", Title(), fCurrentView->Name(),
1786 				kDrawingModeMap[drawingMode]));
1787 
1788 			fLink.StartMessage(B_OK);
1789 			fLink.Attach<int8>(drawingMode);
1790 			fLink.Flush();
1791 
1792 			break;
1793 		}
1794 		case AS_VIEW_SET_VIEW_BITMAP:
1795 		{
1796 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_VIEW_BITMAP: "
1797 				"View: %s\n", Title(), fCurrentView->Name()));
1798 
1799 			int32 bitmapToken, resizingMode, options;
1800 			BRect srcRect, dstRect;
1801 
1802 			link.Read<int32>(&bitmapToken);
1803 			link.Read<BRect>(&srcRect);
1804 			link.Read<BRect>(&dstRect);
1805 			link.Read<int32>(&resizingMode);
1806 			status_t status = link.Read<int32>(&options);
1807 
1808 			rgb_color colorKey = {0};
1809 
1810 			if (status == B_OK) {
1811 				ServerBitmap* bitmap = fServerApp->GetBitmap(bitmapToken);
1812 				if (bitmapToken == -1 || bitmap != NULL) {
1813 					bool wasOverlay = fCurrentView->ViewBitmap() != NULL
1814 						&& fCurrentView->ViewBitmap()->Overlay() != NULL;
1815 
1816 					fCurrentView->SetViewBitmap(bitmap, srcRect, dstRect,
1817 						resizingMode, options);
1818 
1819 					// TODO: if we revert the view color overlay handling
1820 					//	in View::Draw() to the BeOS version, we never
1821 					//	need to invalidate the view for overlays.
1822 
1823 					// Invalidate view - but only if this is a non-overlay
1824 					// switch
1825 					if (bitmap == NULL || bitmap->Overlay() == NULL
1826 						|| !wasOverlay) {
1827 						BRegion dirty((BRect)fCurrentView->Bounds());
1828 						fWindow->InvalidateView(fCurrentView, dirty);
1829 					}
1830 
1831 					if (bitmap != NULL && bitmap->Overlay() != NULL) {
1832 						bitmap->Overlay()->SetFlags(options);
1833 						colorKey = bitmap->Overlay()->Color();
1834 					}
1835 
1836 					if (bitmap != NULL)
1837 						bitmap->ReleaseReference();
1838 				} else
1839 					status = B_BAD_VALUE;
1840 			}
1841 
1842 			fLink.StartMessage(status);
1843 			if (status == B_OK && (options & AS_REQUEST_COLOR_KEY) != 0) {
1844 				// Attach color key for the overlay bitmap
1845 				fLink.Attach<rgb_color>(colorKey);
1846 			}
1847 
1848 			fLink.Flush();
1849 			break;
1850 		}
1851 		case AS_VIEW_PRINT_ALIASING:
1852 		{
1853 			DTRACE(("ServerWindow %s: Message AS_VIEW_PRINT_ALIASING: "
1854 				"View: %s\n", Title(), fCurrentView->Name()));
1855 
1856 			bool fontAliasing;
1857 			if (link.Read<bool>(&fontAliasing) == B_OK) {
1858 				fCurrentView->CurrentState()->SetForceFontAliasing(fontAliasing);
1859 				_UpdateDrawState(fCurrentView);
1860 			}
1861 			break;
1862 		}
1863 		case AS_VIEW_CLIP_TO_PICTURE:
1864 		{
1865 			DTRACE(("ServerWindow %s: Message AS_VIEW_CLIP_TO_PICTURE: "
1866 				"View: %s\n", Title(), fCurrentView->Name()));
1867 
1868 			// TODO: you are not allowed to use View regions here!!!
1869 
1870 			int32 pictureToken;
1871 			BPoint where;
1872 			bool inverse = false;
1873 
1874 			link.Read<int32>(&pictureToken);
1875 			link.Read<BPoint>(&where);
1876 			if (link.Read<bool>(&inverse) != B_OK)
1877 				break;
1878 
1879 			ServerPicture* picture = fServerApp->GetPicture(pictureToken);
1880 			if (picture == NULL)
1881 				break;
1882 
1883 			BRegion region;
1884 			// TODO: I think we also need the BView's token
1885 			// I think PictureToRegion would fit better into the View class (?)
1886 			if (PictureToRegion(picture, region, inverse, where) == B_OK)
1887 				fCurrentView->SetUserClipping(&region);
1888 
1889 			picture->ReleaseReference();
1890 			break;
1891 		}
1892 
1893 		case AS_VIEW_GET_CLIP_REGION:
1894 		{
1895 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_CLIP_REGION: "
1896 				"View: %s\n", Title(), fCurrentView->Name()));
1897 
1898 			// if this view is hidden, it has no visible region
1899 			fLink.StartMessage(B_OK);
1900 			if (!fWindow->IsVisible() || !fCurrentView->IsVisible()) {
1901 				BRegion empty;
1902 				fLink.AttachRegion(empty);
1903 			} else {
1904 				_UpdateCurrentDrawingRegion();
1905 				BRegion region(fCurrentDrawingRegion);
1906 				fCurrentView->ConvertFromScreen(&region);
1907 				fLink.AttachRegion(region);
1908 			}
1909 			fLink.Flush();
1910 
1911 			break;
1912 		}
1913 		case AS_VIEW_SET_CLIP_REGION:
1914 		{
1915 			int32 rectCount;
1916 			status_t status = link.Read<int32>(&rectCount);
1917 				// a negative count means no
1918 				// region for the current draw state,
1919 				// but an *empty* region is actually valid!
1920 				// even if it means no drawing is allowed
1921 
1922 			if (status < B_OK)
1923 				break;
1924 
1925 			if (rectCount >= 0) {
1926 				// we are supposed to set the clipping region
1927 				BRegion region;
1928 				if (rectCount > 0 && link.ReadRegion(&region) < B_OK)
1929 					break;
1930 
1931 				DTRACE(("ServerWindow %s: Message AS_VIEW_SET_CLIP_REGION: "
1932 					"View: %s -> rect count: %ld, frame = "
1933 					"BRect(%.1f, %.1f, %.1f, %.1f)\n",
1934 					Title(), fCurrentView->Name(), rectCount,
1935 					region.Frame().left, region.Frame().top,
1936 					region.Frame().right, region.Frame().bottom));
1937 
1938 				fCurrentView->SetUserClipping(&region);
1939 			} else {
1940 				// we are supposed to unset the clipping region
1941 				// passing NULL sets this states region to that
1942 				// of the previous state
1943 
1944 				DTRACE(("ServerWindow %s: Message AS_VIEW_SET_CLIP_REGION: "
1945 					"View: %s -> unset\n", Title(), fCurrentView->Name()));
1946 
1947 				fCurrentView->SetUserClipping(NULL);
1948 			}
1949 			fCurrentDrawingRegionValid = false;
1950 
1951 			break;
1952 		}
1953 
1954 		case AS_VIEW_INVALIDATE_RECT:
1955 		{
1956 			// NOTE: looks like this call is NOT affected by origin and scale
1957 			// on R5 so this implementation is "correct"
1958 			BRect invalidRect;
1959 			if (link.Read<BRect>(&invalidRect) == B_OK) {
1960 				DTRACE(("ServerWindow %s: Message AS_VIEW_INVALIDATE_RECT: "
1961 					"View: %s -> BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
1962 					fCurrentView->Name(), invalidRect.left, invalidRect.top,
1963 					invalidRect.right, invalidRect.bottom));
1964 
1965 				BRegion dirty(invalidRect);
1966 				fWindow->InvalidateView(fCurrentView, dirty);
1967 			}
1968 			break;
1969 		}
1970 		case AS_VIEW_INVALIDATE_REGION:
1971 		{
1972 			// NOTE: looks like this call is NOT affected by origin and scale
1973 			// on R5 so this implementation is "correct"
1974 			BRegion region;
1975 			if (link.ReadRegion(&region) < B_OK)
1976 				break;
1977 
1978 			DTRACE(("ServerWindow %s: Message AS_VIEW_INVALIDATE_REGION: "
1979 					"View: %s -> rect count: %ld, frame: BRect(%.1f, %.1f, "
1980 					"%.1f, %.1f)\n", Title(),
1981 					fCurrentView->Name(), region.CountRects(),
1982 					region.Frame().left, region.Frame().top,
1983 					region.Frame().right, region.Frame().bottom));
1984 
1985 			fWindow->InvalidateView(fCurrentView, region);
1986 			break;
1987 		}
1988 
1989 		case AS_VIEW_DRAG_IMAGE:
1990 		{
1991 			// TODO: flesh out AS_VIEW_DRAG_IMAGE
1992 			DTRACE(("ServerWindow %s: Message AS_DRAG_IMAGE\n", Title()));
1993 
1994 			int32 bitmapToken;
1995 			drawing_mode dragMode;
1996 			BPoint offset;
1997 			int32 bufferSize;
1998 
1999 			link.Read<int32>(&bitmapToken);
2000 			link.Read<int32>((int32*)&dragMode);
2001 			link.Read<BPoint>(&offset);
2002 			link.Read<int32>(&bufferSize);
2003 
2004 			if (bufferSize > 0) {
2005 				char* buffer = new (nothrow) char[bufferSize];
2006 				BMessage dragMessage;
2007 				if (link.Read(buffer, bufferSize) == B_OK
2008 					&& dragMessage.Unflatten(buffer) == B_OK) {
2009 						ServerBitmap* bitmap
2010 							= fServerApp->GetBitmap(bitmapToken);
2011 						// TODO: possible deadlock
2012 fDesktop->UnlockSingleWindow();
2013 						fDesktop->EventDispatcher().SetDragMessage(dragMessage,
2014 							bitmap, offset);
2015 fDesktop->LockSingleWindow();
2016 						bitmap->ReleaseReference();
2017 				}
2018 				delete[] buffer;
2019 			}
2020 			// sync the client (it can now delete the bitmap)
2021 			fLink.StartMessage(B_OK);
2022 			fLink.Flush();
2023 
2024 			break;
2025 		}
2026 		case AS_VIEW_DRAG_RECT:
2027 		{
2028 			// TODO: flesh out AS_VIEW_DRAG_RECT
2029 			DTRACE(("ServerWindow %s: Message AS_DRAG_RECT\n", Title()));
2030 
2031 			BRect dragRect;
2032 			BPoint offset;
2033 			int32 bufferSize;
2034 
2035 			link.Read<BRect>(&dragRect);
2036 			link.Read<BPoint>(&offset);
2037 			link.Read<int32>(&bufferSize);
2038 
2039 			if (bufferSize > 0) {
2040 				char* buffer = new (nothrow) char[bufferSize];
2041 				BMessage dragMessage;
2042 				if (link.Read(buffer, bufferSize) == B_OK
2043 					&& dragMessage.Unflatten(buffer) == B_OK) {
2044 						// TODO: possible deadlock
2045 fDesktop->UnlockSingleWindow();
2046 						fDesktop->EventDispatcher().SetDragMessage(dragMessage,
2047 							NULL /* should be dragRect */, offset);
2048 fDesktop->LockSingleWindow();
2049 				}
2050 				delete[] buffer;
2051 			}
2052 			break;
2053 		}
2054 
2055 		case AS_VIEW_BEGIN_RECT_TRACK:
2056 		{
2057 			DTRACE(("ServerWindow %s: Message AS_VIEW_BEGIN_RECT_TRACK\n",
2058 				Title()));
2059 			BRect dragRect;
2060 			uint32 style;
2061 
2062 			link.Read<BRect>(&dragRect);
2063 			link.Read<uint32>(&style);
2064 
2065 			// TODO: implement rect tracking (used sometimes for selecting
2066 			// a group of things, also sometimes used to appear to drag
2067 			// something, but without real drag message)
2068 			break;
2069 		}
2070 		case AS_VIEW_END_RECT_TRACK:
2071 		{
2072 			DTRACE(("ServerWindow %s: Message AS_VIEW_END_RECT_TRACK\n",
2073 				Title()));
2074 			// TODO: implement rect tracking
2075 			break;
2076 		}
2077 
2078 		case AS_VIEW_BEGIN_PICTURE:
2079 		{
2080 			DTRACE(("ServerWindow %s: Message AS_VIEW_BEGIN_PICTURE\n",
2081 				Title()));
2082 			ServerPicture* picture = App()->CreatePicture();
2083 			if (picture != NULL) {
2084 				picture->SyncState(fCurrentView);
2085 				fCurrentView->SetPicture(picture);
2086 			}
2087 			break;
2088 		}
2089 
2090 		case AS_VIEW_APPEND_TO_PICTURE:
2091 		{
2092 			DTRACE(("ServerWindow %s: Message AS_VIEW_APPEND_TO_PICTURE\n",
2093 				Title()));
2094 
2095 			int32 token;
2096 			link.Read<int32>(&token);
2097 
2098 			ServerPicture* picture = App()->GetPicture(token);
2099 			if (picture != NULL)
2100 				picture->SyncState(fCurrentView);
2101 
2102 			fCurrentView->SetPicture(picture);
2103 
2104 			if (picture != NULL)
2105 				picture->ReleaseReference();
2106 			break;
2107 		}
2108 
2109 		case AS_VIEW_END_PICTURE:
2110 		{
2111 			DTRACE(("ServerWindow %s: Message AS_VIEW_END_PICTURE\n",
2112 				Title()));
2113 
2114 			ServerPicture* picture = fCurrentView->Picture();
2115 			if (picture != NULL) {
2116 				fCurrentView->SetPicture(NULL);
2117 				fLink.StartMessage(B_OK);
2118 				fLink.Attach<int32>(picture->Token());
2119 			} else
2120 				fLink.StartMessage(B_ERROR);
2121 
2122 			fLink.Flush();
2123 			break;
2124 		}
2125 
2126 		default:
2127 			_DispatchViewDrawingMessage(code, link);
2128 			break;
2129 	}
2130 }
2131 
2132 
2133 /*!	Dispatches all view drawing messages.
2134 	The desktop clipping must be read locked when entering this method.
2135 	Requires a valid fCurrentView.
2136 */
2137 void
2138 ServerWindow::_DispatchViewDrawingMessage(int32 code,
2139 	BPrivate::LinkReceiver &link)
2140 {
2141 	if (!fCurrentView->IsVisible() || !fWindow->IsVisible()) {
2142 		if (link.NeedsReply()) {
2143 			debug_printf("ServerWindow::DispatchViewDrawingMessage() got "
2144 				"message %ld that needs a reply!\n", code);
2145 			// the client is now blocking and waiting for a reply!
2146 			fLink.StartMessage(B_ERROR);
2147 			fLink.Flush();
2148 		}
2149 		return;
2150 	}
2151 
2152 	DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
2153 	if (!drawingEngine) {
2154 		// ?!?
2155 		debug_printf("ServerWindow %s: no drawing engine!!\n", Title());
2156 		if (link.NeedsReply()) {
2157 			// the client is now blocking and waiting for a reply!
2158 			fLink.StartMessage(B_ERROR);
2159 			fLink.Flush();
2160 		}
2161 		return;
2162 	}
2163 
2164 	_UpdateCurrentDrawingRegion();
2165 	if (fCurrentDrawingRegion.CountRects() <= 0) {
2166 		DTRACE(("ServerWindow %s: _DispatchViewDrawingMessage(): View: %s, "
2167 			"INVALID CLIPPING!\n", Title(), fCurrentView->Name()));
2168 		if (link.NeedsReply()) {
2169 			// the client is now blocking and waiting for a reply!
2170 			fLink.StartMessage(B_ERROR);
2171 			fLink.Flush();
2172 		}
2173 		return;
2174 	}
2175 
2176 	drawingEngine->LockParallelAccess();
2177 	// NOTE: the region is not copied, Painter keeps a pointer,
2178 	// that's why you need to use the clipping only for as long
2179 	// as you have it locked
2180 	drawingEngine->ConstrainClippingRegion(&fCurrentDrawingRegion);
2181 
2182 	switch (code) {
2183 		case AS_STROKE_LINE:
2184 		{
2185 			ViewStrokeLineInfo info;
2186 			if (link.Read<ViewStrokeLineInfo>(&info) != B_OK)
2187 				break;
2188 
2189 			DTRACE(("ServerWindow %s: Message AS_STROKE_LINE: View: %s -> "
2190 				"BPoint(%.1f, %.1f) - BPoint(%.1f, %.1f)\n", Title(),
2191 					fCurrentView->Name(),
2192 					info.startPoint.x, info.startPoint.y,
2193 					info.endPoint.x, info.endPoint.y));
2194 
2195 			BPoint penPos = info.endPoint;
2196 			fCurrentView->ConvertToScreenForDrawing(&info.startPoint);
2197 			fCurrentView->ConvertToScreenForDrawing(&info.endPoint);
2198 			drawingEngine->StrokeLine(info.startPoint, info.endPoint);
2199 
2200 			// We update the pen here because many DrawingEngine calls which
2201 			// do not update the pen position actually call StrokeLine
2202 
2203 			// TODO: Decide where to put this, for example, it cannot be done
2204 			// for DrawString(), also there needs to be a decision, if the pen
2205 			// location is in View coordinates (I think it should be) or in
2206 			// screen coordinates.
2207 			fCurrentView->CurrentState()->SetPenLocation(penPos);
2208 			break;
2209 		}
2210 		case AS_VIEW_INVERT_RECT:
2211 		{
2212 			BRect rect;
2213 			if (link.Read<BRect>(&rect) != B_OK)
2214 				break;
2215 
2216 			DTRACE(("ServerWindow %s: Message AS_INVERT_RECT: View: %s -> "
2217 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2218 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2219 				rect.bottom));
2220 
2221 			fCurrentView->ConvertToScreenForDrawing(&rect);
2222 			drawingEngine->InvertRect(rect);
2223 			break;
2224 		}
2225 		case AS_STROKE_RECT:
2226 		{
2227 			BRect rect;
2228 			if (link.Read<BRect>(&rect) != B_OK)
2229 				break;
2230 
2231 			DTRACE(("ServerWindow %s: Message AS_STROKE_RECT: View: %s -> "
2232 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2233 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2234 				rect.bottom));
2235 
2236 			fCurrentView->ConvertToScreenForDrawing(&rect);
2237 			drawingEngine->StrokeRect(rect);
2238 			break;
2239 		}
2240 		case AS_FILL_RECT:
2241 		{
2242 			BRect rect;
2243 			if (link.Read<BRect>(&rect) != B_OK)
2244 				break;
2245 
2246 			DTRACE(("ServerWindow %s: Message AS_FILL_RECT: View: %s -> "
2247 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2248 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2249 				rect.bottom));
2250 
2251 			fCurrentView->ConvertToScreenForDrawing(&rect);
2252 			drawingEngine->FillRect(rect);
2253 			break;
2254 		}
2255 		case AS_FILL_RECT_GRADIENT:
2256 		{
2257 			BRect rect;
2258 			link.Read<BRect>(&rect);
2259 			BGradient* gradient;
2260 			if (link.ReadGradient(&gradient) != B_OK)
2261 				break;
2262 
2263 			GTRACE(("ServerWindow %s: Message AS_FILL_RECT_GRADIENT: View: %s "
2264 				"-> BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2265 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2266 				rect.bottom));
2267 
2268 			fCurrentView->ConvertToScreenForDrawing(&rect);
2269 			fCurrentView->ConvertToScreenForDrawing(gradient);
2270 			drawingEngine->FillRect(rect, *gradient);
2271 			break;
2272 		}
2273 		case AS_VIEW_DRAW_BITMAP:
2274 		{
2275 			ViewDrawBitmapInfo info;
2276 			if (link.Read<ViewDrawBitmapInfo>(&info) != B_OK)
2277 				break;
2278 
2279 #if 0
2280 			if (strcmp(fServerApp->SignatureLeaf(), "x-vnd.videolan-vlc") == 0)
2281 				options |= B_FILTER_BITMAP_BILINEAR;
2282 #endif
2283 
2284 			ServerBitmap* bitmap = fServerApp->GetBitmap(info.bitmapToken);
2285 			if (bitmap != NULL) {
2286 				DTRACE(("ServerWindow %s: Message AS_VIEW_DRAW_BITMAP: "
2287 					"View: %s, bitmap: %ld (size %ld x %ld), "
2288 					"BRect(%.1f, %.1f, %.1f, %.1f) -> "
2289 					"BRect(%.1f, %.1f, %.1f, %.1f)\n",
2290 					fTitle, fCurrentView->Name(), info.bitmapToken,
2291 					bitmap->Width(), bitmap->Height(),
2292 					info.bitmapRect.left, info.bitmapRect.top,
2293 					info.bitmapRect.right, info.bitmapRect.bottom,
2294 					info.viewRect.left, info.viewRect.top,
2295 					info.viewRect.right, info.viewRect.bottom));
2296 
2297 				fCurrentView->ConvertToScreenForDrawing(&info.viewRect);
2298 
2299 				drawingEngine->DrawBitmap(bitmap, info.bitmapRect,
2300 					info.viewRect, info.options);
2301 
2302 				bitmap->ReleaseReference();
2303 			}
2304 			break;
2305 		}
2306 		case AS_STROKE_ARC:
2307 		case AS_FILL_ARC:
2308 		{
2309 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ARC\n", Title()));
2310 
2311 			float angle, span;
2312 			BRect r;
2313 
2314 			link.Read<BRect>(&r);
2315 			link.Read<float>(&angle);
2316 			if (link.Read<float>(&span) != B_OK)
2317 				break;
2318 
2319 			fCurrentView->ConvertToScreenForDrawing(&r);
2320 			drawingEngine->DrawArc(r, angle, span, code == AS_FILL_ARC);
2321 			break;
2322 		}
2323 		case AS_FILL_ARC_GRADIENT:
2324 		{
2325 			GTRACE(("ServerWindow %s: Message AS_FILL_ARC_GRADIENT\n",
2326 				Title()));
2327 
2328 			float angle, span;
2329 			BRect r;
2330 			link.Read<BRect>(&r);
2331 			link.Read<float>(&angle);
2332 			link.Read<float>(&span);
2333 			BGradient* gradient;
2334 			if (link.ReadGradient(&gradient) != B_OK)
2335 				break;
2336 			fCurrentView->ConvertToScreenForDrawing(&r);
2337 			fCurrentView->ConvertToScreenForDrawing(gradient);
2338 			drawingEngine->FillArc(r, angle, span, *gradient);
2339 			break;
2340 		}
2341 		case AS_STROKE_BEZIER:
2342 		case AS_FILL_BEZIER:
2343 		{
2344 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_BEZIER\n",
2345 				Title()));
2346 
2347 			BPoint pts[4];
2348 			status_t status;
2349 			for (int32 i = 0; i < 4; i++) {
2350 				status = link.Read<BPoint>(&(pts[i]));
2351 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2352 			}
2353 			if (status != B_OK)
2354 				break;
2355 
2356 			drawingEngine->DrawBezier(pts, code == AS_FILL_BEZIER);
2357 			break;
2358 		}
2359 		case AS_FILL_BEZIER_GRADIENT:
2360 		{
2361 			GTRACE(("ServerWindow %s: Message AS_FILL_BEZIER_GRADIENT\n",
2362 				Title()));
2363 
2364 			BPoint pts[4];
2365 			for (int32 i = 0; i < 4; i++) {
2366 				link.Read<BPoint>(&(pts[i]));
2367 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2368 			}
2369 			BGradient* gradient;
2370 			if (link.ReadGradient(&gradient) != B_OK)
2371 				break;
2372 			fCurrentView->ConvertToScreenForDrawing(gradient);
2373 			drawingEngine->FillBezier(pts, *gradient);
2374 			break;
2375 		}
2376 		case AS_STROKE_ELLIPSE:
2377 		case AS_FILL_ELLIPSE:
2378 		{
2379 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ELLIPSE\n",
2380 				Title()));
2381 
2382 			BRect rect;
2383 			if (link.Read<BRect>(&rect) != B_OK)
2384 				break;
2385 
2386 			fCurrentView->ConvertToScreenForDrawing(&rect);
2387 			drawingEngine->DrawEllipse(rect, code == AS_FILL_ELLIPSE);
2388 			break;
2389 		}
2390 		case AS_FILL_ELLIPSE_GRADIENT:
2391 		{
2392 			GTRACE(("ServerWindow %s: Message AS_FILL_ELLIPSE_GRADIENT\n",
2393 				Title()));
2394 
2395 			BRect rect;
2396 			link.Read<BRect>(&rect);
2397 			BGradient* gradient;
2398 			if (link.ReadGradient(&gradient) != B_OK)
2399 				break;
2400 			fCurrentView->ConvertToScreenForDrawing(&rect);
2401 			fCurrentView->ConvertToScreenForDrawing(gradient);
2402 			drawingEngine->FillEllipse(rect, *gradient);
2403 			break;
2404 		}
2405 		case AS_STROKE_ROUNDRECT:
2406 		case AS_FILL_ROUNDRECT:
2407 		{
2408 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ROUNDRECT\n",
2409 				Title()));
2410 
2411 			BRect rect;
2412 			float xrad,yrad;
2413 			link.Read<BRect>(&rect);
2414 			link.Read<float>(&xrad);
2415 			if (link.Read<float>(&yrad) != B_OK)
2416 				break;
2417 
2418 			fCurrentView->ConvertToScreenForDrawing(&rect);
2419 			drawingEngine->DrawRoundRect(rect, xrad, yrad,
2420 				code == AS_FILL_ROUNDRECT);
2421 			break;
2422 		}
2423 		case AS_FILL_ROUNDRECT_GRADIENT:
2424 		{
2425 			GTRACE(("ServerWindow %s: Message AS_FILL_ROUNDRECT_GRADIENT\n",
2426 				Title()));
2427 
2428 			BRect rect;
2429 			float xrad,yrad;
2430 			link.Read<BRect>(&rect);
2431 			link.Read<float>(&xrad);
2432 			link.Read<float>(&yrad);
2433 			BGradient* gradient;
2434 			if (link.ReadGradient(&gradient) != B_OK)
2435 				break;
2436 			fCurrentView->ConvertToScreenForDrawing(&rect);
2437 			fCurrentView->ConvertToScreenForDrawing(gradient);
2438 			drawingEngine->FillRoundRect(rect, xrad, yrad, *gradient);
2439 			break;
2440 		}
2441 		case AS_STROKE_TRIANGLE:
2442 		case AS_FILL_TRIANGLE:
2443 		{
2444 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_TRIANGLE\n",
2445 				Title()));
2446 
2447 			BPoint pts[3];
2448 			BRect rect;
2449 
2450 			for (int32 i = 0; i < 3; i++) {
2451 				link.Read<BPoint>(&(pts[i]));
2452 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2453 			}
2454 
2455 			if (link.Read<BRect>(&rect) != B_OK)
2456 				break;
2457 
2458 			fCurrentView->ConvertToScreenForDrawing(&rect);
2459 			drawingEngine->DrawTriangle(pts, rect, code == AS_FILL_TRIANGLE);
2460 			break;
2461 		}
2462 		case AS_FILL_TRIANGLE_GRADIENT:
2463 		{
2464 			DTRACE(("ServerWindow %s: Message AS_FILL_TRIANGLE_GRADIENT\n",
2465 				Title()));
2466 
2467 			BPoint pts[3];
2468 			BRect rect;
2469 			for (int32 i = 0; i < 3; i++) {
2470 				link.Read<BPoint>(&(pts[i]));
2471 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2472 			}
2473 			link.Read<BRect>(&rect);
2474 			BGradient* gradient;
2475 			if (link.ReadGradient(&gradient) != B_OK)
2476 				break;
2477 			fCurrentView->ConvertToScreenForDrawing(&rect);
2478 			fCurrentView->ConvertToScreenForDrawing(gradient);
2479 			drawingEngine->FillTriangle(pts, rect, *gradient);
2480 			break;
2481 		}
2482 		case AS_STROKE_POLYGON:
2483 		case AS_FILL_POLYGON:
2484 		{
2485 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_POLYGON\n",
2486 				Title()));
2487 
2488 			BRect polyFrame;
2489 			bool isClosed = true;
2490 			int32 pointCount;
2491 
2492 			link.Read<BRect>(&polyFrame);
2493 			if (code == AS_STROKE_POLYGON)
2494 				link.Read<bool>(&isClosed);
2495 			link.Read<int32>(&pointCount);
2496 
2497 			BPoint* pointList = new(nothrow) BPoint[pointCount];
2498 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK) {
2499 				for (int32 i = 0; i < pointCount; i++)
2500 					fCurrentView->ConvertToScreenForDrawing(&pointList[i]);
2501 				fCurrentView->ConvertToScreenForDrawing(&polyFrame);
2502 
2503 				drawingEngine->DrawPolygon(pointList, pointCount, polyFrame,
2504 					code == AS_FILL_POLYGON, isClosed && pointCount > 2);
2505 			}
2506 			delete[] pointList;
2507 			break;
2508 		}
2509 		case AS_FILL_POLYGON_GRADIENT:
2510 		{
2511 			DTRACE(("ServerWindow %s: Message AS_FILL_POLYGON_GRADIENT\n",
2512 				Title()));
2513 
2514 			BRect polyFrame;
2515 			bool isClosed = true;
2516 			int32 pointCount;
2517 			link.Read<BRect>(&polyFrame);
2518 			link.Read<int32>(&pointCount);
2519 
2520 			BPoint* pointList = new(nothrow) BPoint[pointCount];
2521 			BGradient* gradient;
2522 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK
2523 				&& link.ReadGradient(&gradient) >= B_OK) {
2524 				for (int32 i = 0; i < pointCount; i++)
2525 					fCurrentView->ConvertToScreenForDrawing(&pointList[i]);
2526 				fCurrentView->ConvertToScreenForDrawing(&polyFrame);
2527 				fCurrentView->ConvertToScreenForDrawing(gradient);
2528 
2529 				drawingEngine->FillPolygon(pointList, pointCount,
2530 					polyFrame, *gradient, isClosed && pointCount > 2);
2531 			}
2532 			delete[] pointList;
2533 			break;
2534 		}
2535 		case AS_STROKE_SHAPE:
2536 		case AS_FILL_SHAPE:
2537 		{
2538 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_SHAPE\n",
2539 				Title()));
2540 
2541 			BRect shapeFrame;
2542 			int32 opCount;
2543 			int32 ptCount;
2544 
2545 			link.Read<BRect>(&shapeFrame);
2546 			link.Read<int32>(&opCount);
2547 			link.Read<int32>(&ptCount);
2548 
2549 			uint32* opList = new(nothrow) uint32[opCount];
2550 			BPoint* ptList = new(nothrow) BPoint[ptCount];
2551 			if (link.Read(opList, opCount * sizeof(uint32)) >= B_OK &&
2552 				link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK) {
2553 
2554 				// this might seem a bit weird, but under R5, the shapes
2555 				// are always offset by the current pen location
2556 				BPoint screenOffset
2557 					= fCurrentView->CurrentState()->PenLocation();
2558 				shapeFrame.OffsetBy(screenOffset);
2559 
2560 				fCurrentView->ConvertToScreenForDrawing(&screenOffset);
2561 				fCurrentView->ConvertToScreenForDrawing(&shapeFrame);
2562 
2563 				drawingEngine->DrawShape(shapeFrame, opCount, opList, ptCount,
2564 					ptList, code == AS_FILL_SHAPE, screenOffset,
2565 					fCurrentView->Scale());
2566 			}
2567 
2568 			delete[] opList;
2569 			delete[] ptList;
2570 			break;
2571 		}
2572 		case AS_FILL_SHAPE_GRADIENT:
2573 		{
2574 			DTRACE(("ServerWindow %s: Message AS_FILL_SHAPE_GRADIENT\n",
2575 				Title()));
2576 
2577 			BRect shapeFrame;
2578 			int32 opCount;
2579 			int32 ptCount;
2580 
2581 			link.Read<BRect>(&shapeFrame);
2582 			link.Read<int32>(&opCount);
2583 			link.Read<int32>(&ptCount);
2584 
2585 			uint32* opList = new(nothrow) uint32[opCount];
2586 			BPoint* ptList = new(nothrow) BPoint[ptCount];
2587 			BGradient* gradient;
2588 			if (link.Read(opList, opCount * sizeof(uint32)) >= B_OK
2589 				&& link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK
2590 				&& link.ReadGradient(&gradient) >= B_OK) {
2591 
2592 				// this might seem a bit weird, but under R5, the shapes
2593 				// are always offset by the current pen location
2594 				BPoint screenOffset
2595 					= fCurrentView->CurrentState()->PenLocation();
2596 				shapeFrame.OffsetBy(screenOffset);
2597 
2598 				fCurrentView->ConvertToScreenForDrawing(&screenOffset);
2599 				fCurrentView->ConvertToScreenForDrawing(&shapeFrame);
2600 				fCurrentView->ConvertToScreenForDrawing(gradient);
2601 				drawingEngine->FillShape(shapeFrame, opCount, opList,
2602 					ptCount, ptList, *gradient, screenOffset,
2603 					fCurrentView->Scale());
2604 			}
2605 
2606 			delete[] opList;
2607 			delete[] ptList;
2608 			break;
2609 		}
2610 		case AS_FILL_REGION:
2611 		{
2612 			DTRACE(("ServerWindow %s: Message AS_FILL_REGION\n", Title()));
2613 
2614 			BRegion region;
2615 			if (link.ReadRegion(&region) < B_OK)
2616 				break;
2617 
2618 			fCurrentView->ConvertToScreenForDrawing(&region);
2619 			drawingEngine->FillRegion(region);
2620 
2621 			break;
2622 		}
2623 		case AS_FILL_REGION_GRADIENT:
2624 		{
2625 			DTRACE(("ServerWindow %s: Message AS_FILL_REGION_GRADIENT\n",
2626 				Title()));
2627 
2628 			BRegion region;
2629 			link.ReadRegion(&region);
2630 
2631 			BGradient* gradient;
2632 			if (link.ReadGradient(&gradient) != B_OK)
2633 				break;
2634 
2635 			fCurrentView->ConvertToScreenForDrawing(&region);
2636 			fCurrentView->ConvertToScreenForDrawing(gradient);
2637 			drawingEngine->FillRegion(region, *gradient);
2638 			break;
2639 		}
2640 		case AS_STROKE_LINEARRAY:
2641 		{
2642 			DTRACE(("ServerWindow %s: Message AS_STROKE_LINEARRAY\n",
2643 				Title()));
2644 
2645 			// Attached Data:
2646 			// 1) int32 Number of lines in the array
2647 			// 2) LineArrayData
2648 
2649 			int32 lineCount;
2650 			if (link.Read<int32>(&lineCount) != B_OK || lineCount <= 0)
2651 				break;
2652 
2653 			// To speed things up, try to use a stack allocation and only
2654 			// fall back to the heap if there are enough lines...
2655 			ViewLineArrayInfo* lineData;
2656 			const int32 kStackBufferLineDataCount = 64;
2657 			ViewLineArrayInfo lineDataStackBuffer[kStackBufferLineDataCount];
2658 			if (lineCount > kStackBufferLineDataCount) {
2659 				lineData = new(std::nothrow) ViewLineArrayInfo[lineCount];
2660 				if (lineData == NULL)
2661 					break;
2662 			} else
2663 				lineData = lineDataStackBuffer;
2664 
2665 			// Read them all in one go
2666 			size_t dataSize = lineCount * sizeof(ViewLineArrayInfo);
2667 			if (link.Read(lineData, dataSize) != B_OK) {
2668 				if (lineData != lineDataStackBuffer)
2669 					delete[] lineData;
2670 				break;
2671 			}
2672 
2673 			// Convert to screen coords and draw
2674 			for (int32 i = 0; i < lineCount; i++) {
2675 				fCurrentView->ConvertToScreenForDrawing(
2676 					&lineData[i].startPoint);
2677 				fCurrentView->ConvertToScreenForDrawing(
2678 					&lineData[i].endPoint);
2679 			}
2680 			drawingEngine->StrokeLineArray(lineCount, lineData);
2681 
2682 			if (lineData != lineDataStackBuffer)
2683 				delete[] lineData;
2684 			break;
2685 		}
2686 		case AS_DRAW_STRING:
2687 		case AS_DRAW_STRING_WITH_DELTA:
2688 		{
2689 			ViewDrawStringInfo info;
2690 			if (link.Read<ViewDrawStringInfo>(&info) != B_OK
2691 				|| info.stringLength <= 0) {
2692 				break;
2693 			}
2694 
2695 			const ssize_t kMaxStackStringSize = 4096;
2696 			char stackString[kMaxStackStringSize];
2697 			char* string = stackString;
2698 			if (info.stringLength >= kMaxStackStringSize) {
2699 				// NOTE: Careful, the + 1 is for termination!
2700 				string = (char*)malloc((info.stringLength + 1 + 63) / 64 * 64);
2701 				if (string == NULL)
2702 					break;
2703 			}
2704 
2705 			escapement_delta* delta = NULL;
2706 			if (code == AS_DRAW_STRING_WITH_DELTA) {
2707 				// In this case, info.delta will contain valid values.
2708 				delta = &info.delta;
2709 			}
2710 
2711 			if (link.Read(string, info.stringLength) != B_OK) {
2712 				if (string != stackString)
2713 					free(string);
2714 				break;
2715 			}
2716 			// Terminate the string, if nothing else, it's important
2717 			// for the DTRACE call below...
2718 			string[info.stringLength] = '\0';
2719 
2720 			DTRACE(("ServerWindow %s: Message AS_DRAW_STRING, View: %s "
2721 				"-> %s\n", Title(), fCurrentView->Name(), string));
2722 
2723 			fCurrentView->ConvertToScreenForDrawing(&info.location);
2724 			BPoint penLocation = drawingEngine->DrawString(string,
2725 				info.stringLength, info.location, delta);
2726 
2727 			fCurrentView->ConvertFromScreenForDrawing(&penLocation);
2728 			fCurrentView->CurrentState()->SetPenLocation(penLocation);
2729 
2730 			if (string != stackString)
2731 				free(string);
2732 			break;
2733 		}
2734 		case AS_DRAW_STRING_WITH_OFFSETS:
2735 		{
2736 			int32 stringLength;
2737 			if (link.Read<int32>(&stringLength) != B_OK || stringLength <= 0)
2738 				break;
2739 
2740 			int32 glyphCount;
2741 			if (link.Read<int32>(&glyphCount) != B_OK || glyphCount <= 0)
2742 				break;
2743 
2744 			const ssize_t kMaxStackStringSize = 512;
2745 			char stackString[kMaxStackStringSize];
2746 			char* string = stackString;
2747 			BPoint stackLocations[kMaxStackStringSize];
2748 			BPoint* locations = stackLocations;
2749 			MemoryDeleter stringDeleter;
2750 			MemoryDeleter locationsDeleter;
2751 			if (stringLength >= kMaxStackStringSize) {
2752 				// NOTE: Careful, the + 1 is for termination!
2753 				string = (char*)malloc((stringLength + 1 + 63) / 64 * 64);
2754 				if (string == NULL)
2755 					break;
2756 				stringDeleter.SetTo(string);
2757 			}
2758 			if (glyphCount > kMaxStackStringSize) {
2759 				locations = (BPoint*)malloc(
2760 					((glyphCount * sizeof(BPoint)) + 63) / 64 * 64);
2761 				if (locations == NULL)
2762 					break;
2763 				locationsDeleter.SetTo(locations);
2764 			}
2765 
2766 			if (link.Read(string, stringLength) != B_OK)
2767 				break;
2768 			// Count UTF8 glyphs and make sure we have enough locations
2769 			if ((int32)UTF8CountChars(string, stringLength) > glyphCount)
2770 				break;
2771 			if (link.Read(locations, glyphCount * sizeof(BPoint)) != B_OK)
2772 				break;
2773 			// Terminate the string, if nothing else, it's important
2774 			// for the DTRACE call below...
2775 			string[stringLength] = '\0';
2776 
2777 			DTRACE(("ServerWindow %s: Message AS_DRAW_STRING_WITH_OFFSETS, View: %s "
2778 				"-> %s\n", Title(), fCurrentView->Name(), string));
2779 
2780 			for (int32 i = 0; i < stringLength; i++)
2781 				fCurrentView->ConvertToScreenForDrawing(&locations[i]);
2782 
2783 			BPoint penLocation = drawingEngine->DrawString(string,
2784 				stringLength, locations);
2785 
2786 			fCurrentView->ConvertFromScreenForDrawing(&penLocation);
2787 			fCurrentView->CurrentState()->SetPenLocation(penLocation);
2788 
2789 			break;
2790 		}
2791 
2792 		case AS_VIEW_DRAW_PICTURE:
2793 		{
2794 			int32 token;
2795 			link.Read<int32>(&token);
2796 
2797 			BPoint where;
2798 			if (link.Read<BPoint>(&where) == B_OK) {
2799 				ServerPicture* picture = App()->GetPicture(token);
2800 				if (picture != NULL) {
2801 					// Setting the drawing origin outside of the
2802 					// state makes sure that everything the picture
2803 					// does is relative to the global picture offset.
2804 					fCurrentView->PushState();
2805 					fCurrentView->SetDrawingOrigin(where);
2806 
2807 					fCurrentView->PushState();
2808 					picture->Play(fCurrentView);
2809 					fCurrentView->PopState();
2810 
2811 					fCurrentView->PopState();
2812 
2813 					picture->ReleaseReference();
2814 				}
2815 			}
2816 			break;
2817 		}
2818 
2819 		default:
2820 			BString codeString;
2821 			string_for_message_code(code, codeString);
2822 			debug_printf("ServerWindow %s received unexpected code: %s\n",
2823 				Title(), codeString.String());
2824 
2825 			if (link.NeedsReply()) {
2826 				// the client is now blocking and waiting for a reply!
2827 				fLink.StartMessage(B_ERROR);
2828 				fLink.Flush();
2829 			}
2830 			break;
2831 	}
2832 
2833 	drawingEngine->UnlockParallelAccess();
2834 }
2835 
2836 
2837 bool
2838 ServerWindow::_DispatchPictureMessage(int32 code, BPrivate::LinkReceiver& link)
2839 {
2840 	ServerPicture* picture = fCurrentView->Picture();
2841 	if (picture == NULL)
2842 		return false;
2843 
2844 	switch (code) {
2845 		case AS_VIEW_SET_ORIGIN:
2846 		{
2847 			float x, y;
2848 			link.Read<float>(&x);
2849 			link.Read<float>(&y);
2850 
2851 			picture->WriteSetOrigin(BPoint(x, y));
2852 			break;
2853 		}
2854 
2855 		case AS_VIEW_INVERT_RECT:
2856 		{
2857 			BRect rect;
2858 			link.Read<BRect>(&rect);
2859 			picture->WriteInvertRect(rect);
2860 			break;
2861 		}
2862 
2863 		case AS_VIEW_PUSH_STATE:
2864 		{
2865 			picture->WritePushState();
2866 			break;
2867 		}
2868 
2869 		case AS_VIEW_POP_STATE:
2870 		{
2871 			picture->WritePopState();
2872 			break;
2873 		}
2874 
2875 		case AS_VIEW_SET_DRAWING_MODE:
2876 		{
2877 			int8 drawingMode;
2878 			link.Read<int8>(&drawingMode);
2879 
2880 			picture->WriteSetDrawingMode((drawing_mode)drawingMode);
2881 
2882 			fCurrentView->CurrentState()->SetDrawingMode(
2883 				(drawing_mode)drawingMode);
2884 			fWindow->GetDrawingEngine()->SetDrawingMode(
2885 				(drawing_mode)drawingMode);
2886 			break;
2887 		}
2888 
2889 		case AS_VIEW_SET_PEN_LOC:
2890 		{
2891 			BPoint location;
2892 			link.Read<BPoint>(&location);
2893 			picture->WriteSetPenLocation(location);
2894 
2895 			fCurrentView->CurrentState()->SetPenLocation(location);
2896 			break;
2897 		}
2898 		case AS_VIEW_SET_PEN_SIZE:
2899 		{
2900 			float penSize;
2901 			link.Read<float>(&penSize);
2902 			picture->WriteSetPenSize(penSize);
2903 
2904 			fCurrentView->CurrentState()->SetPenSize(penSize);
2905 			fWindow->GetDrawingEngine()->SetPenSize(
2906 				fCurrentView->CurrentState()->PenSize());
2907 			break;
2908 		}
2909 
2910 		case AS_VIEW_SET_LINE_MODE:
2911 		{
2912 
2913 			ViewSetLineModeInfo info;
2914 			link.Read<ViewSetLineModeInfo>(&info);
2915 
2916 			picture->WriteSetLineMode(info.lineCap, info.lineJoin,
2917 				info.miterLimit);
2918 
2919 			fCurrentView->CurrentState()->SetLineCapMode(info.lineCap);
2920 			fCurrentView->CurrentState()->SetLineJoinMode(info.lineJoin);
2921 			fCurrentView->CurrentState()->SetMiterLimit(info.miterLimit);
2922 
2923 			fWindow->GetDrawingEngine()->SetStrokeMode(info.lineCap,
2924 				info.lineJoin, info.miterLimit);
2925 			break;
2926 		}
2927 		case AS_VIEW_SET_SCALE:
2928 		{
2929 			float scale;
2930 			link.Read<float>(&scale);
2931 			picture->WriteSetScale(scale);
2932 
2933 			fCurrentView->SetScale(scale);
2934 			_UpdateDrawState(fCurrentView);
2935 			break;
2936 		}
2937 
2938 		case AS_VIEW_SET_PATTERN:
2939 		{
2940 			pattern pat;
2941 			link.Read(&pat, sizeof(pattern));
2942 			picture->WriteSetPattern(pat);
2943 			break;
2944 		}
2945 
2946 		case AS_VIEW_SET_FONT_STATE:
2947 		{
2948 			picture->SetFontFromLink(link);
2949 			break;
2950 		}
2951 
2952 		case AS_FILL_RECT:
2953 		case AS_STROKE_RECT:
2954 		{
2955 			BRect rect;
2956 			link.Read<BRect>(&rect);
2957 
2958 			picture->WriteDrawRect(rect, code == AS_FILL_RECT);
2959 			break;
2960 		}
2961 
2962 		case AS_FILL_REGION:
2963 		{
2964 			// There is no B_PIC_FILL_REGION op, we have to
2965 			// implement it using B_PIC_FILL_RECT
2966 			BRegion region;
2967 			if (link.ReadRegion(&region) < B_OK)
2968 				break;
2969 			for (int32 i = 0; i < region.CountRects(); i++)
2970 				picture->WriteDrawRect(region.RectAt(i), true);
2971 			break;
2972 		}
2973 
2974 		case AS_STROKE_ROUNDRECT:
2975 		case AS_FILL_ROUNDRECT:
2976 		{
2977 			BRect rect;
2978 			link.Read<BRect>(&rect);
2979 
2980 			BPoint radii;
2981 			link.Read<float>(&radii.x);
2982 			link.Read<float>(&radii.y);
2983 
2984 			picture->WriteDrawRoundRect(rect, radii, code == AS_FILL_ROUNDRECT);
2985 			break;
2986 		}
2987 
2988 		case AS_STROKE_ELLIPSE:
2989 		case AS_FILL_ELLIPSE:
2990 		{
2991 			BRect rect;
2992 			link.Read<BRect>(&rect);
2993 			picture->WriteDrawEllipse(rect, code == AS_FILL_ELLIPSE);
2994 			break;
2995 		}
2996 
2997 		case AS_STROKE_ARC:
2998 		case AS_FILL_ARC:
2999 		{
3000 			BRect rect;
3001 			link.Read<BRect>(&rect);
3002 			float startTheta, arcTheta;
3003 			link.Read<float>(&startTheta);
3004 			link.Read<float>(&arcTheta);
3005 
3006 			BPoint radii((rect.Width() + 1) / 2, (rect.Height() + 1) / 2);
3007 			BPoint center = rect.LeftTop() + radii;
3008 
3009 			picture->WriteDrawArc(center, radii, startTheta, arcTheta,
3010 				code == AS_FILL_ARC);
3011 			break;
3012 		}
3013 
3014 		case AS_STROKE_TRIANGLE:
3015 		case AS_FILL_TRIANGLE:
3016 		{
3017 			// There is no B_PIC_FILL/STROKE_TRIANGLE op,
3018 			// we implement it using B_PIC_FILL/STROKE_POLYGON
3019 			BPoint points[3];
3020 
3021 			for (int32 i = 0; i < 3; i++) {
3022 				link.Read<BPoint>(&(points[i]));
3023 			}
3024 
3025 			BRect rect;
3026 			link.Read<BRect>(&rect);
3027 
3028 			picture->WriteDrawPolygon(3, points,
3029 					true, code == AS_FILL_TRIANGLE);
3030 			break;
3031 		}
3032 		case AS_STROKE_POLYGON:
3033 		case AS_FILL_POLYGON:
3034 		{
3035 			BRect polyFrame;
3036 			bool isClosed = true;
3037 			int32 pointCount;
3038 			const bool fill = (code == AS_FILL_POLYGON);
3039 
3040 			link.Read<BRect>(&polyFrame);
3041 			if (code == AS_STROKE_POLYGON)
3042 				link.Read<bool>(&isClosed);
3043 			link.Read<int32>(&pointCount);
3044 
3045 			BPoint* pointList = new(nothrow) BPoint[pointCount];
3046 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK) {
3047 				picture->WriteDrawPolygon(pointCount, pointList,
3048 					isClosed && pointCount > 2, fill);
3049 			}
3050 			delete[] pointList;
3051 			break;
3052 		}
3053 
3054 		case AS_STROKE_BEZIER:
3055 		case AS_FILL_BEZIER:
3056 		{
3057 			BPoint points[4];
3058 			for (int32 i = 0; i < 4; i++) {
3059 				link.Read<BPoint>(&(points[i]));
3060 			}
3061 			picture->WriteDrawBezier(points, code == AS_FILL_BEZIER);
3062 			break;
3063 		}
3064 
3065 		case AS_STROKE_LINE:
3066 		{
3067 			ViewStrokeLineInfo info;
3068 			link.Read<ViewStrokeLineInfo>(&info);
3069 
3070 			picture->WriteStrokeLine(info.startPoint, info.endPoint);
3071 			break;
3072 		}
3073 
3074 		case AS_STROKE_LINEARRAY:
3075 		{
3076 			int32 lineCount;
3077 			if (link.Read<int32>(&lineCount) != B_OK || lineCount <= 0)
3078 				break;
3079 
3080 			// To speed things up, try to use a stack allocation and only
3081 			// fall back to the heap if there are enough lines...
3082 			ViewLineArrayInfo* lineData;
3083 			const int32 kStackBufferLineDataCount = 64;
3084 			ViewLineArrayInfo lineDataStackBuffer[kStackBufferLineDataCount];
3085 			if (lineCount > kStackBufferLineDataCount) {
3086 				lineData = new(std::nothrow) ViewLineArrayInfo[lineCount];
3087 				if (lineData == NULL)
3088 					break;
3089 			} else
3090 				lineData = lineDataStackBuffer;
3091 
3092 			// Read them all in one go
3093 			size_t dataSize = lineCount * sizeof(ViewLineArrayInfo);
3094 			if (link.Read(lineData, dataSize) != B_OK) {
3095 				if (lineData != lineDataStackBuffer)
3096 					delete[] lineData;
3097 				break;
3098 			}
3099 
3100 			picture->WritePushState();
3101 
3102 			for (int32 i = 0; i < lineCount; i++) {
3103 				picture->WriteSetHighColor(lineData[i].color);
3104 				picture->WriteStrokeLine(lineData[i].startPoint,
3105 					lineData[i].endPoint);
3106 			}
3107 
3108 			picture->WritePopState();
3109 
3110 			if (lineData != lineDataStackBuffer)
3111 				delete[] lineData;
3112 			break;
3113 		}
3114 
3115 		case AS_VIEW_SET_LOW_COLOR:
3116 		case AS_VIEW_SET_HIGH_COLOR:
3117 		{
3118 			rgb_color color;
3119 			link.Read(&color, sizeof(rgb_color));
3120 
3121 			if (code == AS_VIEW_SET_HIGH_COLOR) {
3122 				picture->WriteSetHighColor(color);
3123 				fCurrentView->CurrentState()->SetHighColor(color);
3124 				fWindow->GetDrawingEngine()->SetHighColor(color);
3125 			} else {
3126 				picture->WriteSetLowColor(color);
3127 				fCurrentView->CurrentState()->SetLowColor(color);
3128 				fWindow->GetDrawingEngine()->SetLowColor(color);
3129 			}
3130 		}	break;
3131 
3132 		case AS_DRAW_STRING:
3133 		case AS_DRAW_STRING_WITH_DELTA:
3134 		{
3135 			ViewDrawStringInfo info;
3136 			if (link.Read<ViewDrawStringInfo>(&info) != B_OK)
3137 				break;
3138 
3139 			char* string = (char*)malloc(info.stringLength + 1);
3140 			if (string == NULL)
3141 				break;
3142 
3143 			if (code != AS_DRAW_STRING_WITH_DELTA) {
3144 				// In this case, info.delta will NOT contain valid values.
3145 				info.delta = (escapement_delta){ 0, 0 };
3146 			}
3147 
3148 			if (link.Read(string, info.stringLength) != B_OK) {
3149 				free(string);
3150 				break;
3151 			}
3152 			// Terminate the string
3153 			string[info.stringLength] = '\0';
3154 
3155 			picture->WriteDrawString(info.location, string, info.stringLength,
3156 				info.delta);
3157 
3158 			free(string);
3159 			break;
3160 		}
3161 
3162 		case AS_STROKE_SHAPE:
3163 		case AS_FILL_SHAPE:
3164 		{
3165 			BRect shapeFrame;
3166 			int32 opCount;
3167 			int32 ptCount;
3168 
3169 			link.Read<BRect>(&shapeFrame);
3170 			link.Read<int32>(&opCount);
3171 			link.Read<int32>(&ptCount);
3172 
3173 			uint32* opList = new(std::nothrow) uint32[opCount];
3174 			BPoint* ptList = new(std::nothrow) BPoint[ptCount];
3175 			if (opList != NULL && ptList != NULL
3176 				&& link.Read(opList, opCount * sizeof(uint32)) >= B_OK
3177 				&& link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK) {
3178 				// This might seem a bit weird, but under BeOS, the shapes
3179 				// are always offset by the current pen location
3180 				BPoint penLocation
3181 					= fCurrentView->CurrentState()->PenLocation();
3182 				for (int32 i = 0; i < ptCount; i++) {
3183 					ptList[i] += penLocation;
3184 				}
3185 				const bool fill = (code == AS_FILL_SHAPE);
3186 				picture->WriteDrawShape(opCount, opList, ptCount, ptList, fill);
3187 			}
3188 
3189 			delete[] opList;
3190 			delete[] ptList;
3191 			break;
3192 		}
3193 
3194 		case AS_VIEW_DRAW_BITMAP:
3195 		{
3196 			ViewDrawBitmapInfo info;
3197 			link.Read<ViewDrawBitmapInfo>(&info);
3198 
3199 			ServerBitmap* bitmap = App()->GetBitmap(info.bitmapToken);
3200 			if (bitmap == NULL)
3201 				break;
3202 
3203 			picture->WriteDrawBitmap(info.bitmapRect, info.viewRect,
3204 				bitmap->Width(), bitmap->Height(), bitmap->BytesPerRow(),
3205 				bitmap->ColorSpace(), info.options, bitmap->Bits(),
3206 				bitmap->BitsLength());
3207 
3208 			bitmap->ReleaseReference();
3209 			break;
3210 		}
3211 
3212 		case AS_VIEW_DRAW_PICTURE:
3213 		{
3214 			int32 token;
3215 			link.Read<int32>(&token);
3216 
3217 			BPoint where;
3218 			if (link.Read<BPoint>(&where) == B_OK) {
3219 				ServerPicture* pictureToDraw = App()->GetPicture(token);
3220 				if (pictureToDraw != NULL) {
3221 					// We need to make a copy of the picture, since it can
3222 					// change after it has been drawn
3223 					ServerPicture* copy = App()->CreatePicture(pictureToDraw);
3224 					picture->NestPicture(copy);
3225 					picture->WriteDrawPicture(where, copy->Token());
3226 
3227 					pictureToDraw->ReleaseReference();
3228 				}
3229 			}
3230 			break;
3231 		}
3232 
3233 		case AS_VIEW_SET_CLIP_REGION:
3234 		{
3235 			int32 rectCount;
3236 			status_t status = link.Read<int32>(&rectCount);
3237 				// a negative count means no
3238 				// region for the current draw state,
3239 				// but an *empty* region is actually valid!
3240 				// even if it means no drawing is allowed
3241 
3242 			if (status < B_OK)
3243 				break;
3244 
3245 			if (rectCount >= 0) {
3246 				// we are supposed to set the clipping region
3247 				BRegion region;
3248 				if (rectCount > 0 && link.ReadRegion(&region) < B_OK)
3249 					break;
3250 				picture->WriteSetClipping(region);
3251 			} else {
3252 				// we are supposed to clear the clipping region
3253 				picture->WriteClearClipping();
3254 			}
3255 			break;
3256 		}
3257 
3258 		case AS_VIEW_BEGIN_PICTURE:
3259 		{
3260 			ServerPicture* newPicture = App()->CreatePicture();
3261 			if (newPicture != NULL) {
3262 				newPicture->PushPicture(picture);
3263 				newPicture->SyncState(fCurrentView);
3264 				fCurrentView->SetPicture(newPicture);
3265 			}
3266 			break;
3267 		}
3268 
3269 		case AS_VIEW_APPEND_TO_PICTURE:
3270 		{
3271 			int32 token;
3272 			link.Read<int32>(&token);
3273 
3274 			ServerPicture* appendPicture = App()->GetPicture(token);
3275 			if (appendPicture != NULL) {
3276 				//picture->SyncState(fCurrentView);
3277 				appendPicture->AppendPicture(picture);
3278 			}
3279 
3280 			fCurrentView->SetPicture(appendPicture);
3281 
3282 			if (appendPicture != NULL)
3283 				appendPicture->ReleaseReference();
3284 			break;
3285 		}
3286 
3287 		case AS_VIEW_END_PICTURE:
3288 		{
3289 			ServerPicture* poppedPicture = picture->PopPicture();
3290 			fCurrentView->SetPicture(poppedPicture);
3291 			if (poppedPicture != NULL)
3292 				poppedPicture->ReleaseReference();
3293 
3294 			fLink.StartMessage(B_OK);
3295 			fLink.Attach<int32>(picture->Token());
3296 			fLink.Flush();
3297 			return true;
3298 		}
3299 /*
3300 		case AS_VIEW_SET_BLENDING_MODE:
3301 		{
3302 			ViewBlendingModeInfo info;
3303 			link.Read<ViewBlendingModeInfo>(&info);
3304 
3305 			picture->BeginOp(B_PIC_SET_BLENDING_MODE);
3306 			picture->AddInt16((int16)info.sourceAlpha);
3307 			picture->AddInt16((int16)info.alphaFunction);
3308 			picture->EndOp();
3309 
3310 			fCurrentView->CurrentState()->SetBlendingMode(info.sourceAlpha,
3311 				info.alphaFunction);
3312 			fWindow->GetDrawingEngine()->SetBlendingMode(info.sourceAlpha,
3313 				info.alphaFunction);
3314 			break;
3315 		}*/
3316 		default:
3317 			return false;
3318 	}
3319 
3320 	if (link.NeedsReply()) {
3321 		fLink.StartMessage(B_ERROR);
3322 		fLink.Flush();
3323 	}
3324 	return true;
3325 }
3326 
3327 
3328 /*!	\brief Message-dispatching loop for the ServerWindow
3329 
3330 	Watches the ServerWindow's message port and dispatches as necessary
3331 */
3332 void
3333 ServerWindow::_MessageLooper()
3334 {
3335 	// Send a reply to our window - it is expecting fMessagePort
3336 	// port and some other info.
3337 
3338 	fLink.StartMessage(B_OK);
3339 	fLink.Attach<port_id>(fMessagePort);
3340 
3341 	int32 minWidth, maxWidth, minHeight, maxHeight;
3342 	fWindow->GetSizeLimits(&minWidth, &maxWidth, &minHeight, &maxHeight);
3343 
3344 	fLink.Attach<BRect>(fWindow->Frame());
3345 	fLink.Attach<float>((float)minWidth);
3346 	fLink.Attach<float>((float)maxWidth);
3347 	fLink.Attach<float>((float)minHeight);
3348 	fLink.Attach<float>((float)maxHeight);
3349 	fLink.Flush();
3350 
3351 	BPrivate::LinkReceiver& receiver = fLink.Receiver();
3352 	bool quitLoop = false;
3353 
3354 	while (!quitLoop) {
3355 		//STRACE(("info: ServerWindow::MonitorWin listening on port %ld.\n",
3356 		//	fMessagePort));
3357 
3358 		int32 code;
3359 		status_t status = receiver.GetNextMessage(code);
3360 		if (status != B_OK) {
3361 			// that shouldn't happen, it's our port
3362 			printf("Someone deleted our message port!\n");
3363 
3364 			// try to let our client die happily
3365 			NotifyQuitRequested();
3366 			break;
3367 		}
3368 
3369 #ifdef PROFILE_MESSAGE_LOOP
3370 		bigtime_t start = system_time();
3371 #endif
3372 
3373 		Lock();
3374 
3375 #ifdef PROFILE_MESSAGE_LOOP
3376 		bigtime_t diff = system_time() - start;
3377 		if (diff > 10000) {
3378 			printf("ServerWindow %s: lock acquisition took %Ld usecs\n",
3379 				Title(), diff);
3380 		}
3381 #endif
3382 
3383 		int32 messagesProcessed = 0;
3384 		bigtime_t processingStart = system_time();
3385 		bool lockedDesktopSingleWindow = false;
3386 
3387 		while (true) {
3388 			if (code == AS_DELETE_WINDOW || code == kMsgQuitLooper) {
3389 				// this means the client has been killed
3390 				DTRACE(("ServerWindow %s received 'AS_DELETE_WINDOW' message "
3391 					"code\n", Title()));
3392 
3393 				if (code == AS_DELETE_WINDOW) {
3394 					fLink.StartMessage(B_OK);
3395 					fLink.Flush();
3396 				}
3397 
3398 				if (lockedDesktopSingleWindow)
3399 					fDesktop->UnlockSingleWindow();
3400 
3401 				quitLoop = true;
3402 
3403 				// ServerWindow's destructor takes care of pulling this object
3404 				// off the desktop.
3405 				ASSERT(fWindow->IsHidden());
3406 				break;
3407 			}
3408 
3409 			// Acquire the appropriate lock
3410 			bool needsAllWindowsLocked = _MessageNeedsAllWindowsLocked(code);
3411 			if (needsAllWindowsLocked) {
3412 				// We may already still hold the read-lock from the previous
3413 				// inner-loop iteration.
3414 				if (lockedDesktopSingleWindow) {
3415 					fDesktop->UnlockSingleWindow();
3416 					lockedDesktopSingleWindow = false;
3417 				}
3418 				fDesktop->LockAllWindows();
3419 			} else {
3420 				// We never keep the write-lock across inner-loop iterations,
3421 				// so there is nothing else to do besides read-locking unless
3422 				// we already have the read-lock from the previous iteration.
3423 				if (!lockedDesktopSingleWindow) {
3424 					fDesktop->LockSingleWindow();
3425 					lockedDesktopSingleWindow = true;
3426 				}
3427 			}
3428 
3429 			if (atomic_and(&fRedrawRequested, 0) != 0) {
3430 #ifdef PROFILE_MESSAGE_LOOP
3431 				bigtime_t redrawStart = system_time();
3432 #endif
3433 				fWindow->RedrawDirtyRegion();
3434 #ifdef PROFILE_MESSAGE_LOOP
3435 				diff = system_time() - redrawStart;
3436 				atomic_add(&sRedrawProcessingTime.count, 1);
3437 # ifndef HAIKU_TARGET_PLATFORM_LIBBE_TEST
3438 				atomic_add64(&sRedrawProcessingTime.time, diff);
3439 # else
3440 				sRedrawProcessingTime.time += diff;
3441 # endif
3442 #endif
3443 			}
3444 
3445 #ifdef PROFILE_MESSAGE_LOOP
3446 			bigtime_t dispatchStart = system_time();
3447 #endif
3448 			_DispatchMessage(code, receiver);
3449 
3450 #ifdef PROFILE_MESSAGE_LOOP
3451 			if (code >= 0 && code < AS_LAST_CODE) {
3452 				diff = system_time() - dispatchStart;
3453 				atomic_add(&sMessageProfile[code].count, 1);
3454 #ifndef HAIKU_TARGET_PLATFORM_LIBBE_TEST
3455 				atomic_add64(&sMessageProfile[code].time, diff);
3456 #else
3457 				sMessageProfile[code].time += diff;
3458 #endif
3459 				if (diff > 10000) {
3460 					printf("ServerWindow %s: message %ld took %Ld usecs\n",
3461 						Title(), code, diff);
3462 				}
3463 			}
3464 #endif
3465 
3466 			if (needsAllWindowsLocked)
3467 				fDesktop->UnlockAllWindows();
3468 
3469 			// Only process up to 70 waiting messages at once (we have the
3470 			// Desktop locked), but don't hold the lock longer than 10 ms
3471 			if (!receiver.HasMessages() || ++messagesProcessed > 70
3472 				|| system_time() - processingStart > 10000) {
3473 				if (lockedDesktopSingleWindow)
3474 					fDesktop->UnlockSingleWindow();
3475 				break;
3476 			}
3477 
3478 			// next message
3479 			status_t status = receiver.GetNextMessage(code);
3480 			if (status != B_OK) {
3481 				// that shouldn't happen, it's our port
3482 				printf("Someone deleted our message port!\n");
3483 				if (lockedDesktopSingleWindow)
3484 					fDesktop->UnlockSingleWindow();
3485 
3486 				// try to let our client die happily
3487 				NotifyQuitRequested();
3488 				break;
3489 			}
3490 		}
3491 
3492 		Unlock();
3493 	}
3494 
3495 	// We were asked to quit the message loop - either on request or because of
3496 	// an error.
3497 	Quit();
3498 		// does not return
3499 }
3500 
3501 
3502 void
3503 ServerWindow::ScreenChanged(const BMessage* message)
3504 {
3505 	SendMessageToClient(message);
3506 
3507 	if (fDirectWindowInfo != NULL && fDirectWindowInfo->IsFullScreen())
3508 		_ResizeToFullScreen();
3509 }
3510 
3511 
3512 status_t
3513 ServerWindow::SendMessageToClient(const BMessage* msg, int32 target) const
3514 {
3515 	if (target == B_NULL_TOKEN)
3516 		target = fClientToken;
3517 
3518 	BMessenger reply;
3519 	BMessage::Private messagePrivate((BMessage*)msg);
3520 	return messagePrivate.SendMessage(fClientLooperPort, fClientTeam, target,
3521 		0, false, reply);
3522 }
3523 
3524 
3525 Window*
3526 ServerWindow::MakeWindow(BRect frame, const char* name,
3527 	window_look look, window_feel feel, uint32 flags, uint32 workspace)
3528 {
3529 	// The non-offscreen ServerWindow uses the DrawingEngine instance from
3530 	// the desktop.
3531 	return new(std::nothrow) ::Window(frame, name, look, feel, flags,
3532 		workspace, this, fDesktop->HWInterface()->CreateDrawingEngine());
3533 }
3534 
3535 
3536 void
3537 ServerWindow::HandleDirectConnection(int32 bufferState, int32 driverState)
3538 {
3539 	ASSERT_MULTI_LOCKED(fDesktop->WindowLocker());
3540 
3541 	if (fDirectWindowInfo == NULL)
3542 		return;
3543 
3544 	STRACE(("HandleDirectConnection(bufferState = %ld, driverState = %ld)\n",
3545 		bufferState, driverState));
3546 
3547 	status_t status = fDirectWindowInfo->SetState(
3548 		(direct_buffer_state)bufferState, (direct_driver_state)driverState,
3549 		fDesktop->HWInterface()->FrontBuffer(), fWindow->Frame(),
3550 		fWindow->VisibleContentRegion());
3551 
3552 	if (status != B_OK) {
3553 		char errorString[256];
3554 		snprintf(errorString, sizeof(errorString),
3555 			"%s killed for a problem in DirectConnected(): %s",
3556 			App()->Signature(), strerror(status));
3557 		syslog(LOG_ERR, errorString);
3558 
3559 		// The client application didn't release the semaphore
3560 		// within the given timeout. Or something else went wrong.
3561 		// Deleting this member should make it crash.
3562 		delete fDirectWindowInfo;
3563 		fDirectWindowInfo = NULL;
3564 	} else if ((bufferState & B_DIRECT_MODE_MASK) == B_DIRECT_START)
3565 		fIsDirectlyAccessing = true;
3566 	else if ((bufferState & B_DIRECT_MODE_MASK) == B_DIRECT_STOP)
3567 		fIsDirectlyAccessing = false;
3568 }
3569 
3570 
3571 void
3572 ServerWindow::_SetCurrentView(View* view)
3573 {
3574 	if (fCurrentView == view)
3575 		return;
3576 
3577 	fCurrentView = view;
3578 	fCurrentDrawingRegionValid = false;
3579 	_UpdateDrawState(fCurrentView);
3580 
3581 #if 0
3582 #if DELAYED_BACKGROUND_CLEARING
3583 	if (fCurrentView && fCurrentView->IsBackgroundDirty()
3584 		&& fWindow->InUpdate()) {
3585 		DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
3586 		if (drawingEngine->LockParallelAccess()) {
3587 			fWindow->GetEffectiveDrawingRegion(fCurrentView,
3588 				fCurrentDrawingRegion);
3589 			fCurrentDrawingRegionValid = true;
3590 			BRegion dirty(fCurrentDrawingRegion);
3591 
3592 			BRegion content;
3593 			fWindow->GetContentRegion(&content);
3594 
3595 			fCurrentView->Draw(drawingEngine, &dirty, &content, false);
3596 
3597 			drawingEngine->UnlockParallelAccess();
3598 		}
3599 	}
3600 #endif
3601 #endif // 0
3602 }
3603 
3604 
3605 void
3606 ServerWindow::_UpdateDrawState(View* view)
3607 {
3608 	// switch the drawing state
3609 	// TODO: is it possible to scroll a view while it
3610 	// is being drawn? probably not... otherwise the
3611 	// "offsets" passed below would need to be updated again
3612 	DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
3613 	if (view && drawingEngine) {
3614 		BPoint leftTop(0, 0);
3615 		view->ConvertToScreenForDrawing(&leftTop);
3616 		drawingEngine->SetDrawState(view->CurrentState(), leftTop.x, leftTop.y);
3617 	}
3618 }
3619 
3620 
3621 void
3622 ServerWindow::_UpdateCurrentDrawingRegion()
3623 {
3624 	if (!fCurrentDrawingRegionValid
3625 		|| fWindow->DrawingRegionChanged(fCurrentView)) {
3626 		fWindow->GetEffectiveDrawingRegion(fCurrentView, fCurrentDrawingRegion);
3627 		fCurrentDrawingRegionValid = true;
3628 	}
3629 }
3630 
3631 
3632 bool
3633 ServerWindow::_MessageNeedsAllWindowsLocked(uint32 code) const
3634 {
3635 	switch (code) {
3636 		case AS_SET_WINDOW_TITLE:
3637 		case AS_ADD_TO_SUBSET:
3638 		case AS_REMOVE_FROM_SUBSET:
3639 		case AS_VIEW_CREATE_ROOT:
3640 		case AS_VIEW_CREATE:
3641 		case AS_SEND_BEHIND:
3642 		case AS_SET_LOOK:
3643 		case AS_SET_FEEL:
3644 		case AS_SET_FLAGS:
3645 		case AS_SET_WORKSPACES:
3646 		case AS_WINDOW_MOVE:
3647 		case AS_WINDOW_RESIZE:
3648 		case AS_SET_SIZE_LIMITS:
3649 		case AS_SYSTEM_FONT_CHANGED:
3650 		case AS_SET_DECORATOR_SETTINGS:
3651 		case AS_GET_MOUSE:
3652 		case AS_DIRECT_WINDOW_SET_FULLSCREEN:
3653 //		case AS_VIEW_SET_EVENT_MASK:
3654 //		case AS_VIEW_SET_MOUSE_EVENT_MASK:
3655 		case AS_TALK_TO_DESKTOP_LISTENER:
3656 			return true;
3657 		default:
3658 			return false;
3659 	}
3660 }
3661 
3662 
3663 void
3664 ServerWindow::_ResizeToFullScreen()
3665 {
3666 	BRect screenFrame;
3667 
3668 	{
3669 		AutoReadLocker _(fDesktop->ScreenLocker());
3670 		const Screen* screen = fWindow->Screen();
3671 		if (screen == NULL)
3672 			return;
3673 
3674 		screenFrame = fWindow->Screen()->Frame();
3675 	}
3676 
3677 	fDesktop->MoveWindowBy(fWindow,
3678 		screenFrame.left - fWindow->Frame().left,
3679 		screenFrame.top - fWindow->Frame().top);
3680 	fDesktop->ResizeWindowBy(fWindow,
3681 		screenFrame.Width() - fWindow->Frame().Width(),
3682 		screenFrame.Height() - fWindow->Frame().Height());
3683 }
3684 
3685 
3686 status_t
3687 ServerWindow::_EnableDirectWindowMode()
3688 {
3689 	if (fDirectWindowInfo != NULL) {
3690 		// already in direct window mode
3691 		return B_ERROR;
3692 	}
3693 
3694 	if (fDesktop->HWInterface()->FrontBuffer() == NULL) {
3695 		// direct window mode not supported
3696 		return B_UNSUPPORTED;
3697 	}
3698 
3699 	fDirectWindowInfo = new(std::nothrow) DirectWindowInfo;
3700 	if (fDirectWindowInfo == NULL)
3701 		return B_NO_MEMORY;
3702 
3703 	status_t status = fDirectWindowInfo->InitCheck();
3704 	if (status != B_OK) {
3705 		delete fDirectWindowInfo;
3706 		fDirectWindowInfo = NULL;
3707 
3708 		return status;
3709 	}
3710 
3711 	return B_OK;
3712 }
3713 
3714 
3715 void
3716 ServerWindow::_DirectWindowSetFullScreen(bool enable)
3717 {
3718 	window_feel feel = kWindowScreenFeel;
3719 
3720 	if (enable) {
3721 		fDesktop->HWInterface()->SetCursorVisible(false);
3722 
3723 		fDirectWindowInfo->EnableFullScreen(fWindow->Frame(), fWindow->Feel());
3724 		_ResizeToFullScreen();
3725 	} else {
3726 		const BRect& originalFrame = fDirectWindowInfo->OriginalFrame();
3727 
3728 		fDirectWindowInfo->DisableFullScreen();
3729 
3730 		// Resize window back to its original size
3731 		fDesktop->MoveWindowBy(fWindow,
3732 			originalFrame.left - fWindow->Frame().left,
3733 			originalFrame.top - fWindow->Frame().top);
3734 		fDesktop->ResizeWindowBy(fWindow,
3735 			originalFrame.Width() - fWindow->Frame().Width(),
3736 			originalFrame.Height() - fWindow->Frame().Height());
3737 
3738 		fDesktop->HWInterface()->SetCursorVisible(true);
3739 	}
3740 
3741 	fDesktop->SetWindowFeel(fWindow, feel);
3742 }
3743 
3744 
3745 status_t
3746 ServerWindow::PictureToRegion(ServerPicture* picture, BRegion& region,
3747 	bool inverse, BPoint where)
3748 {
3749 	fprintf(stderr, "ServerWindow::PictureToRegion() not implemented\n");
3750 	region.MakeEmpty();
3751 	return B_ERROR;
3752 }
3753