xref: /haiku/src/servers/app/ServerWindow.cpp (revision 1345706a9ff6ad0dc041339a02d4259998b0765d)
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 			break;
965 		}
966 
967 		case AS_SET_DECORATOR_SETTINGS:
968 		{
969 			// Has the all-window look
970 			DTRACE(("ServerWindow %s: Message AS_SET_DECORATOR_SETTINGS\n",
971 				Title()));
972 
973 			int32 size;
974 			if (fWindow && link.Read<int32>(&size) == B_OK) {
975 				char buffer[size];
976 				if (link.Read(buffer, size) == B_OK) {
977 					BMessage settings;
978 					if (settings.Unflatten(buffer) == B_OK)
979 						fDesktop->SetWindowDecoratorSettings(fWindow, settings);
980 				}
981 			}
982 			break;
983 		}
984 
985 		case AS_GET_DECORATOR_SETTINGS:
986 		{
987 			DTRACE(("ServerWindow %s: Message AS_GET_DECORATOR_SETTINGS\n",
988 				Title()));
989 
990 			bool success = false;
991 
992 			BMessage settings;
993 			if (fWindow->GetDecoratorSettings(&settings)) {
994 				int32 size = settings.FlattenedSize();
995 				char buffer[size];
996 				if (settings.Flatten(buffer, size) == B_OK) {
997 					success = true;
998 					fLink.StartMessage(B_OK);
999 					fLink.Attach<int32>(size);
1000 					fLink.Attach(buffer, size);
1001 				}
1002 			}
1003 
1004 			if (!success)
1005 				fLink.StartMessage(B_ERROR);
1006 
1007 			fLink.Flush();
1008 			break;
1009 		}
1010 
1011 		case AS_SYSTEM_FONT_CHANGED:
1012 		{
1013 			// Has the all-window look
1014 			fDesktop->FontsChanged(fWindow);
1015 			// TODO: tell client about this, too, and relayout...
1016 			break;
1017 		}
1018 
1019 		case AS_REDRAW:
1020 			// Nothing to do here - the redraws are actually handled by looking
1021 			// at the fRedrawRequested member variable in _MessageLooper().
1022 			break;
1023 
1024 		case AS_SYNC:
1025 			DTRACE(("ServerWindow %s: Message AS_SYNC\n", Title()));
1026 			// the synchronisation works by the fact that the client
1027 			// window is waiting for this reply, after having received it,
1028 			// client and server queues are in sync (earlier, the client
1029 			// may have pushed drawing commands at the server and now it
1030 			// knows they have all been carried out)
1031 			fLink.StartMessage(B_OK);
1032 			fLink.Flush();
1033 			break;
1034 
1035 		case AS_BEGIN_UPDATE:
1036 			DTRACE(("ServerWindow %s: Message AS_BEGIN_UPDATE\n", Title()));
1037 			fWindow->BeginUpdate(fLink);
1038 			break;
1039 
1040 		case AS_END_UPDATE:
1041 			DTRACE(("ServerWindow %s: Message AS_END_UPDATE\n", Title()));
1042 			fWindow->EndUpdate();
1043 			break;
1044 
1045 		case AS_GET_MOUSE:
1046 		{
1047 			// Has the all-window look
1048 			DTRACE(("ServerWindow %s: Message AS_GET_MOUSE\n", fTitle));
1049 
1050 			// Returns
1051 			// 1) BPoint mouse location
1052 			// 2) int32 button state
1053 
1054 			BPoint where;
1055 			int32 buttons;
1056 			fDesktop->GetLastMouseState(&where, &buttons);
1057 
1058 			fLink.StartMessage(B_OK);
1059 			fLink.Attach<BPoint>(where);
1060 			fLink.Attach<int32>(buttons);
1061 			fLink.Flush();
1062 			break;
1063 		}
1064 
1065 		// BDirectWindow communication
1066 
1067 		case AS_DIRECT_WINDOW_GET_SYNC_DATA:
1068 		{
1069 			status_t status = _EnableDirectWindowMode();
1070 
1071 			fLink.StartMessage(status);
1072 			if (status == B_OK) {
1073 				struct direct_window_sync_data syncData;
1074 				fDirectWindowInfo->GetSyncData(syncData);
1075 
1076 				fLink.Attach(&syncData, sizeof(syncData));
1077 			}
1078 
1079 			fLink.Flush();
1080 			break;
1081 		}
1082 		case AS_DIRECT_WINDOW_SET_FULLSCREEN:
1083 		{
1084 			// Has the all-window look
1085 			bool enable;
1086 			link.Read<bool>(&enable);
1087 
1088 			status_t status = B_OK;
1089 			if (fDirectWindowInfo != NULL)
1090 				_DirectWindowSetFullScreen(enable);
1091 			else
1092 				status = B_BAD_TYPE;
1093 
1094 			fLink.StartMessage(status);
1095 			fLink.Flush();
1096 			break;
1097 		}
1098 
1099 		// View creation and destruction (don't need a valid fCurrentView)
1100 
1101 		case AS_SET_CURRENT_VIEW:
1102 		{
1103 			int32 token;
1104 			if (link.Read<int32>(&token) != B_OK)
1105 				break;
1106 
1107 			View *current;
1108 			if (App()->ViewTokens().GetToken(token, B_HANDLER_TOKEN,
1109 					(void**)&current) != B_OK
1110 				|| current->Window()->ServerWindow() != this) {
1111 				// TODO: if this happens, we probably want to kill the app and
1112 				// clean up
1113 				debug_printf("ServerWindow %s: Message "
1114 					"\n\n\nAS_SET_CURRENT_VIEW: view not found, token %ld\n",
1115 					fTitle, token);
1116 				current = NULL;
1117 			} else {
1118 				DTRACE(("\n\n\nServerWindow %s: Message AS_SET_CURRENT_VIEW: %s, "
1119 					"token %ld\n", fTitle, current->Name(), token));
1120 				_SetCurrentView(current);
1121 			}
1122 			break;
1123 		}
1124 
1125 		case AS_VIEW_CREATE_ROOT:
1126 		{
1127 			DTRACE(("ServerWindow %s: Message AS_VIEW_CREATE_ROOT\n", fTitle));
1128 
1129 			// Start receiving top_view data -- pass NULL as the parent view.
1130 			// This should be the *only* place where this happens.
1131 			if (fCurrentView != NULL) {
1132 				debug_printf("ServerWindow %s: Message "
1133 					"AS_VIEW_CREATE_ROOT: fCurrentView already set!!\n",
1134 					fTitle);
1135 				break;
1136 			}
1137 
1138 			_SetCurrentView(_CreateView(link, NULL));
1139 			fWindow->SetTopView(fCurrentView);
1140 			break;
1141 		}
1142 
1143 		case AS_VIEW_CREATE:
1144 		{
1145 			DTRACE(("ServerWindow %s: Message AS_VIEW_CREATE: View name: "
1146 				"%s\n", fTitle, fCurrentView->Name()));
1147 
1148 			View* parent = NULL;
1149 			View* newView = _CreateView(link, &parent);
1150 			if (parent != NULL && newView != NULL)
1151 				parent->AddChild(newView);
1152 			else {
1153 				debug_printf("ServerWindow %s: Message AS_VIEW_CREATE: "
1154 					"parent or newView NULL!!\n", fTitle);
1155 			}
1156 			break;
1157 		}
1158 
1159 		default:
1160 			if (fCurrentView == NULL) {
1161 				BString codeName;
1162 				string_for_message_code(code, codeName);
1163 				debug_printf("ServerWindow %s received unexpected code - "
1164 					"message '%s' before top_view attached.\n",
1165 					Title(), codeName.String());
1166 				if (link.NeedsReply()) {
1167 					fLink.StartMessage(B_ERROR);
1168 					fLink.Flush();
1169 				}
1170 				return;
1171 			}
1172 
1173 			_DispatchViewMessage(code, link);
1174 			break;
1175 	}
1176 }
1177 
1178 
1179 /*!
1180 	Dispatches all view messages that need a valid fCurrentView.
1181 */
1182 void
1183 ServerWindow::_DispatchViewMessage(int32 code,
1184 	BPrivate::LinkReceiver &link)
1185 {
1186 	if (_DispatchPictureMessage(code, link))
1187 		return;
1188 
1189 	switch (code) {
1190 		case AS_VIEW_SCROLL:
1191 		{
1192 			float dh;
1193 			float dv;
1194 			link.Read<float>(&dh);
1195 			if (link.Read<float>(&dv) != B_OK)
1196 				break;
1197 
1198 			DTRACE(("ServerWindow %s: Message AS_VIEW_SCROLL: View name: "
1199 				"%s, %.1f x %.1f\n", fTitle, fCurrentView->Name(), dh, dv));
1200 			fWindow->ScrollViewBy(fCurrentView, dh, dv);
1201 			break;
1202 		}
1203 		case AS_VIEW_COPY_BITS:
1204 		{
1205 			BRect src;
1206 			BRect dst;
1207 
1208 			link.Read<BRect>(&src);
1209 			if (link.Read<BRect>(&dst) != B_OK)
1210 				break;
1211 
1212 			DTRACE(("ServerWindow %s: Message AS_VIEW_COPY_BITS: View name: "
1213 				"%s, BRect(%.1f, %.1f, %.1f, %.1f) -> "
1214 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", fTitle,
1215 				fCurrentView->Name(), src.left, src.top, src.right, src.bottom,
1216 				dst.left, dst.top, dst.right, dst.bottom));
1217 
1218 			BRegion contentRegion;
1219 			// TODO: avoid copy operation maybe?
1220 			fWindow->GetContentRegion(&contentRegion);
1221 			fCurrentView->CopyBits(src, dst, contentRegion);
1222 			break;
1223 		}
1224 		case AS_VIEW_DELETE:
1225 		{
1226 			// Received when a view is detached from a window
1227 
1228 			int32 token;
1229 			if (link.Read<int32>(&token) != B_OK)
1230 				break;
1231 
1232 			View *view;
1233 			if (App()->ViewTokens().GetToken(token, B_HANDLER_TOKEN,
1234 					(void**)&view) == B_OK
1235 				&& view->Window()->ServerWindow() == this) {
1236 				View* parent = view->Parent();
1237 
1238 				DTRACE(("ServerWindow %s: AS_VIEW_DELETE view: %p, "
1239 					"parent: %p\n", fTitle, view, parent));
1240 
1241 				if (parent != NULL) {
1242 					parent->RemoveChild(view);
1243 
1244 					if (view->EventMask() != 0) {
1245 						// TODO: possible deadlock (event dispatcher already
1246 						// locked itself, waits for Desktop write lock, but
1247 						// we have it, now we are trying to lock the event
1248 						// dispatcher -> deadlock)
1249 fDesktop->UnlockSingleWindow();
1250 						fDesktop->EventDispatcher().RemoveListener(
1251 							EventTarget(), token);
1252 fDesktop->LockSingleWindow();
1253 					}
1254 					if (fCurrentView == view)
1255 						_SetCurrentView(parent);
1256 					delete view;
1257 				} // else we don't delete the root view
1258 			}
1259 			break;
1260 		}
1261 		case AS_VIEW_SET_STATE:
1262 		{
1263 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_STATE: "
1264 				"View name: %s\n", fTitle, fCurrentView->Name()));
1265 
1266 			fCurrentView->CurrentState()->ReadFromLink(link);
1267 			// TODO: When is this used?!?
1268 			fCurrentView->RebuildClipping(true);
1269 			_UpdateDrawState(fCurrentView);
1270 
1271 			break;
1272 		}
1273 		case AS_VIEW_SET_FONT_STATE:
1274 		{
1275 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_FONT_STATE: "
1276 				"View name: %s\n", fTitle, fCurrentView->Name()));
1277 
1278 			fCurrentView->CurrentState()->ReadFontFromLink(link);
1279 			fWindow->GetDrawingEngine()->SetFont(
1280 				fCurrentView->CurrentState());
1281 			break;
1282 		}
1283 		case AS_VIEW_GET_STATE:
1284 		{
1285 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_STATE: "
1286 				"View name: %s\n", fTitle, fCurrentView->Name()));
1287 
1288 			fLink.StartMessage(B_OK);
1289 
1290 			// attach state data
1291 			fCurrentView->CurrentState()->WriteToLink(fLink.Sender());
1292 			fLink.Flush();
1293 			break;
1294 		}
1295 		case AS_VIEW_SET_EVENT_MASK:
1296 		{
1297 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_EVENT_MASK: "
1298 				"View name: %s\n", fTitle, fCurrentView->Name()));
1299 			uint32 eventMask, options;
1300 
1301 			link.Read<uint32>(&eventMask);
1302 			if (link.Read<uint32>(&options) == B_OK) {
1303 				fCurrentView->SetEventMask(eventMask, options);
1304 
1305 fDesktop->UnlockSingleWindow();
1306 				// TODO: possible deadlock!
1307 				if (eventMask != 0 || options != 0) {
1308 					fDesktop->EventDispatcher().AddListener(EventTarget(),
1309 						fCurrentView->Token(), eventMask, options);
1310 				} else {
1311 					fDesktop->EventDispatcher().RemoveListener(EventTarget(),
1312 						fCurrentView->Token());
1313 				}
1314 fDesktop->LockSingleWindow();
1315 			}
1316 			break;
1317 		}
1318 		case AS_VIEW_SET_MOUSE_EVENT_MASK:
1319 		{
1320 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_MOUSE_EVENT_MASK: "
1321 				"View name: %s\n", fTitle, fCurrentView->Name()));
1322 			uint32 eventMask, options;
1323 
1324 			link.Read<uint32>(&eventMask);
1325 			if (link.Read<uint32>(&options) == B_OK) {
1326 fDesktop->UnlockSingleWindow();
1327 				// TODO: possible deadlock
1328 				if (eventMask != 0 || options != 0) {
1329 					if (options & B_LOCK_WINDOW_FOCUS)
1330 						fDesktop->SetFocusLocked(fWindow);
1331 					fDesktop->EventDispatcher().AddTemporaryListener(EventTarget(),
1332 						fCurrentView->Token(), eventMask, options);
1333 				} else {
1334 					fDesktop->EventDispatcher().RemoveTemporaryListener(EventTarget(),
1335 						fCurrentView->Token());
1336 				}
1337 fDesktop->LockSingleWindow();
1338 			}
1339 
1340 			// TODO: support B_LOCK_WINDOW_FOCUS option in Desktop
1341 			break;
1342 		}
1343 		case AS_VIEW_MOVE_TO:
1344 		{
1345 			float x, y;
1346 			link.Read<float>(&x);
1347 			if (link.Read<float>(&y) != B_OK)
1348 				break;
1349 
1350 			DTRACE(("ServerWindow %s: Message AS_VIEW_MOVE_TO: View name: "
1351 				"%s, x: %.1f, y: %.1f\n", fTitle, fCurrentView->Name(), x, y));
1352 
1353 			float offsetX = x - fCurrentView->Frame().left;
1354 			float offsetY = y - fCurrentView->Frame().top;
1355 
1356 			BRegion dirty;
1357 			fCurrentView->MoveBy(offsetX, offsetY, &dirty);
1358 
1359 			// TODO: think about how to avoid this hack:
1360 			// the parent clipping needs to be updated, it is not
1361 			// done in MoveBy() since it would cause
1362 			// too much computations when children are resized because
1363 			// follow modes
1364 			if (View* parent = fCurrentView->Parent())
1365 				parent->RebuildClipping(false);
1366 
1367 			fWindow->MarkContentDirty(dirty);
1368 			break;
1369 		}
1370 		case AS_VIEW_RESIZE_TO:
1371 		{
1372 			float newWidth, newHeight;
1373 			link.Read<float>(&newWidth);
1374 			if (link.Read<float>(&newHeight) != B_OK)
1375 				break;
1376 
1377 			DTRACE(("ServerWindow %s: Message AS_VIEW_RESIZE_TO: View name: "
1378 				"%s, width: %.1f, height: %.1f\n", fTitle,
1379 				fCurrentView->Name(), newWidth, newHeight));
1380 
1381 			float deltaWidth = newWidth - fCurrentView->Frame().Width();
1382 			float deltaHeight = newHeight - fCurrentView->Frame().Height();
1383 
1384 			BRegion dirty;
1385 			fCurrentView->ResizeBy(deltaWidth, deltaHeight, &dirty);
1386 
1387 			// TODO: see above
1388 			if (View* parent = fCurrentView->Parent())
1389 				parent->RebuildClipping(false);
1390 
1391 			fWindow->MarkContentDirty(dirty);
1392 			break;
1393 		}
1394 		case AS_VIEW_GET_COORD:
1395 		{
1396 			// our offset in the parent -> will be originX and originY
1397 			// in BView
1398 			BPoint parentOffset = fCurrentView->Frame().LeftTop();
1399 
1400 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_COORD: "
1401 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1402 				fCurrentView->Name(), parentOffset.x, parentOffset.y));
1403 
1404 			fLink.StartMessage(B_OK);
1405 			fLink.Attach<BPoint>(parentOffset);
1406 			fLink.Attach<BRect>(fCurrentView->Bounds());
1407 			fLink.Flush();
1408 			break;
1409 		}
1410 		case AS_VIEW_SET_ORIGIN:
1411 		{
1412 			float x, y;
1413 			link.Read<float>(&x);
1414 			if (link.Read<float>(&y) != B_OK)
1415 				break;
1416 
1417 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_ORIGIN: "
1418 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1419 				fCurrentView->Name(), x, y));
1420 
1421 			fCurrentView->SetDrawingOrigin(BPoint(x, y));
1422 			_UpdateDrawState(fCurrentView);
1423 			break;
1424 		}
1425 		case AS_VIEW_GET_ORIGIN:
1426 		{
1427 			BPoint drawingOrigin = fCurrentView->DrawingOrigin();
1428 
1429 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_ORIGIN: "
1430 				"View: %s -> x: %.1f, y: %.1f\n", Title(),
1431 				fCurrentView->Name(), drawingOrigin.x, drawingOrigin.y));
1432 
1433 			fLink.StartMessage(B_OK);
1434 			fLink.Attach<BPoint>(drawingOrigin);
1435 			fLink.Flush();
1436 			break;
1437 		}
1438 		case AS_VIEW_RESIZE_MODE:
1439 		{
1440 			uint32 resizeMode;
1441 			if (link.Read<uint32>(&resizeMode) != B_OK)
1442 				break;
1443 
1444 			DTRACE(("ServerWindow %s: Message AS_VIEW_RESIZE_MODE: "
1445 				"View: %s -> %ld\n", Title(), fCurrentView->Name(),
1446 				resizeMode));
1447 
1448 			fCurrentView->SetResizeMode(resizeMode);
1449 			break;
1450 		}
1451 		case AS_VIEW_SET_FLAGS:
1452 		{
1453 			uint32 flags;
1454 			link.Read<uint32>(&flags);
1455 
1456 			// The views clipping changes when the B_DRAW_ON_CHILDREN flag is
1457 			// toggled.
1458 			bool updateClipping = (flags & B_DRAW_ON_CHILDREN)
1459 				^ (fCurrentView->Flags() & B_DRAW_ON_CHILDREN);
1460 
1461 			fCurrentView->SetFlags(flags);
1462 			_UpdateDrawState(fCurrentView);
1463 
1464 			if (updateClipping) {
1465 				fCurrentView->RebuildClipping(false);
1466 				fCurrentDrawingRegionValid = false;
1467 			}
1468 
1469 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_FLAGS: "
1470 				"View: %s -> flags: %lu\n", Title(), fCurrentView->Name(),
1471 				flags));
1472 			break;
1473 		}
1474 		case AS_VIEW_HIDE:
1475 			DTRACE(("ServerWindow %s: Message AS_VIEW_HIDE: View: %s\n",
1476 				Title(), fCurrentView->Name()));
1477 			fCurrentView->SetHidden(true);
1478 			break;
1479 
1480 		case AS_VIEW_SHOW:
1481 			DTRACE(("ServerWindow %s: Message AS_VIEW_SHOW: View: %s\n",
1482 				Title(), fCurrentView->Name()));
1483 			fCurrentView->SetHidden(false);
1484 			break;
1485 
1486 		case AS_VIEW_SET_LINE_MODE:
1487 		{
1488 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_LINE_MODE: "
1489 				"View: %s\n", Title(), fCurrentView->Name()));
1490 			ViewSetLineModeInfo info;
1491 			if (link.Read<ViewSetLineModeInfo>(&info) != B_OK)
1492 				break;
1493 
1494 			fCurrentView->CurrentState()->SetLineCapMode(info.lineCap);
1495 			fCurrentView->CurrentState()->SetLineJoinMode(info.lineJoin);
1496 			fCurrentView->CurrentState()->SetMiterLimit(info.miterLimit);
1497 
1498 			fWindow->GetDrawingEngine()->SetStrokeMode(info.lineCap,
1499 				info.lineJoin, info.miterLimit);
1500 
1501 			break;
1502 		}
1503 		case AS_VIEW_GET_LINE_MODE:
1504 		{
1505 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_LINE_MODE: "
1506 				"View: %s\n", Title(), fCurrentView->Name()));
1507 			ViewSetLineModeInfo info;
1508 			info.lineJoin = fCurrentView->CurrentState()->LineJoinMode();
1509 			info.lineCap = fCurrentView->CurrentState()->LineCapMode();
1510 			info.miterLimit = fCurrentView->CurrentState()->MiterLimit();
1511 
1512 			fLink.StartMessage(B_OK);
1513 			fLink.Attach<ViewSetLineModeInfo>(info);
1514 			fLink.Flush();
1515 
1516 			break;
1517 		}
1518 		case AS_VIEW_PUSH_STATE:
1519 		{
1520 			DTRACE(("ServerWindow %s: Message AS_VIEW_PUSH_STATE: View: "
1521 				"%s\n", Title(), fCurrentView->Name()));
1522 
1523 			fCurrentView->PushState();
1524 			// TODO: is this necessary?
1525 //			_UpdateDrawState(fCurrentView);
1526 			break;
1527 		}
1528 		case AS_VIEW_POP_STATE:
1529 		{
1530 			DTRACE(("ServerWindow %s: Message AS_VIEW_POP_STATE: View: %s\n",
1531 				Title(), fCurrentView->Name()));
1532 
1533 			fCurrentView->PopState();
1534 			_UpdateDrawState(fCurrentView);
1535 			break;
1536 		}
1537 		case AS_VIEW_SET_SCALE:
1538 		{
1539 			float scale;
1540 			if (link.Read<float>(&scale) != B_OK)
1541 				break;
1542 
1543 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_SCALE: "
1544 				"View: %s -> scale: %.2f\n", Title(), fCurrentView->Name(),
1545 				scale));
1546 
1547 			fCurrentView->SetScale(scale);
1548 			_UpdateDrawState(fCurrentView);
1549 			break;
1550 		}
1551 		case AS_VIEW_GET_SCALE:
1552 		{
1553 			float scale = fCurrentView->CurrentState()->Scale();
1554 
1555 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_SCALE: "
1556 				"View: %s -> scale: %.2f\n",
1557 				Title(), fCurrentView->Name(), scale));
1558 
1559 			fLink.StartMessage(B_OK);
1560 			fLink.Attach<float>(scale);
1561 			fLink.Flush();
1562 			break;
1563 		}
1564 		case AS_VIEW_SET_PEN_LOC:
1565 		{
1566 			BPoint location;
1567 			if (link.Read<BPoint>(&location) != B_OK)
1568 				break;
1569 
1570 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PEN_LOC: "
1571 				"View: %s -> BPoint(%.1f, %.1f)\n", Title(),
1572 				fCurrentView->Name(), location.x, location.y));
1573 
1574 			fCurrentView->CurrentState()->SetPenLocation(location);
1575 			break;
1576 		}
1577 		case AS_VIEW_GET_PEN_LOC:
1578 		{
1579 			BPoint location = fCurrentView->CurrentState()->PenLocation();
1580 
1581 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_PEN_LOC: "
1582 				"View: %s -> BPoint(%.1f, %.1f)\n", Title(),
1583 				fCurrentView->Name(), location.x, location.y));
1584 
1585 			fLink.StartMessage(B_OK);
1586 			fLink.Attach<BPoint>(location);
1587 			fLink.Flush();
1588 
1589 			break;
1590 		}
1591 		case AS_VIEW_SET_PEN_SIZE:
1592 		{
1593 			float penSize;
1594 			if (link.Read<float>(&penSize) != B_OK)
1595 				break;
1596 
1597 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PEN_SIZE: "
1598 				"View: %s -> %.1f\n", Title(), fCurrentView->Name(), penSize));
1599 
1600 			fCurrentView->CurrentState()->SetPenSize(penSize);
1601 			fWindow->GetDrawingEngine()->SetPenSize(
1602 				fCurrentView->CurrentState()->PenSize());
1603 			break;
1604 		}
1605 		case AS_VIEW_GET_PEN_SIZE:
1606 		{
1607 			float penSize = fCurrentView->CurrentState()->UnscaledPenSize();
1608 
1609 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_PEN_SIZE: "
1610 				"View: %s -> %.1f\n", Title(), fCurrentView->Name(), penSize));
1611 
1612 			fLink.StartMessage(B_OK);
1613 			fLink.Attach<float>(penSize);
1614 			fLink.Flush();
1615 
1616 			break;
1617 		}
1618 		case AS_VIEW_SET_VIEW_COLOR:
1619 		{
1620 			rgb_color color;
1621 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1622 				break;
1623 
1624 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_VIEW_COLOR: "
1625 				"View: %s -> rgb_color(%d, %d, %d, %d)\n", Title(),
1626 				fCurrentView->Name(), color.red, color.green, color.blue,
1627 				color.alpha));
1628 
1629 			fCurrentView->SetViewColor(color);
1630 			break;
1631 		}
1632 		case AS_VIEW_GET_VIEW_COLOR:
1633 		{
1634 			rgb_color color = fCurrentView->ViewColor();
1635 
1636 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_VIEW_COLOR: "
1637 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1638 				Title(), fCurrentView->Name(), color.red, color.green,
1639 				color.blue, color.alpha));
1640 
1641 			fLink.StartMessage(B_OK);
1642 			fLink.Attach<rgb_color>(color);
1643 			fLink.Flush();
1644 			break;
1645 		}
1646 		case AS_VIEW_SET_HIGH_COLOR:
1647 		{
1648 			rgb_color color;
1649 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1650 				break;
1651 
1652 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_HIGH_COLOR: "
1653 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1654 				Title(), fCurrentView->Name(), color.red, color.green,
1655 				color.blue, color.alpha));
1656 
1657 			fCurrentView->CurrentState()->SetHighColor(color);
1658 			fWindow->GetDrawingEngine()->SetHighColor(color);
1659 			break;
1660 		}
1661 		case AS_VIEW_GET_HIGH_COLOR:
1662 		{
1663 			rgb_color color = fCurrentView->CurrentState()->HighColor();
1664 
1665 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_HIGH_COLOR: "
1666 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1667 				Title(), fCurrentView->Name(), color.red, color.green,
1668 				color.blue, color.alpha));
1669 
1670 			fLink.StartMessage(B_OK);
1671 			fLink.Attach<rgb_color>(color);
1672 			fLink.Flush();
1673 			break;
1674 		}
1675 		case AS_VIEW_SET_LOW_COLOR:
1676 		{
1677 			rgb_color color;
1678 			if (link.Read(&color, sizeof(rgb_color)) != B_OK)
1679 				break;
1680 
1681 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_LOW_COLOR: "
1682 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1683 				Title(), fCurrentView->Name(), color.red, color.green,
1684 				color.blue, color.alpha));
1685 
1686 			fCurrentView->CurrentState()->SetLowColor(color);
1687 			fWindow->GetDrawingEngine()->SetLowColor(color);
1688 			break;
1689 		}
1690 		case AS_VIEW_GET_LOW_COLOR:
1691 		{
1692 			rgb_color color = fCurrentView->CurrentState()->LowColor();
1693 
1694 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_LOW_COLOR: "
1695 				"View: %s -> rgb_color(%d, %d, %d, %d)\n",
1696 				Title(), fCurrentView->Name(), color.red, color.green,
1697 				color.blue, color.alpha));
1698 
1699 			fLink.StartMessage(B_OK);
1700 			fLink.Attach<rgb_color>(color);
1701 			fLink.Flush();
1702 			break;
1703 		}
1704 		case AS_VIEW_SET_PATTERN:
1705 		{
1706 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_PATTERN: "
1707 				"View: %s\n", fTitle, fCurrentView->Name()));
1708 
1709 			pattern pat;
1710 			if (link.Read(&pat, sizeof(pattern)) != B_OK)
1711 				break;
1712 
1713 			fCurrentView->CurrentState()->SetPattern(Pattern(pat));
1714 			fWindow->GetDrawingEngine()->SetPattern(pat);
1715 			break;
1716 		}
1717 
1718 		case AS_VIEW_SET_BLENDING_MODE:
1719 		{
1720 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_BLEND_MODE: "
1721 				"View: %s\n", Title(), fCurrentView->Name()));
1722 
1723 			ViewBlendingModeInfo info;
1724 			if (link.Read<ViewBlendingModeInfo>(&info) != B_OK)
1725 				break;
1726 
1727 			fCurrentView->CurrentState()->SetBlendingMode(
1728 				info.sourceAlpha, info.alphaFunction);
1729 			fWindow->GetDrawingEngine()->SetBlendingMode(
1730 				info.sourceAlpha, info.alphaFunction);
1731 			break;
1732 		}
1733 		case AS_VIEW_GET_BLENDING_MODE:
1734 		{
1735 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_BLEND_MODE: "
1736 				"View: %s\n", Title(), fCurrentView->Name()));
1737 
1738 			ViewBlendingModeInfo info;
1739 			info.sourceAlpha = fCurrentView->CurrentState()->AlphaSrcMode();
1740 			info.alphaFunction = fCurrentView->CurrentState()->AlphaFncMode();
1741 
1742 			fLink.StartMessage(B_OK);
1743 			fLink.Attach<ViewBlendingModeInfo>(info);
1744 			fLink.Flush();
1745 
1746 			break;
1747 		}
1748 		case AS_VIEW_SET_DRAWING_MODE:
1749 		{
1750 			int8 drawingMode;
1751 			if (link.Read<int8>(&drawingMode) != B_OK)
1752 				break;
1753 
1754 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_DRAW_MODE: "
1755 				"View: %s -> %s\n", Title(), fCurrentView->Name(),
1756 				kDrawingModeMap[drawingMode]));
1757 
1758 			fCurrentView->CurrentState()->SetDrawingMode(
1759 				(drawing_mode)drawingMode);
1760 			fWindow->GetDrawingEngine()->SetDrawingMode(
1761 				(drawing_mode)drawingMode);
1762 			break;
1763 		}
1764 		case AS_VIEW_GET_DRAWING_MODE:
1765 		{
1766 			int8 drawingMode
1767 				= (int8)(fCurrentView->CurrentState()->GetDrawingMode());
1768 
1769 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_DRAW_MODE: "
1770 				"View: %s -> %s\n", Title(), fCurrentView->Name(),
1771 				kDrawingModeMap[drawingMode]));
1772 
1773 			fLink.StartMessage(B_OK);
1774 			fLink.Attach<int8>(drawingMode);
1775 			fLink.Flush();
1776 
1777 			break;
1778 		}
1779 		case AS_VIEW_SET_VIEW_BITMAP:
1780 		{
1781 			DTRACE(("ServerWindow %s: Message AS_VIEW_SET_VIEW_BITMAP: "
1782 				"View: %s\n", Title(), fCurrentView->Name()));
1783 
1784 			int32 bitmapToken, resizingMode, options;
1785 			BRect srcRect, dstRect;
1786 
1787 			link.Read<int32>(&bitmapToken);
1788 			link.Read<BRect>(&srcRect);
1789 			link.Read<BRect>(&dstRect);
1790 			link.Read<int32>(&resizingMode);
1791 			status_t status = link.Read<int32>(&options);
1792 
1793 			rgb_color colorKey = {0};
1794 
1795 			if (status == B_OK) {
1796 				ServerBitmap* bitmap = fServerApp->GetBitmap(bitmapToken);
1797 				if (bitmapToken == -1 || bitmap != NULL) {
1798 					bool wasOverlay = fCurrentView->ViewBitmap() != NULL
1799 						&& fCurrentView->ViewBitmap()->Overlay() != NULL;
1800 
1801 					fCurrentView->SetViewBitmap(bitmap, srcRect, dstRect,
1802 						resizingMode, options);
1803 
1804 					// TODO: if we revert the view color overlay handling
1805 					//	in View::Draw() to the BeOS version, we never
1806 					//	need to invalidate the view for overlays.
1807 
1808 					// Invalidate view - but only if this is a non-overlay
1809 					// switch
1810 					if (bitmap == NULL || bitmap->Overlay() == NULL
1811 						|| !wasOverlay) {
1812 						BRegion dirty((BRect)fCurrentView->Bounds());
1813 						fWindow->InvalidateView(fCurrentView, dirty);
1814 					}
1815 
1816 					if (bitmap != NULL && bitmap->Overlay() != NULL) {
1817 						bitmap->Overlay()->SetFlags(options);
1818 						colorKey = bitmap->Overlay()->Color();
1819 					}
1820 
1821 					if (bitmap != NULL)
1822 						bitmap->ReleaseReference();
1823 				} else
1824 					status = B_BAD_VALUE;
1825 			}
1826 
1827 			fLink.StartMessage(status);
1828 			if (status == B_OK && (options & AS_REQUEST_COLOR_KEY) != 0) {
1829 				// Attach color key for the overlay bitmap
1830 				fLink.Attach<rgb_color>(colorKey);
1831 			}
1832 
1833 			fLink.Flush();
1834 			break;
1835 		}
1836 		case AS_VIEW_PRINT_ALIASING:
1837 		{
1838 			DTRACE(("ServerWindow %s: Message AS_VIEW_PRINT_ALIASING: "
1839 				"View: %s\n", Title(), fCurrentView->Name()));
1840 
1841 			bool fontAliasing;
1842 			if (link.Read<bool>(&fontAliasing) == B_OK) {
1843 				fCurrentView->CurrentState()->SetForceFontAliasing(fontAliasing);
1844 				_UpdateDrawState(fCurrentView);
1845 			}
1846 			break;
1847 		}
1848 		case AS_VIEW_CLIP_TO_PICTURE:
1849 		{
1850 			DTRACE(("ServerWindow %s: Message AS_VIEW_CLIP_TO_PICTURE: "
1851 				"View: %s\n", Title(), fCurrentView->Name()));
1852 
1853 			// TODO: you are not allowed to use View regions here!!!
1854 
1855 			int32 pictureToken;
1856 			BPoint where;
1857 			bool inverse = false;
1858 
1859 			link.Read<int32>(&pictureToken);
1860 			link.Read<BPoint>(&where);
1861 			if (link.Read<bool>(&inverse) != B_OK)
1862 				break;
1863 
1864 			ServerPicture* picture = fServerApp->GetPicture(pictureToken);
1865 			if (picture == NULL)
1866 				break;
1867 
1868 			BRegion region;
1869 			// TODO: I think we also need the BView's token
1870 			// I think PictureToRegion would fit better into the View class (?)
1871 			if (PictureToRegion(picture, region, inverse, where) == B_OK)
1872 				fCurrentView->SetUserClipping(&region);
1873 
1874 			picture->ReleaseReference();
1875 			break;
1876 		}
1877 
1878 		case AS_VIEW_GET_CLIP_REGION:
1879 		{
1880 			DTRACE(("ServerWindow %s: Message AS_VIEW_GET_CLIP_REGION: "
1881 				"View: %s\n", Title(), fCurrentView->Name()));
1882 
1883 			// if this view is hidden, it has no visible region
1884 			fLink.StartMessage(B_OK);
1885 			if (!fWindow->IsVisible() || !fCurrentView->IsVisible()) {
1886 				BRegion empty;
1887 				fLink.AttachRegion(empty);
1888 			} else {
1889 				_UpdateCurrentDrawingRegion();
1890 				BRegion region(fCurrentDrawingRegion);
1891 				fCurrentView->ConvertFromScreen(&region);
1892 				fLink.AttachRegion(region);
1893 			}
1894 			fLink.Flush();
1895 
1896 			break;
1897 		}
1898 		case AS_VIEW_SET_CLIP_REGION:
1899 		{
1900 			int32 rectCount;
1901 			status_t status = link.Read<int32>(&rectCount);
1902 				// a negative count means no
1903 				// region for the current draw state,
1904 				// but an *empty* region is actually valid!
1905 				// even if it means no drawing is allowed
1906 
1907 			if (status < B_OK)
1908 				break;
1909 
1910 			if (rectCount >= 0) {
1911 				// we are supposed to set the clipping region
1912 				BRegion region;
1913 				if (rectCount > 0 && link.ReadRegion(&region) < B_OK)
1914 					break;
1915 
1916 				DTRACE(("ServerWindow %s: Message AS_VIEW_SET_CLIP_REGION: "
1917 					"View: %s -> rect count: %ld, frame = "
1918 					"BRect(%.1f, %.1f, %.1f, %.1f)\n",
1919 					Title(), fCurrentView->Name(), rectCount,
1920 					region.Frame().left, region.Frame().top,
1921 					region.Frame().right, region.Frame().bottom));
1922 
1923 				fCurrentView->SetUserClipping(&region);
1924 			} else {
1925 				// we are supposed to unset the clipping region
1926 				// passing NULL sets this states region to that
1927 				// of the previous state
1928 
1929 				DTRACE(("ServerWindow %s: Message AS_VIEW_SET_CLIP_REGION: "
1930 					"View: %s -> unset\n", Title(), fCurrentView->Name()));
1931 
1932 				fCurrentView->SetUserClipping(NULL);
1933 			}
1934 			fCurrentDrawingRegionValid = false;
1935 
1936 			break;
1937 		}
1938 
1939 		case AS_VIEW_INVALIDATE_RECT:
1940 		{
1941 			// NOTE: looks like this call is NOT affected by origin and scale
1942 			// on R5 so this implementation is "correct"
1943 			BRect invalidRect;
1944 			if (link.Read<BRect>(&invalidRect) == B_OK) {
1945 				DTRACE(("ServerWindow %s: Message AS_VIEW_INVALIDATE_RECT: "
1946 					"View: %s -> BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
1947 					fCurrentView->Name(), invalidRect.left, invalidRect.top,
1948 					invalidRect.right, invalidRect.bottom));
1949 
1950 				BRegion dirty(invalidRect);
1951 				fWindow->InvalidateView(fCurrentView, dirty);
1952 			}
1953 			break;
1954 		}
1955 		case AS_VIEW_INVALIDATE_REGION:
1956 		{
1957 			// NOTE: looks like this call is NOT affected by origin and scale
1958 			// on R5 so this implementation is "correct"
1959 			BRegion region;
1960 			if (link.ReadRegion(&region) < B_OK)
1961 				break;
1962 
1963 			DTRACE(("ServerWindow %s: Message AS_VIEW_INVALIDATE_REGION: "
1964 					"View: %s -> rect count: %ld, frame: BRect(%.1f, %.1f, "
1965 					"%.1f, %.1f)\n", Title(),
1966 					fCurrentView->Name(), region.CountRects(),
1967 					region.Frame().left, region.Frame().top,
1968 					region.Frame().right, region.Frame().bottom));
1969 
1970 			fWindow->InvalidateView(fCurrentView, region);
1971 			break;
1972 		}
1973 
1974 		case AS_VIEW_DRAG_IMAGE:
1975 		{
1976 			// TODO: flesh out AS_VIEW_DRAG_IMAGE
1977 			DTRACE(("ServerWindow %s: Message AS_DRAG_IMAGE\n", Title()));
1978 
1979 			int32 bitmapToken;
1980 			drawing_mode dragMode;
1981 			BPoint offset;
1982 			int32 bufferSize;
1983 
1984 			link.Read<int32>(&bitmapToken);
1985 			link.Read<int32>((int32*)&dragMode);
1986 			link.Read<BPoint>(&offset);
1987 			link.Read<int32>(&bufferSize);
1988 
1989 			if (bufferSize > 0) {
1990 				char* buffer = new (nothrow) char[bufferSize];
1991 				BMessage dragMessage;
1992 				if (link.Read(buffer, bufferSize) == B_OK
1993 					&& dragMessage.Unflatten(buffer) == B_OK) {
1994 						ServerBitmap* bitmap
1995 							= fServerApp->GetBitmap(bitmapToken);
1996 						// TODO: possible deadlock
1997 fDesktop->UnlockSingleWindow();
1998 						fDesktop->EventDispatcher().SetDragMessage(dragMessage,
1999 							bitmap, offset);
2000 fDesktop->LockSingleWindow();
2001 						bitmap->ReleaseReference();
2002 				}
2003 				delete[] buffer;
2004 			}
2005 			// sync the client (it can now delete the bitmap)
2006 			fLink.StartMessage(B_OK);
2007 			fLink.Flush();
2008 
2009 			break;
2010 		}
2011 		case AS_VIEW_DRAG_RECT:
2012 		{
2013 			// TODO: flesh out AS_VIEW_DRAG_RECT
2014 			DTRACE(("ServerWindow %s: Message AS_DRAG_RECT\n", Title()));
2015 
2016 			BRect dragRect;
2017 			BPoint offset;
2018 			int32 bufferSize;
2019 
2020 			link.Read<BRect>(&dragRect);
2021 			link.Read<BPoint>(&offset);
2022 			link.Read<int32>(&bufferSize);
2023 
2024 			if (bufferSize > 0) {
2025 				char* buffer = new (nothrow) char[bufferSize];
2026 				BMessage dragMessage;
2027 				if (link.Read(buffer, bufferSize) == B_OK
2028 					&& dragMessage.Unflatten(buffer) == B_OK) {
2029 						// TODO: possible deadlock
2030 fDesktop->UnlockSingleWindow();
2031 						fDesktop->EventDispatcher().SetDragMessage(dragMessage,
2032 							NULL /* should be dragRect */, offset);
2033 fDesktop->LockSingleWindow();
2034 				}
2035 				delete[] buffer;
2036 			}
2037 			break;
2038 		}
2039 
2040 		case AS_VIEW_BEGIN_RECT_TRACK:
2041 		{
2042 			DTRACE(("ServerWindow %s: Message AS_VIEW_BEGIN_RECT_TRACK\n",
2043 				Title()));
2044 			BRect dragRect;
2045 			uint32 style;
2046 
2047 			link.Read<BRect>(&dragRect);
2048 			link.Read<uint32>(&style);
2049 
2050 			// TODO: implement rect tracking (used sometimes for selecting
2051 			// a group of things, also sometimes used to appear to drag
2052 			// something, but without real drag message)
2053 			break;
2054 		}
2055 		case AS_VIEW_END_RECT_TRACK:
2056 		{
2057 			DTRACE(("ServerWindow %s: Message AS_VIEW_END_RECT_TRACK\n",
2058 				Title()));
2059 			// TODO: implement rect tracking
2060 			break;
2061 		}
2062 
2063 		case AS_VIEW_BEGIN_PICTURE:
2064 		{
2065 			DTRACE(("ServerWindow %s: Message AS_VIEW_BEGIN_PICTURE\n",
2066 				Title()));
2067 			ServerPicture* picture = App()->CreatePicture();
2068 			if (picture != NULL) {
2069 				picture->SyncState(fCurrentView);
2070 				fCurrentView->SetPicture(picture);
2071 			}
2072 			break;
2073 		}
2074 
2075 		case AS_VIEW_APPEND_TO_PICTURE:
2076 		{
2077 			DTRACE(("ServerWindow %s: Message AS_VIEW_APPEND_TO_PICTURE\n",
2078 				Title()));
2079 
2080 			int32 token;
2081 			link.Read<int32>(&token);
2082 
2083 			ServerPicture* picture = App()->GetPicture(token);
2084 			if (picture != NULL)
2085 				picture->SyncState(fCurrentView);
2086 
2087 			fCurrentView->SetPicture(picture);
2088 
2089 			if (picture != NULL)
2090 				picture->ReleaseReference();
2091 			break;
2092 		}
2093 
2094 		case AS_VIEW_END_PICTURE:
2095 		{
2096 			DTRACE(("ServerWindow %s: Message AS_VIEW_END_PICTURE\n",
2097 				Title()));
2098 
2099 			ServerPicture* picture = fCurrentView->Picture();
2100 			if (picture != NULL) {
2101 				fCurrentView->SetPicture(NULL);
2102 				fLink.StartMessage(B_OK);
2103 				fLink.Attach<int32>(picture->Token());
2104 			} else
2105 				fLink.StartMessage(B_ERROR);
2106 
2107 			fLink.Flush();
2108 			break;
2109 		}
2110 
2111 		default:
2112 			_DispatchViewDrawingMessage(code, link);
2113 			break;
2114 	}
2115 }
2116 
2117 
2118 /*!	Dispatches all view drawing messages.
2119 	The desktop clipping must be read locked when entering this method.
2120 	Requires a valid fCurrentView.
2121 */
2122 void
2123 ServerWindow::_DispatchViewDrawingMessage(int32 code,
2124 	BPrivate::LinkReceiver &link)
2125 {
2126 	if (!fCurrentView->IsVisible() || !fWindow->IsVisible()) {
2127 		if (link.NeedsReply()) {
2128 			debug_printf("ServerWindow::DispatchViewDrawingMessage() got "
2129 				"message %ld that needs a reply!\n", code);
2130 			// the client is now blocking and waiting for a reply!
2131 			fLink.StartMessage(B_ERROR);
2132 			fLink.Flush();
2133 		}
2134 		return;
2135 	}
2136 
2137 	DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
2138 	if (!drawingEngine) {
2139 		// ?!?
2140 		debug_printf("ServerWindow %s: no drawing engine!!\n", Title());
2141 		if (link.NeedsReply()) {
2142 			// the client is now blocking and waiting for a reply!
2143 			fLink.StartMessage(B_ERROR);
2144 			fLink.Flush();
2145 		}
2146 		return;
2147 	}
2148 
2149 	_UpdateCurrentDrawingRegion();
2150 	if (fCurrentDrawingRegion.CountRects() <= 0) {
2151 		DTRACE(("ServerWindow %s: _DispatchViewDrawingMessage(): View: %s, "
2152 			"INVALID CLIPPING!\n", Title(), fCurrentView->Name()));
2153 		if (link.NeedsReply()) {
2154 			// the client is now blocking and waiting for a reply!
2155 			fLink.StartMessage(B_ERROR);
2156 			fLink.Flush();
2157 		}
2158 		return;
2159 	}
2160 
2161 	drawingEngine->LockParallelAccess();
2162 	// NOTE: the region is not copied, Painter keeps a pointer,
2163 	// that's why you need to use the clipping only for as long
2164 	// as you have it locked
2165 	drawingEngine->ConstrainClippingRegion(&fCurrentDrawingRegion);
2166 
2167 	switch (code) {
2168 		case AS_STROKE_LINE:
2169 		{
2170 			ViewStrokeLineInfo info;
2171 			if (link.Read<ViewStrokeLineInfo>(&info) != B_OK)
2172 				break;
2173 
2174 			DTRACE(("ServerWindow %s: Message AS_STROKE_LINE: View: %s -> "
2175 				"BPoint(%.1f, %.1f) - BPoint(%.1f, %.1f)\n", Title(),
2176 					fCurrentView->Name(),
2177 					info.startPoint.x, info.startPoint.y,
2178 					info.endPoint.x, info.endPoint.y));
2179 
2180 			BPoint penPos = info.endPoint;
2181 			fCurrentView->ConvertToScreenForDrawing(&info.startPoint);
2182 			fCurrentView->ConvertToScreenForDrawing(&info.endPoint);
2183 			drawingEngine->StrokeLine(info.startPoint, info.endPoint);
2184 
2185 			// We update the pen here because many DrawingEngine calls which
2186 			// do not update the pen position actually call StrokeLine
2187 
2188 			// TODO: Decide where to put this, for example, it cannot be done
2189 			// for DrawString(), also there needs to be a decision, if the pen
2190 			// location is in View coordinates (I think it should be) or in
2191 			// screen coordinates.
2192 			fCurrentView->CurrentState()->SetPenLocation(penPos);
2193 			break;
2194 		}
2195 		case AS_VIEW_INVERT_RECT:
2196 		{
2197 			BRect rect;
2198 			if (link.Read<BRect>(&rect) != B_OK)
2199 				break;
2200 
2201 			DTRACE(("ServerWindow %s: Message AS_INVERT_RECT: View: %s -> "
2202 				"BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2203 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2204 				rect.bottom));
2205 
2206 			fCurrentView->ConvertToScreenForDrawing(&rect);
2207 			drawingEngine->InvertRect(rect);
2208 			break;
2209 		}
2210 		case AS_STROKE_RECT:
2211 		{
2212 			BRect rect;
2213 			if (link.Read<BRect>(&rect) != B_OK)
2214 				break;
2215 
2216 			DTRACE(("ServerWindow %s: Message AS_STROKE_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->StrokeRect(rect);
2223 			break;
2224 		}
2225 		case AS_FILL_RECT:
2226 		{
2227 			BRect rect;
2228 			if (link.Read<BRect>(&rect) != B_OK)
2229 				break;
2230 
2231 			DTRACE(("ServerWindow %s: Message AS_FILL_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->FillRect(rect);
2238 			break;
2239 		}
2240 		case AS_FILL_RECT_GRADIENT:
2241 		{
2242 			BRect rect;
2243 			link.Read<BRect>(&rect);
2244 			BGradient* gradient;
2245 			if (link.ReadGradient(&gradient) != B_OK)
2246 				break;
2247 
2248 			GTRACE(("ServerWindow %s: Message AS_FILL_RECT_GRADIENT: View: %s "
2249 				"-> BRect(%.1f, %.1f, %.1f, %.1f)\n", Title(),
2250 				fCurrentView->Name(), rect.left, rect.top, rect.right,
2251 				rect.bottom));
2252 
2253 			fCurrentView->ConvertToScreenForDrawing(&rect);
2254 			fCurrentView->ConvertToScreenForDrawing(gradient);
2255 			drawingEngine->FillRect(rect, *gradient);
2256 			break;
2257 		}
2258 		case AS_VIEW_DRAW_BITMAP:
2259 		{
2260 			ViewDrawBitmapInfo info;
2261 			if (link.Read<ViewDrawBitmapInfo>(&info) != B_OK)
2262 				break;
2263 
2264 #if 0
2265 			if (strcmp(fServerApp->SignatureLeaf(), "x-vnd.videolan-vlc") == 0)
2266 				options |= B_FILTER_BITMAP_BILINEAR;
2267 #endif
2268 
2269 			ServerBitmap* bitmap = fServerApp->GetBitmap(info.bitmapToken);
2270 			if (bitmap != NULL) {
2271 				DTRACE(("ServerWindow %s: Message AS_VIEW_DRAW_BITMAP: "
2272 					"View: %s, bitmap: %ld (size %ld x %ld), "
2273 					"BRect(%.1f, %.1f, %.1f, %.1f) -> "
2274 					"BRect(%.1f, %.1f, %.1f, %.1f)\n",
2275 					fTitle, fCurrentView->Name(), info.bitmapToken,
2276 					bitmap->Width(), bitmap->Height(),
2277 					info.bitmapRect.left, info.bitmapRect.top,
2278 					info.bitmapRect.right, info.bitmapRect.bottom,
2279 					info.viewRect.left, info.viewRect.top,
2280 					info.viewRect.right, info.viewRect.bottom));
2281 
2282 				fCurrentView->ConvertToScreenForDrawing(&info.viewRect);
2283 
2284 				drawingEngine->DrawBitmap(bitmap, info.bitmapRect,
2285 					info.viewRect, info.options);
2286 
2287 				bitmap->ReleaseReference();
2288 			}
2289 			break;
2290 		}
2291 		case AS_STROKE_ARC:
2292 		case AS_FILL_ARC:
2293 		{
2294 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ARC\n", Title()));
2295 
2296 			float angle, span;
2297 			BRect r;
2298 
2299 			link.Read<BRect>(&r);
2300 			link.Read<float>(&angle);
2301 			if (link.Read<float>(&span) != B_OK)
2302 				break;
2303 
2304 			fCurrentView->ConvertToScreenForDrawing(&r);
2305 			drawingEngine->DrawArc(r, angle, span, code == AS_FILL_ARC);
2306 			break;
2307 		}
2308 		case AS_FILL_ARC_GRADIENT:
2309 		{
2310 			GTRACE(("ServerWindow %s: Message AS_FILL_ARC_GRADIENT\n",
2311 				Title()));
2312 
2313 			float angle, span;
2314 			BRect r;
2315 			link.Read<BRect>(&r);
2316 			link.Read<float>(&angle);
2317 			link.Read<float>(&span);
2318 			BGradient* gradient;
2319 			if (link.ReadGradient(&gradient) != B_OK)
2320 				break;
2321 			fCurrentView->ConvertToScreenForDrawing(&r);
2322 			fCurrentView->ConvertToScreenForDrawing(gradient);
2323 			drawingEngine->FillArc(r, angle, span, *gradient);
2324 			break;
2325 		}
2326 		case AS_STROKE_BEZIER:
2327 		case AS_FILL_BEZIER:
2328 		{
2329 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_BEZIER\n",
2330 				Title()));
2331 
2332 			BPoint pts[4];
2333 			status_t status;
2334 			for (int32 i = 0; i < 4; i++) {
2335 				status = link.Read<BPoint>(&(pts[i]));
2336 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2337 			}
2338 			if (status != B_OK)
2339 				break;
2340 
2341 			drawingEngine->DrawBezier(pts, code == AS_FILL_BEZIER);
2342 			break;
2343 		}
2344 		case AS_FILL_BEZIER_GRADIENT:
2345 		{
2346 			GTRACE(("ServerWindow %s: Message AS_FILL_BEZIER_GRADIENT\n",
2347 				Title()));
2348 
2349 			BPoint pts[4];
2350 			for (int32 i = 0; i < 4; i++) {
2351 				link.Read<BPoint>(&(pts[i]));
2352 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2353 			}
2354 			BGradient* gradient;
2355 			if (link.ReadGradient(&gradient) != B_OK)
2356 				break;
2357 			fCurrentView->ConvertToScreenForDrawing(gradient);
2358 			drawingEngine->FillBezier(pts, *gradient);
2359 			break;
2360 		}
2361 		case AS_STROKE_ELLIPSE:
2362 		case AS_FILL_ELLIPSE:
2363 		{
2364 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ELLIPSE\n",
2365 				Title()));
2366 
2367 			BRect rect;
2368 			if (link.Read<BRect>(&rect) != B_OK)
2369 				break;
2370 
2371 			fCurrentView->ConvertToScreenForDrawing(&rect);
2372 			drawingEngine->DrawEllipse(rect, code == AS_FILL_ELLIPSE);
2373 			break;
2374 		}
2375 		case AS_FILL_ELLIPSE_GRADIENT:
2376 		{
2377 			GTRACE(("ServerWindow %s: Message AS_FILL_ELLIPSE_GRADIENT\n",
2378 				Title()));
2379 
2380 			BRect rect;
2381 			link.Read<BRect>(&rect);
2382 			BGradient* gradient;
2383 			if (link.ReadGradient(&gradient) != B_OK)
2384 				break;
2385 			fCurrentView->ConvertToScreenForDrawing(&rect);
2386 			fCurrentView->ConvertToScreenForDrawing(gradient);
2387 			drawingEngine->FillEllipse(rect, *gradient);
2388 			break;
2389 		}
2390 		case AS_STROKE_ROUNDRECT:
2391 		case AS_FILL_ROUNDRECT:
2392 		{
2393 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_ROUNDRECT\n",
2394 				Title()));
2395 
2396 			BRect rect;
2397 			float xrad,yrad;
2398 			link.Read<BRect>(&rect);
2399 			link.Read<float>(&xrad);
2400 			if (link.Read<float>(&yrad) != B_OK)
2401 				break;
2402 
2403 			fCurrentView->ConvertToScreenForDrawing(&rect);
2404 			drawingEngine->DrawRoundRect(rect, xrad, yrad,
2405 				code == AS_FILL_ROUNDRECT);
2406 			break;
2407 		}
2408 		case AS_FILL_ROUNDRECT_GRADIENT:
2409 		{
2410 			GTRACE(("ServerWindow %s: Message AS_FILL_ROUNDRECT_GRADIENT\n",
2411 				Title()));
2412 
2413 			BRect rect;
2414 			float xrad,yrad;
2415 			link.Read<BRect>(&rect);
2416 			link.Read<float>(&xrad);
2417 			link.Read<float>(&yrad);
2418 			BGradient* gradient;
2419 			if (link.ReadGradient(&gradient) != B_OK)
2420 				break;
2421 			fCurrentView->ConvertToScreenForDrawing(&rect);
2422 			fCurrentView->ConvertToScreenForDrawing(gradient);
2423 			drawingEngine->FillRoundRect(rect, xrad, yrad, *gradient);
2424 			break;
2425 		}
2426 		case AS_STROKE_TRIANGLE:
2427 		case AS_FILL_TRIANGLE:
2428 		{
2429 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_TRIANGLE\n",
2430 				Title()));
2431 
2432 			BPoint pts[3];
2433 			BRect rect;
2434 
2435 			for (int32 i = 0; i < 3; i++) {
2436 				link.Read<BPoint>(&(pts[i]));
2437 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2438 			}
2439 
2440 			if (link.Read<BRect>(&rect) != B_OK)
2441 				break;
2442 
2443 			fCurrentView->ConvertToScreenForDrawing(&rect);
2444 			drawingEngine->DrawTriangle(pts, rect, code == AS_FILL_TRIANGLE);
2445 			break;
2446 		}
2447 		case AS_FILL_TRIANGLE_GRADIENT:
2448 		{
2449 			DTRACE(("ServerWindow %s: Message AS_FILL_TRIANGLE_GRADIENT\n",
2450 				Title()));
2451 
2452 			BPoint pts[3];
2453 			BRect rect;
2454 			for (int32 i = 0; i < 3; i++) {
2455 				link.Read<BPoint>(&(pts[i]));
2456 				fCurrentView->ConvertToScreenForDrawing(&pts[i]);
2457 			}
2458 			link.Read<BRect>(&rect);
2459 			BGradient* gradient;
2460 			if (link.ReadGradient(&gradient) != B_OK)
2461 				break;
2462 			fCurrentView->ConvertToScreenForDrawing(&rect);
2463 			fCurrentView->ConvertToScreenForDrawing(gradient);
2464 			drawingEngine->FillTriangle(pts, rect, *gradient);
2465 			break;
2466 		}
2467 		case AS_STROKE_POLYGON:
2468 		case AS_FILL_POLYGON:
2469 		{
2470 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_POLYGON\n",
2471 				Title()));
2472 
2473 			BRect polyFrame;
2474 			bool isClosed = true;
2475 			int32 pointCount;
2476 
2477 			link.Read<BRect>(&polyFrame);
2478 			if (code == AS_STROKE_POLYGON)
2479 				link.Read<bool>(&isClosed);
2480 			link.Read<int32>(&pointCount);
2481 
2482 			BPoint* pointList = new(nothrow) BPoint[pointCount];
2483 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK) {
2484 				for (int32 i = 0; i < pointCount; i++)
2485 					fCurrentView->ConvertToScreenForDrawing(&pointList[i]);
2486 				fCurrentView->ConvertToScreenForDrawing(&polyFrame);
2487 
2488 				drawingEngine->DrawPolygon(pointList, pointCount, polyFrame,
2489 					code == AS_FILL_POLYGON, isClosed && pointCount > 2);
2490 			}
2491 			delete[] pointList;
2492 			break;
2493 		}
2494 		case AS_FILL_POLYGON_GRADIENT:
2495 		{
2496 			DTRACE(("ServerWindow %s: Message AS_FILL_POLYGON_GRADIENT\n",
2497 				Title()));
2498 
2499 			BRect polyFrame;
2500 			bool isClosed = true;
2501 			int32 pointCount;
2502 			link.Read<BRect>(&polyFrame);
2503 			link.Read<int32>(&pointCount);
2504 
2505 			BPoint* pointList = new(nothrow) BPoint[pointCount];
2506 			BGradient* gradient;
2507 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK
2508 				&& link.ReadGradient(&gradient) >= B_OK) {
2509 				for (int32 i = 0; i < pointCount; i++)
2510 					fCurrentView->ConvertToScreenForDrawing(&pointList[i]);
2511 				fCurrentView->ConvertToScreenForDrawing(&polyFrame);
2512 				fCurrentView->ConvertToScreenForDrawing(gradient);
2513 
2514 				drawingEngine->FillPolygon(pointList, pointCount,
2515 					polyFrame, *gradient, isClosed && pointCount > 2);
2516 			}
2517 			delete[] pointList;
2518 			break;
2519 		}
2520 		case AS_STROKE_SHAPE:
2521 		case AS_FILL_SHAPE:
2522 		{
2523 			DTRACE(("ServerWindow %s: Message AS_STROKE/FILL_SHAPE\n",
2524 				Title()));
2525 
2526 			BRect shapeFrame;
2527 			int32 opCount;
2528 			int32 ptCount;
2529 
2530 			link.Read<BRect>(&shapeFrame);
2531 			link.Read<int32>(&opCount);
2532 			link.Read<int32>(&ptCount);
2533 
2534 			uint32* opList = new(nothrow) uint32[opCount];
2535 			BPoint* ptList = new(nothrow) BPoint[ptCount];
2536 			if (link.Read(opList, opCount * sizeof(uint32)) >= B_OK &&
2537 				link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK) {
2538 
2539 				// this might seem a bit weird, but under R5, the shapes
2540 				// are always offset by the current pen location
2541 				BPoint screenOffset
2542 					= fCurrentView->CurrentState()->PenLocation();
2543 				shapeFrame.OffsetBy(screenOffset);
2544 
2545 				fCurrentView->ConvertToScreenForDrawing(&screenOffset);
2546 				fCurrentView->ConvertToScreenForDrawing(&shapeFrame);
2547 
2548 				drawingEngine->DrawShape(shapeFrame, opCount, opList, ptCount,
2549 					ptList, code == AS_FILL_SHAPE, screenOffset,
2550 					fCurrentView->Scale());
2551 			}
2552 
2553 			delete[] opList;
2554 			delete[] ptList;
2555 			break;
2556 		}
2557 		case AS_FILL_SHAPE_GRADIENT:
2558 		{
2559 			DTRACE(("ServerWindow %s: Message AS_FILL_SHAPE_GRADIENT\n",
2560 				Title()));
2561 
2562 			BRect shapeFrame;
2563 			int32 opCount;
2564 			int32 ptCount;
2565 
2566 			link.Read<BRect>(&shapeFrame);
2567 			link.Read<int32>(&opCount);
2568 			link.Read<int32>(&ptCount);
2569 
2570 			uint32* opList = new(nothrow) uint32[opCount];
2571 			BPoint* ptList = new(nothrow) BPoint[ptCount];
2572 			BGradient* gradient;
2573 			if (link.Read(opList, opCount * sizeof(uint32)) >= B_OK
2574 				&& link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK
2575 				&& link.ReadGradient(&gradient) >= B_OK) {
2576 
2577 				// this might seem a bit weird, but under R5, the shapes
2578 				// are always offset by the current pen location
2579 				BPoint screenOffset
2580 					= fCurrentView->CurrentState()->PenLocation();
2581 				shapeFrame.OffsetBy(screenOffset);
2582 
2583 				fCurrentView->ConvertToScreenForDrawing(&screenOffset);
2584 				fCurrentView->ConvertToScreenForDrawing(&shapeFrame);
2585 				fCurrentView->ConvertToScreenForDrawing(gradient);
2586 				drawingEngine->FillShape(shapeFrame, opCount, opList,
2587 					ptCount, ptList, *gradient, screenOffset,
2588 					fCurrentView->Scale());
2589 			}
2590 
2591 			delete[] opList;
2592 			delete[] ptList;
2593 			break;
2594 		}
2595 		case AS_FILL_REGION:
2596 		{
2597 			DTRACE(("ServerWindow %s: Message AS_FILL_REGION\n", Title()));
2598 
2599 			BRegion region;
2600 			if (link.ReadRegion(&region) < B_OK)
2601 				break;
2602 
2603 			fCurrentView->ConvertToScreenForDrawing(&region);
2604 			drawingEngine->FillRegion(region);
2605 
2606 			break;
2607 		}
2608 		case AS_FILL_REGION_GRADIENT:
2609 		{
2610 			DTRACE(("ServerWindow %s: Message AS_FILL_REGION_GRADIENT\n",
2611 				Title()));
2612 
2613 			BRegion region;
2614 			link.ReadRegion(&region);
2615 
2616 			BGradient* gradient;
2617 			if (link.ReadGradient(&gradient) != B_OK)
2618 				break;
2619 
2620 			fCurrentView->ConvertToScreenForDrawing(&region);
2621 			fCurrentView->ConvertToScreenForDrawing(gradient);
2622 			drawingEngine->FillRegion(region, *gradient);
2623 			break;
2624 		}
2625 		case AS_STROKE_LINEARRAY:
2626 		{
2627 			DTRACE(("ServerWindow %s: Message AS_STROKE_LINEARRAY\n",
2628 				Title()));
2629 
2630 			// Attached Data:
2631 			// 1) int32 Number of lines in the array
2632 			// 2) LineArrayData
2633 
2634 			int32 lineCount;
2635 			if (link.Read<int32>(&lineCount) != B_OK || lineCount <= 0)
2636 				break;
2637 
2638 			// To speed things up, try to use a stack allocation and only
2639 			// fall back to the heap if there are enough lines...
2640 			ViewLineArrayInfo* lineData;
2641 			const int32 kStackBufferLineDataCount = 64;
2642 			ViewLineArrayInfo lineDataStackBuffer[kStackBufferLineDataCount];
2643 			if (lineCount > kStackBufferLineDataCount) {
2644 				lineData = new(std::nothrow) ViewLineArrayInfo[lineCount];
2645 				if (lineData == NULL)
2646 					break;
2647 			} else
2648 				lineData = lineDataStackBuffer;
2649 
2650 			// Read them all in one go
2651 			size_t dataSize = lineCount * sizeof(ViewLineArrayInfo);
2652 			if (link.Read(lineData, dataSize) != B_OK) {
2653 				if (lineData != lineDataStackBuffer)
2654 					delete[] lineData;
2655 				break;
2656 			}
2657 
2658 			// Convert to screen coords and draw
2659 			for (int32 i = 0; i < lineCount; i++) {
2660 				fCurrentView->ConvertToScreenForDrawing(
2661 					&lineData[i].startPoint);
2662 				fCurrentView->ConvertToScreenForDrawing(
2663 					&lineData[i].endPoint);
2664 			}
2665 			drawingEngine->StrokeLineArray(lineCount, lineData);
2666 
2667 			if (lineData != lineDataStackBuffer)
2668 				delete[] lineData;
2669 			break;
2670 		}
2671 		case AS_DRAW_STRING:
2672 		case AS_DRAW_STRING_WITH_DELTA:
2673 		{
2674 			ViewDrawStringInfo info;
2675 			if (link.Read<ViewDrawStringInfo>(&info) != B_OK
2676 				|| info.stringLength <= 0) {
2677 				break;
2678 			}
2679 
2680 			const ssize_t kMaxStackStringSize = 4096;
2681 			char stackString[kMaxStackStringSize];
2682 			char* string = stackString;
2683 			if (info.stringLength >= kMaxStackStringSize) {
2684 				// NOTE: Careful, the + 1 is for termination!
2685 				string = (char*)malloc((info.stringLength + 1 + 63) / 64 * 64);
2686 				if (string == NULL)
2687 					break;
2688 			}
2689 
2690 			escapement_delta* delta = NULL;
2691 			if (code == AS_DRAW_STRING_WITH_DELTA) {
2692 				// In this case, info.delta will contain valid values.
2693 				delta = &info.delta;
2694 			}
2695 
2696 			if (link.Read(string, info.stringLength) != B_OK) {
2697 				if (string != stackString)
2698 					free(string);
2699 				break;
2700 			}
2701 			// Terminate the string, if nothing else, it's important
2702 			// for the DTRACE call below...
2703 			string[info.stringLength] = '\0';
2704 
2705 			DTRACE(("ServerWindow %s: Message AS_DRAW_STRING, View: %s "
2706 				"-> %s\n", Title(), fCurrentView->Name(), string));
2707 
2708 			fCurrentView->ConvertToScreenForDrawing(&info.location);
2709 			BPoint penLocation = drawingEngine->DrawString(string,
2710 				info.stringLength, info.location, delta);
2711 
2712 			fCurrentView->ConvertFromScreenForDrawing(&penLocation);
2713 			fCurrentView->CurrentState()->SetPenLocation(penLocation);
2714 
2715 			if (string != stackString)
2716 				free(string);
2717 			break;
2718 		}
2719 		case AS_DRAW_STRING_WITH_OFFSETS:
2720 		{
2721 			int32 stringLength;
2722 			if (link.Read<int32>(&stringLength) != B_OK || stringLength <= 0)
2723 				break;
2724 
2725 			int32 glyphCount;
2726 			if (link.Read<int32>(&glyphCount) != B_OK || glyphCount <= 0)
2727 				break;
2728 
2729 			const ssize_t kMaxStackStringSize = 512;
2730 			char stackString[kMaxStackStringSize];
2731 			char* string = stackString;
2732 			BPoint stackLocations[kMaxStackStringSize];
2733 			BPoint* locations = stackLocations;
2734 			MemoryDeleter stringDeleter;
2735 			MemoryDeleter locationsDeleter;
2736 			if (stringLength >= kMaxStackStringSize) {
2737 				// NOTE: Careful, the + 1 is for termination!
2738 				string = (char*)malloc((stringLength + 1 + 63) / 64 * 64);
2739 				if (string == NULL)
2740 					break;
2741 				stringDeleter.SetTo(string);
2742 			}
2743 			if (glyphCount > kMaxStackStringSize) {
2744 				locations = (BPoint*)malloc(
2745 					((glyphCount * sizeof(BPoint)) + 63) / 64 * 64);
2746 				if (locations == NULL)
2747 					break;
2748 				locationsDeleter.SetTo(locations);
2749 			}
2750 
2751 			if (link.Read(string, stringLength) != B_OK)
2752 				break;
2753 			// Count UTF8 glyphs and make sure we have enough locations
2754 			if ((int32)UTF8CountChars(string, stringLength) > glyphCount)
2755 				break;
2756 			if (link.Read(locations, glyphCount * sizeof(BPoint)) != B_OK)
2757 				break;
2758 			// Terminate the string, if nothing else, it's important
2759 			// for the DTRACE call below...
2760 			string[stringLength] = '\0';
2761 
2762 			DTRACE(("ServerWindow %s: Message AS_DRAW_STRING_WITH_OFFSETS, View: %s "
2763 				"-> %s\n", Title(), fCurrentView->Name(), string));
2764 
2765 			for (int32 i = 0; i < stringLength; i++)
2766 				fCurrentView->ConvertToScreenForDrawing(&locations[i]);
2767 
2768 			BPoint penLocation = drawingEngine->DrawString(string,
2769 				stringLength, locations);
2770 
2771 			fCurrentView->ConvertFromScreenForDrawing(&penLocation);
2772 			fCurrentView->CurrentState()->SetPenLocation(penLocation);
2773 
2774 			break;
2775 		}
2776 
2777 		case AS_VIEW_DRAW_PICTURE:
2778 		{
2779 			int32 token;
2780 			link.Read<int32>(&token);
2781 
2782 			BPoint where;
2783 			if (link.Read<BPoint>(&where) == B_OK) {
2784 				ServerPicture* picture = App()->GetPicture(token);
2785 				if (picture != NULL) {
2786 					// Setting the drawing origin outside of the
2787 					// state makes sure that everything the picture
2788 					// does is relative to the global picture offset.
2789 					fCurrentView->PushState();
2790 					fCurrentView->SetDrawingOrigin(where);
2791 
2792 					fCurrentView->PushState();
2793 					picture->Play(fCurrentView);
2794 					fCurrentView->PopState();
2795 
2796 					fCurrentView->PopState();
2797 
2798 					picture->ReleaseReference();
2799 				}
2800 			}
2801 			break;
2802 		}
2803 
2804 		default:
2805 			BString codeString;
2806 			string_for_message_code(code, codeString);
2807 			debug_printf("ServerWindow %s received unexpected code: %s\n",
2808 				Title(), codeString.String());
2809 
2810 			if (link.NeedsReply()) {
2811 				// the client is now blocking and waiting for a reply!
2812 				fLink.StartMessage(B_ERROR);
2813 				fLink.Flush();
2814 			}
2815 			break;
2816 	}
2817 
2818 	drawingEngine->UnlockParallelAccess();
2819 }
2820 
2821 
2822 bool
2823 ServerWindow::_DispatchPictureMessage(int32 code, BPrivate::LinkReceiver& link)
2824 {
2825 	ServerPicture* picture = fCurrentView->Picture();
2826 	if (picture == NULL)
2827 		return false;
2828 
2829 	switch (code) {
2830 		case AS_VIEW_SET_ORIGIN:
2831 		{
2832 			float x, y;
2833 			link.Read<float>(&x);
2834 			link.Read<float>(&y);
2835 
2836 			picture->WriteSetOrigin(BPoint(x, y));
2837 			break;
2838 		}
2839 
2840 		case AS_VIEW_INVERT_RECT:
2841 		{
2842 			BRect rect;
2843 			link.Read<BRect>(&rect);
2844 			picture->WriteInvertRect(rect);
2845 			break;
2846 		}
2847 
2848 		case AS_VIEW_PUSH_STATE:
2849 		{
2850 			picture->WritePushState();
2851 			break;
2852 		}
2853 
2854 		case AS_VIEW_POP_STATE:
2855 		{
2856 			picture->WritePopState();
2857 			break;
2858 		}
2859 
2860 		case AS_VIEW_SET_DRAWING_MODE:
2861 		{
2862 			int8 drawingMode;
2863 			link.Read<int8>(&drawingMode);
2864 
2865 			picture->WriteSetDrawingMode((drawing_mode)drawingMode);
2866 
2867 			fCurrentView->CurrentState()->SetDrawingMode(
2868 				(drawing_mode)drawingMode);
2869 			fWindow->GetDrawingEngine()->SetDrawingMode(
2870 				(drawing_mode)drawingMode);
2871 			break;
2872 		}
2873 
2874 		case AS_VIEW_SET_PEN_LOC:
2875 		{
2876 			BPoint location;
2877 			link.Read<BPoint>(&location);
2878 			picture->WriteSetPenLocation(location);
2879 
2880 			fCurrentView->CurrentState()->SetPenLocation(location);
2881 			break;
2882 		}
2883 		case AS_VIEW_SET_PEN_SIZE:
2884 		{
2885 			float penSize;
2886 			link.Read<float>(&penSize);
2887 			picture->WriteSetPenSize(penSize);
2888 
2889 			fCurrentView->CurrentState()->SetPenSize(penSize);
2890 			fWindow->GetDrawingEngine()->SetPenSize(
2891 				fCurrentView->CurrentState()->PenSize());
2892 			break;
2893 		}
2894 
2895 		case AS_VIEW_SET_LINE_MODE:
2896 		{
2897 
2898 			ViewSetLineModeInfo info;
2899 			link.Read<ViewSetLineModeInfo>(&info);
2900 
2901 			picture->WriteSetLineMode(info.lineCap, info.lineJoin,
2902 				info.miterLimit);
2903 
2904 			fCurrentView->CurrentState()->SetLineCapMode(info.lineCap);
2905 			fCurrentView->CurrentState()->SetLineJoinMode(info.lineJoin);
2906 			fCurrentView->CurrentState()->SetMiterLimit(info.miterLimit);
2907 
2908 			fWindow->GetDrawingEngine()->SetStrokeMode(info.lineCap,
2909 				info.lineJoin, info.miterLimit);
2910 			break;
2911 		}
2912 		case AS_VIEW_SET_SCALE:
2913 		{
2914 			float scale;
2915 			link.Read<float>(&scale);
2916 			picture->WriteSetScale(scale);
2917 
2918 			fCurrentView->SetScale(scale);
2919 			_UpdateDrawState(fCurrentView);
2920 			break;
2921 		}
2922 
2923 		case AS_VIEW_SET_PATTERN:
2924 		{
2925 			pattern pat;
2926 			link.Read(&pat, sizeof(pattern));
2927 			picture->WriteSetPattern(pat);
2928 			break;
2929 		}
2930 
2931 		case AS_VIEW_SET_FONT_STATE:
2932 		{
2933 			picture->SetFontFromLink(link);
2934 			break;
2935 		}
2936 
2937 		case AS_FILL_RECT:
2938 		case AS_STROKE_RECT:
2939 		{
2940 			BRect rect;
2941 			link.Read<BRect>(&rect);
2942 
2943 			picture->WriteDrawRect(rect, code == AS_FILL_RECT);
2944 			break;
2945 		}
2946 
2947 		case AS_FILL_REGION:
2948 		{
2949 			// There is no B_PIC_FILL_REGION op, we have to
2950 			// implement it using B_PIC_FILL_RECT
2951 			BRegion region;
2952 			if (link.ReadRegion(&region) < B_OK)
2953 				break;
2954 			for (int32 i = 0; i < region.CountRects(); i++)
2955 				picture->WriteDrawRect(region.RectAt(i), true);
2956 			break;
2957 		}
2958 
2959 		case AS_STROKE_ROUNDRECT:
2960 		case AS_FILL_ROUNDRECT:
2961 		{
2962 			BRect rect;
2963 			link.Read<BRect>(&rect);
2964 
2965 			BPoint radii;
2966 			link.Read<float>(&radii.x);
2967 			link.Read<float>(&radii.y);
2968 
2969 			picture->WriteDrawRoundRect(rect, radii, code == AS_FILL_ROUNDRECT);
2970 			break;
2971 		}
2972 
2973 		case AS_STROKE_ELLIPSE:
2974 		case AS_FILL_ELLIPSE:
2975 		{
2976 			BRect rect;
2977 			link.Read<BRect>(&rect);
2978 			picture->WriteDrawEllipse(rect, code == AS_FILL_ELLIPSE);
2979 			break;
2980 		}
2981 
2982 		case AS_STROKE_ARC:
2983 		case AS_FILL_ARC:
2984 		{
2985 			BRect rect;
2986 			link.Read<BRect>(&rect);
2987 			float startTheta, arcTheta;
2988 			link.Read<float>(&startTheta);
2989 			link.Read<float>(&arcTheta);
2990 
2991 			BPoint radii((rect.Width() + 1) / 2, (rect.Height() + 1) / 2);
2992 			BPoint center = rect.LeftTop() + radii;
2993 
2994 			picture->WriteDrawArc(center, radii, startTheta, arcTheta,
2995 				code == AS_FILL_ARC);
2996 			break;
2997 		}
2998 
2999 		case AS_STROKE_TRIANGLE:
3000 		case AS_FILL_TRIANGLE:
3001 		{
3002 			// There is no B_PIC_FILL/STROKE_TRIANGLE op,
3003 			// we implement it using B_PIC_FILL/STROKE_POLYGON
3004 			BPoint points[3];
3005 
3006 			for (int32 i = 0; i < 3; i++) {
3007 				link.Read<BPoint>(&(points[i]));
3008 			}
3009 
3010 			BRect rect;
3011 			link.Read<BRect>(&rect);
3012 
3013 			picture->WriteDrawPolygon(3, points,
3014 					true, code == AS_FILL_TRIANGLE);
3015 			break;
3016 		}
3017 		case AS_STROKE_POLYGON:
3018 		case AS_FILL_POLYGON:
3019 		{
3020 			BRect polyFrame;
3021 			bool isClosed = true;
3022 			int32 pointCount;
3023 			const bool fill = (code == AS_FILL_POLYGON);
3024 
3025 			link.Read<BRect>(&polyFrame);
3026 			if (code == AS_STROKE_POLYGON)
3027 				link.Read<bool>(&isClosed);
3028 			link.Read<int32>(&pointCount);
3029 
3030 			BPoint* pointList = new(nothrow) BPoint[pointCount];
3031 			if (link.Read(pointList, pointCount * sizeof(BPoint)) >= B_OK) {
3032 				picture->WriteDrawPolygon(pointCount, pointList,
3033 					isClosed && pointCount > 2, fill);
3034 			}
3035 			delete[] pointList;
3036 			break;
3037 		}
3038 
3039 		case AS_STROKE_BEZIER:
3040 		case AS_FILL_BEZIER:
3041 		{
3042 			BPoint points[4];
3043 			for (int32 i = 0; i < 4; i++) {
3044 				link.Read<BPoint>(&(points[i]));
3045 			}
3046 			picture->WriteDrawBezier(points, code == AS_FILL_BEZIER);
3047 			break;
3048 		}
3049 
3050 		case AS_STROKE_LINE:
3051 		{
3052 			ViewStrokeLineInfo info;
3053 			link.Read<ViewStrokeLineInfo>(&info);
3054 
3055 			picture->WriteStrokeLine(info.startPoint, info.endPoint);
3056 			break;
3057 		}
3058 
3059 		case AS_STROKE_LINEARRAY:
3060 		{
3061 			int32 lineCount;
3062 			if (link.Read<int32>(&lineCount) != B_OK || lineCount <= 0)
3063 				break;
3064 
3065 			// To speed things up, try to use a stack allocation and only
3066 			// fall back to the heap if there are enough lines...
3067 			ViewLineArrayInfo* lineData;
3068 			const int32 kStackBufferLineDataCount = 64;
3069 			ViewLineArrayInfo lineDataStackBuffer[kStackBufferLineDataCount];
3070 			if (lineCount > kStackBufferLineDataCount) {
3071 				lineData = new(std::nothrow) ViewLineArrayInfo[lineCount];
3072 				if (lineData == NULL)
3073 					break;
3074 			} else
3075 				lineData = lineDataStackBuffer;
3076 
3077 			// Read them all in one go
3078 			size_t dataSize = lineCount * sizeof(ViewLineArrayInfo);
3079 			if (link.Read(lineData, dataSize) != B_OK) {
3080 				if (lineData != lineDataStackBuffer)
3081 					delete[] lineData;
3082 				break;
3083 			}
3084 
3085 			picture->WritePushState();
3086 
3087 			for (int32 i = 0; i < lineCount; i++) {
3088 				picture->WriteSetHighColor(lineData[i].color);
3089 				picture->WriteStrokeLine(lineData[i].startPoint,
3090 					lineData[i].endPoint);
3091 			}
3092 
3093 			picture->WritePopState();
3094 
3095 			if (lineData != lineDataStackBuffer)
3096 				delete[] lineData;
3097 			break;
3098 		}
3099 
3100 		case AS_VIEW_SET_LOW_COLOR:
3101 		case AS_VIEW_SET_HIGH_COLOR:
3102 		{
3103 			rgb_color color;
3104 			link.Read(&color, sizeof(rgb_color));
3105 
3106 			if (code == AS_VIEW_SET_HIGH_COLOR) {
3107 				picture->WriteSetHighColor(color);
3108 				fCurrentView->CurrentState()->SetHighColor(color);
3109 				fWindow->GetDrawingEngine()->SetHighColor(color);
3110 			} else {
3111 				picture->WriteSetLowColor(color);
3112 				fCurrentView->CurrentState()->SetLowColor(color);
3113 				fWindow->GetDrawingEngine()->SetLowColor(color);
3114 			}
3115 		}	break;
3116 
3117 		case AS_DRAW_STRING:
3118 		case AS_DRAW_STRING_WITH_DELTA:
3119 		{
3120 			ViewDrawStringInfo info;
3121 			if (link.Read<ViewDrawStringInfo>(&info) != B_OK)
3122 				break;
3123 
3124 			char* string = (char*)malloc(info.stringLength + 1);
3125 			if (string == NULL)
3126 				break;
3127 
3128 			if (code != AS_DRAW_STRING_WITH_DELTA) {
3129 				// In this case, info.delta will NOT contain valid values.
3130 				info.delta = (escapement_delta){ 0, 0 };
3131 			}
3132 
3133 			if (link.Read(string, info.stringLength) != B_OK) {
3134 				free(string);
3135 				break;
3136 			}
3137 			// Terminate the string
3138 			string[info.stringLength] = '\0';
3139 
3140 			picture->WriteDrawString(info.location, string, info.stringLength,
3141 				info.delta);
3142 
3143 			free(string);
3144 			break;
3145 		}
3146 
3147 		case AS_STROKE_SHAPE:
3148 		case AS_FILL_SHAPE:
3149 		{
3150 			BRect shapeFrame;
3151 			int32 opCount;
3152 			int32 ptCount;
3153 
3154 			link.Read<BRect>(&shapeFrame);
3155 			link.Read<int32>(&opCount);
3156 			link.Read<int32>(&ptCount);
3157 
3158 			uint32* opList = new(std::nothrow) uint32[opCount];
3159 			BPoint* ptList = new(std::nothrow) BPoint[ptCount];
3160 			if (opList != NULL && ptList != NULL
3161 				&& link.Read(opList, opCount * sizeof(uint32)) >= B_OK
3162 				&& link.Read(ptList, ptCount * sizeof(BPoint)) >= B_OK) {
3163 				// This might seem a bit weird, but under BeOS, the shapes
3164 				// are always offset by the current pen location
3165 				BPoint penLocation
3166 					= fCurrentView->CurrentState()->PenLocation();
3167 				for (int32 i = 0; i < ptCount; i++) {
3168 					ptList[i] += penLocation;
3169 				}
3170 				const bool fill = (code == AS_FILL_SHAPE);
3171 				picture->WriteDrawShape(opCount, opList, ptCount, ptList, fill);
3172 			}
3173 
3174 			delete[] opList;
3175 			delete[] ptList;
3176 			break;
3177 		}
3178 
3179 		case AS_VIEW_DRAW_BITMAP:
3180 		{
3181 			ViewDrawBitmapInfo info;
3182 			link.Read<ViewDrawBitmapInfo>(&info);
3183 
3184 			ServerBitmap* bitmap = App()->GetBitmap(info.bitmapToken);
3185 			if (bitmap == NULL)
3186 				break;
3187 
3188 			picture->WriteDrawBitmap(info.bitmapRect, info.viewRect,
3189 				bitmap->Width(), bitmap->Height(), bitmap->BytesPerRow(),
3190 				bitmap->ColorSpace(), info.options, bitmap->Bits(),
3191 				bitmap->BitsLength());
3192 
3193 			bitmap->ReleaseReference();
3194 			break;
3195 		}
3196 
3197 		case AS_VIEW_DRAW_PICTURE:
3198 		{
3199 			int32 token;
3200 			link.Read<int32>(&token);
3201 
3202 			BPoint where;
3203 			if (link.Read<BPoint>(&where) == B_OK) {
3204 				ServerPicture* pictureToDraw = App()->GetPicture(token);
3205 				if (pictureToDraw != NULL) {
3206 					// We need to make a copy of the picture, since it can
3207 					// change after it has been drawn
3208 					ServerPicture* copy = App()->CreatePicture(pictureToDraw);
3209 					picture->NestPicture(copy);
3210 					picture->WriteDrawPicture(where, copy->Token());
3211 
3212 					pictureToDraw->ReleaseReference();
3213 				}
3214 			}
3215 			break;
3216 		}
3217 
3218 		case AS_VIEW_SET_CLIP_REGION:
3219 		{
3220 			int32 rectCount;
3221 			status_t status = link.Read<int32>(&rectCount);
3222 				// a negative count means no
3223 				// region for the current draw state,
3224 				// but an *empty* region is actually valid!
3225 				// even if it means no drawing is allowed
3226 
3227 			if (status < B_OK)
3228 				break;
3229 
3230 			if (rectCount >= 0) {
3231 				// we are supposed to set the clipping region
3232 				BRegion region;
3233 				if (rectCount > 0 && link.ReadRegion(&region) < B_OK)
3234 					break;
3235 				picture->WriteSetClipping(region);
3236 			} else {
3237 				// we are supposed to clear the clipping region
3238 				picture->WriteClearClipping();
3239 			}
3240 			break;
3241 		}
3242 
3243 		case AS_VIEW_BEGIN_PICTURE:
3244 		{
3245 			ServerPicture* newPicture = App()->CreatePicture();
3246 			if (newPicture != NULL) {
3247 				newPicture->PushPicture(picture);
3248 				newPicture->SyncState(fCurrentView);
3249 				fCurrentView->SetPicture(newPicture);
3250 			}
3251 			break;
3252 		}
3253 
3254 		case AS_VIEW_APPEND_TO_PICTURE:
3255 		{
3256 			int32 token;
3257 			link.Read<int32>(&token);
3258 
3259 			ServerPicture* appendPicture = App()->GetPicture(token);
3260 			if (appendPicture != NULL) {
3261 				//picture->SyncState(fCurrentView);
3262 				appendPicture->AppendPicture(picture);
3263 			}
3264 
3265 			fCurrentView->SetPicture(appendPicture);
3266 
3267 			if (appendPicture != NULL)
3268 				appendPicture->ReleaseReference();
3269 			break;
3270 		}
3271 
3272 		case AS_VIEW_END_PICTURE:
3273 		{
3274 			ServerPicture* poppedPicture = picture->PopPicture();
3275 			fCurrentView->SetPicture(poppedPicture);
3276 			if (poppedPicture != NULL)
3277 				poppedPicture->ReleaseReference();
3278 
3279 			fLink.StartMessage(B_OK);
3280 			fLink.Attach<int32>(picture->Token());
3281 			fLink.Flush();
3282 			return true;
3283 		}
3284 /*
3285 		case AS_VIEW_SET_BLENDING_MODE:
3286 		{
3287 			ViewBlendingModeInfo info;
3288 			link.Read<ViewBlendingModeInfo>(&info);
3289 
3290 			picture->BeginOp(B_PIC_SET_BLENDING_MODE);
3291 			picture->AddInt16((int16)info.sourceAlpha);
3292 			picture->AddInt16((int16)info.alphaFunction);
3293 			picture->EndOp();
3294 
3295 			fCurrentView->CurrentState()->SetBlendingMode(info.sourceAlpha,
3296 				info.alphaFunction);
3297 			fWindow->GetDrawingEngine()->SetBlendingMode(info.sourceAlpha,
3298 				info.alphaFunction);
3299 			break;
3300 		}*/
3301 		default:
3302 			return false;
3303 	}
3304 
3305 	if (link.NeedsReply()) {
3306 		fLink.StartMessage(B_ERROR);
3307 		fLink.Flush();
3308 	}
3309 	return true;
3310 }
3311 
3312 
3313 /*!	\brief Message-dispatching loop for the ServerWindow
3314 
3315 	Watches the ServerWindow's message port and dispatches as necessary
3316 */
3317 void
3318 ServerWindow::_MessageLooper()
3319 {
3320 	// Send a reply to our window - it is expecting fMessagePort
3321 	// port and some other info.
3322 
3323 	fLink.StartMessage(B_OK);
3324 	fLink.Attach<port_id>(fMessagePort);
3325 
3326 	int32 minWidth, maxWidth, minHeight, maxHeight;
3327 	fWindow->GetSizeLimits(&minWidth, &maxWidth, &minHeight, &maxHeight);
3328 
3329 	fLink.Attach<BRect>(fWindow->Frame());
3330 	fLink.Attach<float>((float)minWidth);
3331 	fLink.Attach<float>((float)maxWidth);
3332 	fLink.Attach<float>((float)minHeight);
3333 	fLink.Attach<float>((float)maxHeight);
3334 	fLink.Flush();
3335 
3336 	BPrivate::LinkReceiver& receiver = fLink.Receiver();
3337 	bool quitLoop = false;
3338 
3339 	while (!quitLoop) {
3340 		//STRACE(("info: ServerWindow::MonitorWin listening on port %ld.\n",
3341 		//	fMessagePort));
3342 
3343 		int32 code;
3344 		status_t status = receiver.GetNextMessage(code);
3345 		if (status != B_OK) {
3346 			// that shouldn't happen, it's our port
3347 			printf("Someone deleted our message port!\n");
3348 
3349 			// try to let our client die happily
3350 			NotifyQuitRequested();
3351 			break;
3352 		}
3353 
3354 #ifdef PROFILE_MESSAGE_LOOP
3355 		bigtime_t start = system_time();
3356 #endif
3357 
3358 		Lock();
3359 
3360 #ifdef PROFILE_MESSAGE_LOOP
3361 		bigtime_t diff = system_time() - start;
3362 		if (diff > 10000) {
3363 			printf("ServerWindow %s: lock acquisition took %Ld usecs\n",
3364 				Title(), diff);
3365 		}
3366 #endif
3367 
3368 		int32 messagesProcessed = 0;
3369 		bigtime_t processingStart = system_time();
3370 		bool lockedDesktop = false;
3371 		bool needsAllWindowsLocked = false;
3372 
3373 		while (true) {
3374 			if (code == AS_DELETE_WINDOW || code == kMsgQuitLooper) {
3375 				// this means the client has been killed
3376 				DTRACE(("ServerWindow %s received 'AS_DELETE_WINDOW' message "
3377 					"code\n", Title()));
3378 
3379 				if (code == AS_DELETE_WINDOW) {
3380 					fLink.StartMessage(B_OK);
3381 					fLink.Flush();
3382 				}
3383 
3384 				if (lockedDesktop)
3385 					fDesktop->UnlockSingleWindow();
3386 
3387 				quitLoop = true;
3388 
3389 				// ServerWindow's destructor takes care of pulling this object
3390 				// off the desktop.
3391 				ASSERT(fWindow->IsHidden());
3392 				break;
3393 			}
3394 
3395 			needsAllWindowsLocked = _MessageNeedsAllWindowsLocked(code);
3396 
3397 			if (!lockedDesktop && !needsAllWindowsLocked) {
3398 				// only lock it once
3399 				fDesktop->LockSingleWindow();
3400 				lockedDesktop = true;
3401 			} else if (lockedDesktop && !needsAllWindowsLocked) {
3402 				// nothing to do
3403 			} else if (needsAllWindowsLocked) {
3404 				if (lockedDesktop) {
3405 					// unlock single before locking all
3406 					fDesktop->UnlockSingleWindow();
3407 					lockedDesktop = false;
3408 				}
3409 				fDesktop->LockAllWindows();
3410 			}
3411 
3412 			if (atomic_and(&fRedrawRequested, 0) != 0) {
3413 #ifdef PROFILE_MESSAGE_LOOP
3414 				bigtime_t redrawStart = system_time();
3415 #endif
3416 				fWindow->RedrawDirtyRegion();
3417 #ifdef PROFILE_MESSAGE_LOOP
3418 				diff = system_time() - redrawStart;
3419 				atomic_add(&sRedrawProcessingTime.count, 1);
3420 # ifndef HAIKU_TARGET_PLATFORM_LIBBE_TEST
3421 				atomic_add64(&sRedrawProcessingTime.time, diff);
3422 # else
3423 				sRedrawProcessingTime.time += diff;
3424 # endif
3425 #endif
3426 			}
3427 
3428 #ifdef PROFILE_MESSAGE_LOOP
3429 			bigtime_t dispatchStart = system_time();
3430 #endif
3431 			_DispatchMessage(code, receiver);
3432 
3433 #ifdef PROFILE_MESSAGE_LOOP
3434 			if (code >= 0 && code < AS_LAST_CODE) {
3435 				diff = system_time() - dispatchStart;
3436 				atomic_add(&sMessageProfile[code].count, 1);
3437 #ifndef HAIKU_TARGET_PLATFORM_LIBBE_TEST
3438 				atomic_add64(&sMessageProfile[code].time, diff);
3439 #else
3440 				sMessageProfile[code].time += diff;
3441 #endif
3442 				if (diff > 10000) {
3443 					printf("ServerWindow %s: message %ld took %Ld usecs\n",
3444 						Title(), code, diff);
3445 				}
3446 			}
3447 #endif
3448 
3449 			if (needsAllWindowsLocked)
3450 				fDesktop->UnlockAllWindows();
3451 
3452 			// Only process up to 70 waiting messages at once (we have the
3453 			// Desktop locked), but don't hold the lock longer than 10 ms
3454 			if (!receiver.HasMessages() || ++messagesProcessed > 70
3455 				|| system_time() - processingStart > 10000) {
3456 				if (lockedDesktop)
3457 					fDesktop->UnlockSingleWindow();
3458 				break;
3459 			}
3460 
3461 			// next message
3462 			status_t status = receiver.GetNextMessage(code);
3463 			if (status != B_OK) {
3464 				// that shouldn't happen, it's our port
3465 				printf("Someone deleted our message port!\n");
3466 				if (lockedDesktop)
3467 					fDesktop->UnlockSingleWindow();
3468 
3469 				// try to let our client die happily
3470 				NotifyQuitRequested();
3471 				break;
3472 			}
3473 		}
3474 
3475 		Unlock();
3476 	}
3477 
3478 	// We were asked to quit the message loop - either on request or because of
3479 	// an error.
3480 	Quit();
3481 		// does not return
3482 }
3483 
3484 
3485 void
3486 ServerWindow::ScreenChanged(const BMessage* message)
3487 {
3488 	SendMessageToClient(message);
3489 
3490 	if (fDirectWindowInfo != NULL && fDirectWindowInfo->IsFullScreen())
3491 		_ResizeToFullScreen();
3492 }
3493 
3494 
3495 status_t
3496 ServerWindow::SendMessageToClient(const BMessage* msg, int32 target) const
3497 {
3498 	if (target == B_NULL_TOKEN)
3499 		target = fClientToken;
3500 
3501 	BMessenger reply;
3502 	BMessage::Private messagePrivate((BMessage*)msg);
3503 	return messagePrivate.SendMessage(fClientLooperPort, fClientTeam, target,
3504 		0, false, reply);
3505 }
3506 
3507 
3508 Window*
3509 ServerWindow::MakeWindow(BRect frame, const char* name,
3510 	window_look look, window_feel feel, uint32 flags, uint32 workspace)
3511 {
3512 	// The non-offscreen ServerWindow uses the DrawingEngine instance from
3513 	// the desktop.
3514 	return new(std::nothrow) ::Window(frame, name, look, feel, flags,
3515 		workspace, this, fDesktop->HWInterface()->CreateDrawingEngine());
3516 }
3517 
3518 
3519 void
3520 ServerWindow::HandleDirectConnection(int32 bufferState, int32 driverState)
3521 {
3522 	ASSERT_MULTI_LOCKED(fDesktop->WindowLocker());
3523 
3524 	if (fDirectWindowInfo == NULL)
3525 		return;
3526 
3527 	STRACE(("HandleDirectConnection(bufferState = %ld, driverState = %ld)\n",
3528 		bufferState, driverState));
3529 
3530 	status_t status = fDirectWindowInfo->SetState(
3531 		(direct_buffer_state)bufferState, (direct_driver_state)driverState,
3532 		fDesktop->HWInterface()->FrontBuffer(), fWindow->Frame(),
3533 		fWindow->VisibleContentRegion());
3534 
3535 	if (status != B_OK) {
3536 		char errorString[256];
3537 		snprintf(errorString, sizeof(errorString),
3538 			"%s killed for a problem in DirectConnected(): %s",
3539 			App()->Signature(), strerror(status));
3540 		syslog(LOG_ERR, errorString);
3541 
3542 		// The client application didn't release the semaphore
3543 		// within the given timeout. Or something else went wrong.
3544 		// Deleting this member should make it crash.
3545 		delete fDirectWindowInfo;
3546 		fDirectWindowInfo = NULL;
3547 	} else if ((bufferState & B_DIRECT_MODE_MASK) == B_DIRECT_START)
3548 		fIsDirectlyAccessing = true;
3549 	else if ((bufferState & B_DIRECT_MODE_MASK) == B_DIRECT_STOP)
3550 		fIsDirectlyAccessing = false;
3551 }
3552 
3553 
3554 void
3555 ServerWindow::_SetCurrentView(View* view)
3556 {
3557 	if (fCurrentView == view)
3558 		return;
3559 
3560 	fCurrentView = view;
3561 	fCurrentDrawingRegionValid = false;
3562 	_UpdateDrawState(fCurrentView);
3563 
3564 #if 0
3565 #if DELAYED_BACKGROUND_CLEARING
3566 	if (fCurrentView && fCurrentView->IsBackgroundDirty()
3567 		&& fWindow->InUpdate()) {
3568 		DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
3569 		if (drawingEngine->LockParallelAccess()) {
3570 			fWindow->GetEffectiveDrawingRegion(fCurrentView,
3571 				fCurrentDrawingRegion);
3572 			fCurrentDrawingRegionValid = true;
3573 			BRegion dirty(fCurrentDrawingRegion);
3574 
3575 			BRegion content;
3576 			fWindow->GetContentRegion(&content);
3577 
3578 			fCurrentView->Draw(drawingEngine, &dirty, &content, false);
3579 
3580 			drawingEngine->UnlockParallelAccess();
3581 		}
3582 	}
3583 #endif
3584 #endif // 0
3585 }
3586 
3587 
3588 void
3589 ServerWindow::_UpdateDrawState(View* view)
3590 {
3591 	// switch the drawing state
3592 	// TODO: is it possible to scroll a view while it
3593 	// is being drawn? probably not... otherwise the
3594 	// "offsets" passed below would need to be updated again
3595 	DrawingEngine* drawingEngine = fWindow->GetDrawingEngine();
3596 	if (view && drawingEngine) {
3597 		BPoint leftTop(0, 0);
3598 		view->ConvertToScreenForDrawing(&leftTop);
3599 		drawingEngine->SetDrawState(view->CurrentState(), leftTop.x, leftTop.y);
3600 	}
3601 }
3602 
3603 
3604 void
3605 ServerWindow::_UpdateCurrentDrawingRegion()
3606 {
3607 	if (!fCurrentDrawingRegionValid
3608 		|| fWindow->DrawingRegionChanged(fCurrentView)) {
3609 		fWindow->GetEffectiveDrawingRegion(fCurrentView, fCurrentDrawingRegion);
3610 		fCurrentDrawingRegionValid = true;
3611 	}
3612 }
3613 
3614 
3615 bool
3616 ServerWindow::_MessageNeedsAllWindowsLocked(uint32 code) const
3617 {
3618 	switch (code) {
3619 		case AS_SET_WINDOW_TITLE:
3620 		case AS_ADD_TO_SUBSET:
3621 		case AS_REMOVE_FROM_SUBSET:
3622 		case AS_VIEW_CREATE_ROOT:
3623 		case AS_VIEW_CREATE:
3624 		case AS_SEND_BEHIND:
3625 		case AS_SET_LOOK:
3626 		case AS_SET_FEEL:
3627 		case AS_SET_FLAGS:
3628 		case AS_SET_WORKSPACES:
3629 		case AS_WINDOW_MOVE:
3630 		case AS_WINDOW_RESIZE:
3631 		case AS_SET_SIZE_LIMITS:
3632 		case AS_SYSTEM_FONT_CHANGED:
3633 		case AS_SET_DECORATOR_SETTINGS:
3634 		case AS_GET_MOUSE:
3635 		case AS_DIRECT_WINDOW_SET_FULLSCREEN:
3636 //		case AS_VIEW_SET_EVENT_MASK:
3637 //		case AS_VIEW_SET_MOUSE_EVENT_MASK:
3638 			return true;
3639 		default:
3640 			return false;
3641 	}
3642 }
3643 
3644 
3645 void
3646 ServerWindow::_ResizeToFullScreen()
3647 {
3648 	BRect screenFrame;
3649 
3650 	{
3651 		AutoReadLocker _(fDesktop->ScreenLocker());
3652 		const Screen* screen = fWindow->Screen();
3653 		if (screen == NULL)
3654 			return;
3655 
3656 		screenFrame = fWindow->Screen()->Frame();
3657 	}
3658 
3659 	fDesktop->MoveWindowBy(fWindow,
3660 		screenFrame.left - fWindow->Frame().left,
3661 		screenFrame.top - fWindow->Frame().top);
3662 	fDesktop->ResizeWindowBy(fWindow,
3663 		screenFrame.Width() - fWindow->Frame().Width(),
3664 		screenFrame.Height() - fWindow->Frame().Height());
3665 }
3666 
3667 
3668 status_t
3669 ServerWindow::_EnableDirectWindowMode()
3670 {
3671 	if (fDirectWindowInfo != NULL) {
3672 		// already in direct window mode
3673 		return B_ERROR;
3674 	}
3675 
3676 	if (fDesktop->HWInterface()->FrontBuffer() == NULL) {
3677 		// direct window mode not supported
3678 		return B_UNSUPPORTED;
3679 	}
3680 
3681 	fDirectWindowInfo = new(std::nothrow) DirectWindowInfo;
3682 	if (fDirectWindowInfo == NULL)
3683 		return B_NO_MEMORY;
3684 
3685 	status_t status = fDirectWindowInfo->InitCheck();
3686 	if (status != B_OK) {
3687 		delete fDirectWindowInfo;
3688 		fDirectWindowInfo = NULL;
3689 
3690 		return status;
3691 	}
3692 
3693 	return B_OK;
3694 }
3695 
3696 
3697 void
3698 ServerWindow::_DirectWindowSetFullScreen(bool enable)
3699 {
3700 	window_feel feel = kWindowScreenFeel;
3701 
3702 	if (enable) {
3703 		fDesktop->HWInterface()->SetCursorVisible(false);
3704 
3705 		fDirectWindowInfo->EnableFullScreen(fWindow->Frame(), fWindow->Feel());
3706 		_ResizeToFullScreen();
3707 	} else {
3708 		const BRect& originalFrame = fDirectWindowInfo->OriginalFrame();
3709 
3710 		fDirectWindowInfo->DisableFullScreen();
3711 
3712 		// Resize window back to its original size
3713 		fDesktop->MoveWindowBy(fWindow,
3714 			originalFrame.left - fWindow->Frame().left,
3715 			originalFrame.top - fWindow->Frame().top);
3716 		fDesktop->ResizeWindowBy(fWindow,
3717 			originalFrame.Width() - fWindow->Frame().Width(),
3718 			originalFrame.Height() - fWindow->Frame().Height());
3719 
3720 		fDesktop->HWInterface()->SetCursorVisible(true);
3721 	}
3722 
3723 	fDesktop->SetWindowFeel(fWindow, feel);
3724 }
3725 
3726 
3727 status_t
3728 ServerWindow::PictureToRegion(ServerPicture* picture, BRegion& region,
3729 	bool inverse, BPoint where)
3730 {
3731 	fprintf(stderr, "ServerWindow::PictureToRegion() not implemented\n");
3732 	region.MakeEmpty();
3733 	return B_ERROR;
3734 }
3735