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