xref: /haiku/src/apps/diskprobe/DataView.cpp (revision 1b80286772b529a3d6de3bbeb0720c62e6a32fed)
1 /*
2  * Copyright 2004-2009, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "DataView.h"
8 #include "DataEditor.h"
9 
10 #include <stdio.h>
11 #include <stdlib.h>
12 
13 #include <Window.h>
14 #include <ScrollBar.h>
15 #include <Autolock.h>
16 #include <Clipboard.h>
17 #include <Mime.h>
18 #include <Beep.h>
19 
20 
21 #ifndef __HAIKU__
22 typedef uint32 addr_t;
23 #endif
24 
25 static const uint32 kBlockSize = 16;
26 static const uint32 kHorizontalSpace = 8;
27 static const uint32 kVerticalSpace = 4;
28 
29 static const uint32 kBlockSpace = 3;
30 static const uint32 kHexByteWidth = 3;
31 	// these are determined by the implementation of DataView::ConvertLine()
32 
33 
34 /*!	This function checks if the buffer contains a valid UTF-8
35 	string, following the convention from the DataView::ConvertLine()
36 	method: everything that's not replaced by a '.' will be accepted.
37 */
38 bool
39 is_valid_utf8(uint8 *data, size_t size)
40 {
41 	for (size_t i = 0; i < size; i++) {
42 		// accept a terminating null byte
43 		if (i == size - 1 && data[0] == '\0')
44 			return true;
45 
46 		if ((data[i] & 0x80) == 0) {
47 			// a single byte character
48 			if (data[i] < ' ' || data[i] == 0x7f)
49 				return false;
50 
51 			continue;
52 		}
53 
54 		if ((data[i] & 0xc0) == 0x80) {
55 			// not a proper multibyte start
56 			return false;
57 		}
58 
59 		// start of a multibyte character
60 		uint8 mask = 0x80;
61 		uint32 result = (uint32)(data[i++] & 0xff);
62 
63 		while (result & mask) {
64 			if (mask == 0x02) {
65 				// seven byte char - invalid
66 				return false;
67 			}
68 
69 			result &= ~mask;
70 			mask >>= 1;
71 		}
72 
73 		while (i < size && (data[i] & 0xc0) == 0x80) {
74 			result <<= 6;
75 			result += data[i++] & 0x3f;
76 
77 			mask <<= 1;
78 			if (mask == 0x40)
79 				break;
80 		}
81 
82 		if (mask != 0x40) {
83 			// not enough bytes in multibyte char
84 			return false;
85 		}
86 	}
87 
88 	return true;
89 }
90 
91 
92 //	#pragma mark -
93 
94 
95 DataView::DataView(BRect rect, DataEditor &editor)
96 	: BView(rect, "dataView", B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE | B_FRAME_EVENTS),
97 	fEditor(editor),
98 	fFocus(kHexFocus),
99 	fBase(kHexBase),
100 	fIsActive(true),
101 	fMouseSelectionStart(-1),
102 	fKeySelectionStart(-1),
103 	fBitPosition(0),
104 	fFitFontSize(false),
105 	fDragMessageSize(-1)
106 {
107 	fPositionLength = 4;
108 	fStart = fEnd = 0;
109 
110 	if (fEditor.Lock()) {
111 		fDataSize = fEditor.ViewSize();
112 		fOffset = fEditor.ViewOffset();
113 		fEditor.Unlock();
114 	} else
115 		fDataSize = 512;
116 	fData = (uint8 *)malloc(fDataSize);
117 
118 	SetFontSize(12.0);
119 		// also sets the fixed font
120 
121 	UpdateFromEditor();
122 }
123 
124 
125 DataView::~DataView()
126 {
127 }
128 
129 
130 void
131 DataView::DetachedFromWindow()
132 {
133 	fEditor.StopWatching(this);
134 }
135 
136 
137 void
138 DataView::AttachedToWindow()
139 {
140 	fEditor.StartWatching(this);
141 	MakeFocus(true);
142 		// this seems to be necessary - if we don't do this here,
143 		// the view is sometimes focus, but IsFocus() returns false...
144 }
145 
146 
147 void
148 DataView::UpdateFromEditor(BMessage *message)
149 {
150 	if (fData == NULL)
151 		return;
152 
153 	BAutolock locker(fEditor);
154 
155 	fFileSize = fEditor.FileSize();
156 
157 	// get the range of the changes
158 
159 	int32 start = 0, end = fDataSize - 1;
160 	off_t offset, size;
161 	if (message != NULL
162 		&& message->FindInt64("offset", &offset) == B_OK
163 		&& message->FindInt64("size", &size) == B_OK) {
164 		if (offset > fOffset + fDataSize
165 			|| offset + size < fOffset) {
166 			// the changes are not within our scope, so we can ignore them
167 			return;
168 		}
169 
170 		if (offset > fOffset)
171 			start = offset - fOffset;
172 		if (offset + size < fOffset + fDataSize)
173 			end = offset + size - fOffset;
174 	}
175 
176 	if (fOffset + fDataSize > fFileSize)
177 		fSizeInView = fFileSize - fOffset;
178 	else
179 		fSizeInView = fDataSize;
180 
181 	const uint8 *data;
182 	if (fEditor.GetViewBuffer(&data) == B_OK)
183 		// ToDo: copy only the relevant part
184 		memcpy(fData, data, fDataSize);
185 
186 	InvalidateRange(start, end);
187 
188 	// we notify our selection listeners also if the
189 	// data in the selection has changed
190 	if (start <= fEnd && end >= fStart) {
191 		BMessage update;
192 		update.AddInt64("start", fStart);
193 		update.AddInt64("end", fEnd);
194 		SendNotices(kDataViewSelection, &update);
195 	}
196 }
197 
198 
199 bool
200 DataView::AcceptsDrop(const BMessage *message)
201 {
202 	return !fEditor.IsReadOnly()
203 		&& (message->HasData("text/plain", B_MIME_TYPE)
204 			|| message->HasData(B_FILE_MIME_TYPE, B_MIME_TYPE));
205 }
206 
207 
208 void
209 DataView::MessageReceived(BMessage *message)
210 {
211 	switch (message->what) {
212 		case kMsgUpdateData:
213 		case kMsgDataEditorUpdate:
214 			UpdateFromEditor(message);
215 			break;
216 
217 		case kMsgDataEditorParameterChange:
218 		{
219 			int32 viewSize;
220 			off_t offset;
221 			if (message->FindInt64("offset", &offset) == B_OK) {
222 				fOffset = offset;
223 				SetSelection(0, 0);
224 				MakeVisible(0);
225 			}
226 			if (message->FindInt32("view_size", &viewSize) == B_OK) {
227 				fDataSize = viewSize;
228 				fData = (uint8 *)realloc(fData, fDataSize);
229 				UpdateScroller();
230 				SendNotices(kDataViewPreferredSize);
231 			}
232 			if (message->FindInt64("file_size", &offset) == B_OK)
233 				UpdateFromEditor();
234 			break;
235 		}
236 
237 		case kMsgBaseType:
238 		{
239 			int32 type;
240 			if (message->FindInt32("base", &type) != B_OK)
241 				break;
242 
243 			SetBase((base_type)type);
244 			break;
245 		}
246 
247 		case kMsgSetSelection:
248 		{
249 			int64 start, end;
250 			if (message->FindInt64("start", &start) != B_OK
251 				|| message->FindInt64("end", &end) != B_OK)
252 				break;
253 
254 			SetSelection(start, end);
255 			break;
256 		}
257 
258 		case B_SELECT_ALL:
259 			SetSelection(0, fDataSize - 1);
260 			break;
261 
262 		case B_COPY:
263 			Copy();
264 			break;
265 
266 		case B_PASTE:
267 			Paste();
268 			break;
269 
270 		case B_UNDO:
271 			fEditor.Undo();
272 			break;
273 
274 		case B_REDO:
275 			fEditor.Redo();
276 			break;
277 
278 		case B_MIME_DATA:
279 			if (AcceptsDrop(message)) {
280 				const void *data;
281 				ssize_t size;
282 				if (message->FindData("text/plain", B_MIME_TYPE, &data, &size) == B_OK
283 					|| message->FindData(B_FILE_MIME_TYPE, B_MIME_TYPE, &data, &size) == B_OK) {
284 					if (fEditor.Replace(fOffset + fStart, (const uint8 *)data, size) != B_OK)
285 						SetSelection(fStoredStart, fStoredEnd);
286 
287 					fDragMessageSize = -1;
288 				}
289 			}
290 			break;
291 
292 		default:
293 			BView::MessageReceived(message);
294 	}
295 }
296 
297 
298 void
299 DataView::Copy()
300 {
301 	if (!be_clipboard->Lock())
302 		return;
303 
304 	be_clipboard->Clear();
305 
306 	BMessage *clip;
307 	if ((clip = be_clipboard->Data()) != NULL) {
308 		uint8 *data = fData + fStart;
309 		size_t length = fEnd + 1 - fStart;
310 
311 		clip->AddData(B_FILE_MIME_TYPE, B_MIME_TYPE, data, length);
312 
313 		if (is_valid_utf8(data, length))
314 			clip->AddData("text/plain", B_MIME_TYPE, data, length);
315 
316 		be_clipboard->Commit();
317 	}
318 
319 	be_clipboard->Unlock();
320 }
321 
322 
323 void
324 DataView::Paste()
325 {
326 	if (!be_clipboard->Lock())
327 		return;
328 
329 	const void *data;
330 	ssize_t length;
331 	BMessage *clip;
332 	if ((clip = be_clipboard->Data()) != NULL
333 		&& (clip->FindData(B_FILE_MIME_TYPE, B_MIME_TYPE, &data, &length) == B_OK
334 			|| clip->FindData("text/plain", B_MIME_TYPE, &data, &length) == B_OK)) {
335 		// we have valid data, but it could still be too
336 		// large to to fit in the file
337 		if (fOffset + fStart + length > fFileSize)
338 			length = fFileSize - fOffset;
339 
340 		if (fEditor.Replace(fOffset + fStart, (const uint8 *)data, length) == B_OK)
341 			SetSelection(fStart + length, fStart + length);
342 	} else
343 		beep();
344 
345 	be_clipboard->Unlock();
346 }
347 
348 
349 void
350 DataView::ConvertLine(char *line, off_t offset, const uint8 *buffer, size_t size)
351 {
352 	if (size == 0) {
353 		line[0] = '\0';
354 		return;
355 	}
356 
357 	line += sprintf(line, fBase == kHexBase ? "%0*Lx:  " : "%0*Ld:  ",
358 		(int)fPositionLength, offset);
359 
360 	for (uint32 i = 0; i < kBlockSize; i++) {
361 		if (i >= size) {
362 			strcpy(line, "   ");
363 			line += kHexByteWidth;
364 		} else
365 			line += sprintf(line, "%02x ", *(unsigned char *)(buffer + i));
366 	}
367 
368 	strcpy(line, "   ");
369 	line += 3;
370 
371 	for (uint32 i = 0; i < kBlockSize; i++) {
372 		if (i < size) {
373 			char c = buffer[i];
374 
375 			if (c < ' ' || c == 0x7f)
376 				*line++ = '.';
377 			else
378 				*line++ = c;
379 		} else
380 			break;
381 	}
382 
383 	*line = '\0';
384 }
385 
386 
387 void
388 DataView::Draw(BRect updateRect)
389 {
390 	if (fData == NULL || fFileSize == 0)
391 		return;
392 
393 	// ToDo: take "updateRect" into account!
394 
395 	char line[255];
396 	BPoint location(kHorizontalSpace, kVerticalSpace + fAscent);
397 
398 	for (uint32 i = 0; i < fSizeInView; i += kBlockSize) {
399 		ConvertLine(line, i, fData + i, fSizeInView - i);
400 		DrawString(line, location);
401 
402 		location.y += fFontHeight;
403 	}
404 
405 	DrawSelection();
406 }
407 
408 
409 BRect
410 DataView::DataBounds(bool inView) const
411 {
412 	return BRect(0, 0,
413 		fCharWidth * (kBlockSize * 4 + fPositionLength + 6) + 2 * kHorizontalSpace,
414 		fFontHeight * (((inView ? fSizeInView : fDataSize) + kBlockSize - 1) / kBlockSize)
415 			+ 2 * kVerticalSpace);
416 }
417 
418 
419 int32
420 DataView::PositionAt(view_focus focus, BPoint point, view_focus *_newFocus)
421 {
422 	// clip the point into our data bounds
423 
424 	BRect bounds = DataBounds(true);
425 	if (point.x < bounds.left)
426 		point.x = bounds.left;
427 	else if (point.x > bounds.right)
428 		point.x = bounds.right;
429 
430 	if (point.y < bounds.top)
431 		point.y = bounds.top;
432 	else if (point.y >= bounds.bottom - kVerticalSpace)
433 		point.y = bounds.bottom - kVerticalSpace - 1;
434 
435 	float left = fCharWidth * (fPositionLength + kBlockSpace) + kHorizontalSpace;
436 	float hexWidth = fCharWidth * kBlockSize * kHexByteWidth;
437 	float width = fCharWidth;
438 
439 	if (focus == kNoFocus) {
440 		// find in which part the point is in
441 		if (point.x < left - width / 2)
442 			return -1;
443 
444 		if (point.x > left + hexWidth)
445 			focus = kAsciiFocus;
446 		else
447 			focus = kHexFocus;
448 
449 		if (_newFocus)
450 			*_newFocus = focus;
451 	}
452 	if (focus == kHexFocus) {
453 		left -= width / 2;
454 		width *= kHexByteWidth;
455 	} else
456 		left += hexWidth + (kBlockSpace * width);
457 
458 	int32 row = int32((point.y - kVerticalSpace) / fFontHeight);
459 	int32 column = int32((point.x - left) / width);
460 	if (column >= (int32)kBlockSize)
461 		column = (int32)kBlockSize - 1;
462 	else if (column < 0)
463 		column = 0;
464 
465 	return row * kBlockSize + column;
466 }
467 
468 
469 BRect
470 DataView::SelectionFrame(view_focus which, int32 start, int32 end)
471 {
472 	float spacing = 0;
473 	float width = fCharWidth;
474 	float byteWidth = fCharWidth;
475 	float left;
476 
477 	if (which == kHexFocus) {
478 		spacing = fCharWidth / 2;
479 		left = width * (fPositionLength + kBlockSpace);
480 		width *= kHexByteWidth;
481 		byteWidth *= 2;
482 	} else
483 		left = width * (fPositionLength + 2 * kBlockSpace + kHexByteWidth * kBlockSize);
484 
485 	left += kHorizontalSpace;
486 	float startInLine = (start % kBlockSize) * width;
487 	float endInLine = (end % kBlockSize) * width + byteWidth - 1;
488 
489 	return BRect(left + startInLine - spacing,
490 		kVerticalSpace + (start / kBlockSize) * fFontHeight,
491 		left + endInLine + spacing,
492 		kVerticalSpace + (end / kBlockSize + 1) * fFontHeight - 1);
493 }
494 
495 
496 void
497 DataView::DrawSelectionFrame(view_focus which)
498 {
499 	if (fFileSize == 0)
500 		return;
501 
502 	bool drawBlock = false;
503 	bool drawLastLine = false;
504 	BRect block, lastLine;
505 	int32 spacing = 0;
506 	if (which == kAsciiFocus)
507 		spacing++;
508 
509 	// draw first line
510 
511 	int32 start = fStart % kBlockSize;
512 	int32 first = (fStart / kBlockSize) * kBlockSize;
513 
514 	int32 end = fEnd;
515 	if (end > first + (int32)kBlockSize - 1)
516 		end = first + kBlockSize - 1;
517 
518 	BRect firstLine = SelectionFrame(which, first + start, end);
519 	firstLine.right += spacing;
520 	first += kBlockSize;
521 
522 	// draw block (and last line) if necessary
523 
524 	end = fEnd % kBlockSize;
525 	int32 last = (fEnd / kBlockSize) * kBlockSize;
526 
527 	if (last >= first) {
528 		if (end == kBlockSize - 1)
529 			last += kBlockSize;
530 		if (last > first) {
531 			block = SelectionFrame(which, first, last - 1);
532 			block.right += spacing;
533 			drawBlock = true;
534 		}
535 		if (end != kBlockSize - 1) {
536 			lastLine = SelectionFrame(which, last, last + end);
537 			lastLine.right += spacing;
538 			drawLastLine = true;
539 		}
540 	}
541 
542 	SetDrawingMode(B_OP_INVERT);
543 	BeginLineArray(8);
544 
545 	// +*******
546 	// |      *
547 	// +------+
548 
549 	const rgb_color color = {0, 0, 0};
550 	float bottom;
551 	if (drawBlock)
552 		bottom = block.bottom;
553 	else
554 		bottom = firstLine.bottom;
555 
556 	AddLine(BPoint(firstLine.left + 1, firstLine.top), firstLine.RightTop(), color);
557 	AddLine(BPoint(firstLine.right, firstLine.top + 1), BPoint(firstLine.right, bottom), color);
558 
559 	// *-------+
560 	// *       |
561 	// *********
562 
563 	BRect rect;
564 	if (start == 0 || !drawBlock && !drawLastLine)
565 		rect = firstLine;
566 	else if (drawBlock)
567 		rect = block;
568 	else
569 		rect = lastLine;
570 
571 	if (drawBlock)
572 		rect.bottom = block.bottom;
573 	if (drawLastLine) {
574 		rect.bottom = lastLine.bottom;
575 		rect.right = lastLine.right;
576 	}
577 	rect.bottom++;
578 
579 	AddLine(rect.LeftTop(), rect.LeftBottom(), color);
580 	AddLine(BPoint(rect.left + 1, rect.bottom), rect.RightBottom(), color);
581 
582 	//     *--------+
583 	//     *        |
584 	// +****        |
585 	// |            |
586 
587 	if (start && (drawLastLine || drawBlock)) {
588 		AddLine(firstLine.LeftTop(), firstLine.LeftBottom(), color);
589 
590 		float right = firstLine.left;
591 		if (!drawBlock && right > lastLine.right)
592 			right = lastLine.right;
593 		AddLine(BPoint(rect.left + 1, rect.top), BPoint(right, rect.top), color);
594 	}
595 
596 	// |            |
597 	// |        *****
598 	// |        *
599 	// +--------+
600 
601 	if (drawLastLine) {
602 		AddLine(lastLine.RightBottom(), BPoint(lastLine.right, lastLine.top + 1), color);
603 		if (!drawBlock && lastLine.right <= firstLine.left)
604 			lastLine.right = firstLine.left + (lastLine.right < firstLine.left ? 0 : 1);
605 		AddLine(BPoint(lastLine.right, lastLine.top), BPoint(firstLine.right, lastLine.top), color);
606 	}
607 
608 	EndLineArray();
609 	SetDrawingMode(B_OP_COPY);
610 }
611 
612 
613 void
614 DataView::DrawSelectionBlock(view_focus which, int32 blockStart, int32 blockEnd)
615 {
616 	if (fFileSize == 0)
617 		return;
618 
619 	// draw first line
620 
621 	SetDrawingMode(B_OP_INVERT);
622 
623 	int32 start = blockStart % kBlockSize;
624 	int32 first = (blockStart / kBlockSize) * kBlockSize;
625 
626 	int32 end = blockEnd;
627 	if (end > first + (int32)kBlockSize - 1)
628 		end = first + kBlockSize - 1;
629 
630 	FillRect(SelectionFrame(which, first + start, end));
631 	first += kBlockSize;
632 
633 	// draw block (and last line) if necessary
634 
635 	end = blockEnd % kBlockSize;
636 	int32 last = (blockEnd / kBlockSize) * kBlockSize;
637 
638 	if (last >= first) {
639 		if (end == kBlockSize - 1)
640 			last += kBlockSize;
641 
642 		if (last > first)
643 			FillRect(SelectionFrame(which, first, last - 1));
644 		if (end != kBlockSize - 1)
645 			FillRect(SelectionFrame(which, last, last + end));
646 	}
647 
648 	SetDrawingMode(B_OP_COPY);
649 }
650 
651 
652 void
653 DataView::DrawSelectionBlock(view_focus which)
654 {
655 	DrawSelectionBlock(which, fStart, fEnd);
656 }
657 
658 
659 void
660 DataView::DrawSelection(bool frameOnly)
661 {
662 	if (IsFocus() && fIsActive) {
663 		if (!frameOnly)
664 			DrawSelectionBlock(fFocus);
665 		DrawSelectionFrame(fFocus == kHexFocus ? kAsciiFocus : kHexFocus);
666 	} else {
667 		DrawSelectionFrame(kHexFocus);
668 		DrawSelectionFrame(kAsciiFocus);
669 	}
670 }
671 
672 
673 void
674 DataView::SetSelection(int32 start, int32 end, view_focus focus)
675 {
676 	// correct the values if necessary
677 
678 	if (start > end) {
679 		int32 temp = start;
680 		start = end;
681 		end = temp;
682 	}
683 
684 	if (start > (int32)fSizeInView - 1)
685 		start = (int32)fSizeInView - 1;
686 	if (start < 0)
687 		start = 0;
688 
689 	if (end > (int32)fSizeInView - 1)
690 		end = (int32)fSizeInView - 1;
691 	if (end < 0)
692 		end = 0;
693 
694 	if (fStart == start && fEnd == end) {
695 		// nothing has changed, no need to update
696 		return;
697 	}
698 
699 	// notify our listeners
700 	if (fStart != start) {
701 		BMessage update;
702 		update.AddInt64("position", start);
703 		SendNotices(kDataViewCursorPosition, &update);
704 	}
705 
706 	BMessage update;
707 	update.AddInt64("start", start);
708 	update.AddInt64("end", end);
709 	SendNotices(kDataViewSelection, &update);
710 
711 	// Update selection - first, we need to remove the old selection, then
712 	// we redraw the selection with the current values.
713 
714 	DrawSelection(focus == kNoFocus);
715 		// From the block selection, only the parts that need updating are
716 		// actually updated, if there is no focus change.
717 
718 	if (IsFocus() && fIsActive && focus == kNoFocus) {
719 		// Update the selection block incrementally
720 
721 		if (start > fStart) {
722 			// remove from the top
723 			DrawSelectionBlock(fFocus, fStart, start - 1);
724 		} else if (start < fStart) {
725 			// add to the top
726 			DrawSelectionBlock(fFocus, start, fStart - 1);
727 		}
728 
729 		if (end < fEnd) {
730 			// remove from bottom
731 			DrawSelectionBlock(fFocus, end + 1, fEnd);
732 		} else if (end > fEnd) {
733 			// add to the bottom
734 			DrawSelectionBlock(fFocus, fEnd + 1, end);
735 		}
736 	}
737 
738 	if (focus != kNoFocus)
739 		fFocus = focus;
740 	fStart = start;
741 	fEnd = end;
742 
743 	DrawSelection(focus == kNoFocus);
744 
745 	fBitPosition = 0;
746 }
747 
748 
749 void
750 DataView::GetSelection(int32 &start, int32 &end)
751 {
752 	start = fStart;
753 	end = fEnd;
754 }
755 
756 
757 void
758 DataView::InvalidateRange(int32 start, int32 end)
759 {
760 	if (start <= 0 && end >= int32(fDataSize) - 1) {
761 		Invalidate();
762 		return;
763 	}
764 
765 	int32 startLine = start / kBlockSize;
766 	int32 endLine = end / kBlockSize;
767 
768 	if (endLine > startLine) {
769 		start = startLine * kBlockSize;
770 		end = (endLine + 1) * kBlockSize - 1;
771 	}
772 
773 	// the part with focus
774 	BRect rect = SelectionFrame(fFocus, start, end);
775 	rect.bottom++;
776 	rect.right++;
777 	Invalidate(rect);
778 
779 	// the part without focus
780 	rect = SelectionFrame(fFocus == kHexFocus ? kAsciiFocus : kHexFocus, start, end);
781 	rect.bottom++;
782 	rect.right++;
783 	Invalidate(rect);
784 }
785 
786 
787 void
788 DataView::MakeVisible(int32 position)
789 {
790 	if (position < 0 || position > int32(fDataSize) - 1)
791 		return;
792 
793 	BRect frame = SelectionFrame(fFocus, position, position);
794 	BRect bounds = Bounds();
795 	if (bounds.Contains(frame))
796 		return;
797 
798 	// special case the first and the last line and column, so that
799 	// we can take kHorizontalSpace & kVerticalSpace into account
800 
801 	if ((position % kBlockSize) == 0)
802 		frame.left -= kHorizontalSpace;
803 	else if ((position % kBlockSize) == kBlockSize - 1)
804 		frame.right += kHorizontalSpace;
805 
806 	if (position < int32(kBlockSize))
807 		frame.top -= kVerticalSpace;
808 	else if (position > int32(fDataSize - kBlockSize))
809 		frame.bottom += kVerticalSpace;
810 
811 	// compute the scroll point
812 
813 	BPoint point = bounds.LeftTop();
814 	if (bounds.left > frame.left)
815 		point.x = frame.left;
816 	else if (bounds.right < frame.right)
817 		point.x = frame.right - bounds.Width();
818 
819 	if (bounds.top > frame.top)
820 		point.y = frame.top;
821 	else if (bounds.bottom < frame.bottom)
822 		point.y = frame.bottom - bounds.Height();
823 
824 	ScrollTo(point);
825 }
826 
827 
828 const uint8 *
829 DataView::DataAt(int32 start)
830 {
831 	if (start < 0 || start >= int32(fSizeInView) || fData == NULL)
832 		return NULL;
833 
834 	return fData + start;
835 }
836 
837 
838 void
839 DataView::SetBase(base_type type)
840 {
841 	if (fBase == type)
842 		return;
843 
844 	fBase = type;
845 	Invalidate();
846 }
847 
848 
849 void
850 DataView::SetFocus(view_focus which)
851 {
852 	if (which == fFocus)
853 		return;
854 
855 	DrawSelection();
856 	fFocus = which;
857 	DrawSelection();
858 }
859 
860 
861 void
862 DataView::SetActive(bool active)
863 {
864 	if (active == fIsActive)
865 		return;
866 
867 	fIsActive = active;
868 
869 	// only redraw the focussed part
870 
871 	if (IsFocus() && active) {
872 		DrawSelectionFrame(fFocus);
873 		DrawSelectionBlock(fFocus);
874 	} else {
875 		DrawSelectionBlock(fFocus);
876 		DrawSelectionFrame(fFocus);
877 	}
878 }
879 
880 
881 void
882 DataView::WindowActivated(bool active)
883 {
884 	BView::WindowActivated(active);
885 	SetActive(active);
886 }
887 
888 
889 void
890 DataView::MakeFocus(bool focus)
891 {
892 	bool previous = IsFocus();
893 	BView::MakeFocus(focus);
894 
895 	if (focus == previous)
896 		return;
897 
898 	if (Window()->IsActive() && focus)
899 		SetActive(true);
900 	else if (!Window()->IsActive() || !focus)
901 		SetActive(false);
902 }
903 
904 
905 void
906 DataView::UpdateScroller()
907 {
908 	float width, height;
909 	GetPreferredSize(&width, &height);
910 
911 	BScrollBar *bar;
912 	if ((bar = ScrollBar(B_HORIZONTAL)) != NULL) {
913 		float delta = width - Bounds().Width();
914 		if (delta < 0)
915 			delta = 0;
916 
917 		bar->SetRange(0, delta);
918 		bar->SetSteps(fCharWidth, Bounds().Width());
919 		bar->SetProportion(Bounds().Width() / width);
920 	}
921 	if ((bar = ScrollBar(B_VERTICAL)) != NULL) {
922 		float delta = height - Bounds().Height();
923 		if (delta < 0)
924 			delta = 0;
925 
926 		bar->SetRange(0, delta);
927 		bar->SetSteps(fFontHeight, Bounds().Height());
928 		bar->SetProportion(Bounds().Height() / height);
929 	}
930 }
931 
932 
933 void
934 DataView::FrameResized(float width, float height)
935 {
936 	if (fFitFontSize) {
937 		// adapt the font size to fit in the view's bounds
938 		float oldSize = FontSize();
939 		BFont font = be_fixed_font;
940 		float steps = 0.5f;
941 
942 		float size;
943 		for (size = 1.f; size < 100; size += steps) {
944 			font.SetSize(size);
945 			float charWidth = font.StringWidth("w");
946 			if (charWidth * (kBlockSize * 4 + fPositionLength + 6) + 2 * kHorizontalSpace > width)
947 				break;
948 
949 			if (size > 6)
950 				steps = 1.0f;
951 		}
952 		size -= steps;
953 		font.SetSize(size);
954 
955 		if (oldSize != size) {
956 			SetFont(&font);
957 			Invalidate();
958 		}
959 	}
960 
961 	UpdateScroller();
962 }
963 
964 
965 void
966 DataView::InitiateDrag(view_focus focus)
967 {
968 	BMessage *drag = new BMessage(B_MIME_DATA);
969 
970 	// Add originator and action
971 	drag->AddPointer("be:originator", this);
972 	//drag->AddString("be:clip_name", "Byte Clipping");
973 	//drag->AddInt32("be_actions", B_TRASH_TARGET);
974 
975 	// Add data (just like in Copy())
976 	uint8 *data = fData + fStart;
977 	size_t length = fEnd + 1 - fStart;
978 
979 	drag->AddData(B_FILE_MIME_TYPE, B_MIME_TYPE, data, length);
980 	if (is_valid_utf8(data, length))
981 		drag->AddData("text/plain", B_MIME_TYPE, data, length);
982 
983 	// get a frame that contains the whole selection - SelectionFrame()
984 	// only spans a rectangle between the start and the end point, so
985 	// we have to pass it the correct input values
986 
987 	BRect frame;
988 	const int32 width = kBlockSize - 1;
989 	int32 first = fStart & ~width;
990 	int32 last = ((fEnd + width) & ~width) - 1;
991 	if (first == (last & ~width))
992 		frame = SelectionFrame(focus, fStart, fEnd);
993 	else
994 		frame = SelectionFrame(focus, first, last);
995 
996 	BRect bounds = Bounds();
997 	if (!bounds.Contains(frame))
998 		frame = bounds & frame;
999 
1000 	DragMessage(drag, frame, NULL);
1001 
1002 	fStoredStart = fStart;
1003 	fStoredEnd = fEnd;
1004 	fDragMessageSize = length;
1005 }
1006 
1007 
1008 void
1009 DataView::MouseDown(BPoint where)
1010 {
1011 	MakeFocus(true);
1012 
1013 	BMessage *message = Looper()->CurrentMessage();
1014 	int32 buttons;
1015 	if (message == NULL || message->FindInt32("buttons", &buttons) != B_OK)
1016 		return;
1017 
1018 	view_focus newFocus;
1019 	int32 position = PositionAt(kNoFocus, where, &newFocus);
1020 
1021 	if ((buttons & B_SECONDARY_MOUSE_BUTTON) != 0
1022 		&& position >= fStart && position <= fEnd) {
1023 		InitiateDrag(newFocus);
1024 		return;
1025 	}
1026 
1027 	if ((buttons & B_PRIMARY_MOUSE_BUTTON) == 0)
1028 		return;
1029 
1030 	int32 modifiers = message->FindInt32("modifiers");
1031 
1032 	fMouseSelectionStart = position;
1033 	if (fMouseSelectionStart == -1) {
1034 		// "where" is outside the valid frame
1035 		return;
1036 	}
1037 
1038 	int32 selectionEnd = fMouseSelectionStart;
1039 	if (modifiers & B_SHIFT_KEY) {
1040 		// enlarge the current selection
1041 		if (fStart < selectionEnd)
1042 			fMouseSelectionStart = fStart;
1043 		else if (fEnd > selectionEnd)
1044 			fMouseSelectionStart = fEnd;
1045 	}
1046 	SetSelection(fMouseSelectionStart, selectionEnd, newFocus);
1047 
1048 	SetMouseEventMask(B_POINTER_EVENTS,
1049 		B_NO_POINTER_HISTORY | B_SUSPEND_VIEW_FOCUS | B_LOCK_WINDOW_FOCUS);
1050 }
1051 
1052 
1053 void
1054 DataView::MouseMoved(BPoint where, uint32 transit, const BMessage *dragMessage)
1055 {
1056 	if (transit == B_EXITED_VIEW && fDragMessageSize > 0) {
1057 		SetSelection(fStoredStart, fStoredEnd);
1058 		fDragMessageSize = -1;
1059 	}
1060 
1061 	if (dragMessage && AcceptsDrop(dragMessage)) {
1062 		// handle drag message and tracking
1063 
1064 		if (transit == B_ENTERED_VIEW) {
1065 			fStoredStart = fStart;
1066 			fStoredEnd = fEnd;
1067 
1068 			const void *data;
1069 			ssize_t size;
1070 			if (dragMessage->FindData("text/plain", B_MIME_TYPE, &data, &size) == B_OK
1071 				|| dragMessage->FindData("text/plain", B_MIME_TYPE, &data, &size) == B_OK)
1072 				fDragMessageSize = size;
1073 		} else if (fDragMessageSize > 0) {
1074 			view_focus newFocus;
1075 			int32 start = PositionAt(kNoFocus, where, &newFocus);
1076 			int32 end = start + fDragMessageSize - 1;
1077 
1078 			SetSelection(start, end);
1079 			MakeVisible(start);
1080 		}
1081 		return;
1082 	}
1083 
1084 	if (fMouseSelectionStart == -1)
1085 		return;
1086 
1087 	int32 end = PositionAt(fFocus, where);
1088 	if (end == -1)
1089 		return;
1090 
1091 	SetSelection(fMouseSelectionStart, end);
1092 	MakeVisible(end);
1093 }
1094 
1095 
1096 void
1097 DataView::MouseUp(BPoint where)
1098 {
1099 	fMouseSelectionStart = fKeySelectionStart = -1;
1100 }
1101 
1102 
1103 void
1104 DataView::KeyDown(const char *bytes, int32 numBytes)
1105 {
1106 	int32 modifiers;
1107 	if (Looper()->CurrentMessage() == NULL
1108 		|| Looper()->CurrentMessage()->FindInt32("modifiers", &modifiers) != B_OK)
1109 		modifiers = ::modifiers();
1110 
1111 	// check if the selection is going to be changed
1112 	switch (bytes[0]) {
1113 		case B_LEFT_ARROW:
1114 		case B_RIGHT_ARROW:
1115 		case B_UP_ARROW:
1116 		case B_DOWN_ARROW:
1117 			if (modifiers & B_SHIFT_KEY) {
1118 				if (fKeySelectionStart == -1)
1119 					fKeySelectionStart = fStart;
1120 			} else
1121 				fKeySelectionStart = -1;
1122 			break;
1123 	}
1124 
1125 	switch (bytes[0]) {
1126 		case B_LEFT_ARROW:
1127 		{
1128 			int32 position = fStart - 1;
1129 
1130 			if (modifiers & B_SHIFT_KEY) {
1131 				if (fKeySelectionStart == fEnd)
1132 					SetSelection(fStart - 1, fEnd);
1133 				else {
1134 					SetSelection(fStart, fEnd - 1);
1135 					position = fEnd;
1136 				}
1137 			} else
1138 				SetSelection(fStart - 1, fStart - 1);
1139 
1140 			MakeVisible(position);
1141 			break;
1142 		}
1143 		case B_RIGHT_ARROW:
1144 		{
1145 			int32 position = fEnd + 1;
1146 
1147 			if (modifiers & B_SHIFT_KEY) {
1148 				if (fKeySelectionStart == fStart)
1149 					SetSelection(fStart, fEnd + 1);
1150 				else
1151 					SetSelection(fStart + 1, fEnd);
1152 			} else
1153 				SetSelection(fEnd + 1, fEnd + 1);
1154 
1155 			MakeVisible(position);
1156 			break;
1157 		}
1158 		case B_UP_ARROW:
1159 		{
1160 			int32 start, end;
1161 			if (modifiers & B_SHIFT_KEY) {
1162 				if (fKeySelectionStart == fStart) {
1163 					start = fEnd - int32(kBlockSize);
1164 					end = fStart;
1165 				} else {
1166 					start = fStart - int32(kBlockSize);
1167 					end = fEnd;
1168 				}
1169 				if (start < 0)
1170 					start = 0;
1171 			} else {
1172 				start = fStart - int32(kBlockSize);
1173 				if (start < 0)
1174 					start = fStart;
1175 
1176 				end = start;
1177 			}
1178 
1179 			SetSelection(start, end);
1180 			MakeVisible(start);
1181 			break;
1182 		}
1183 		case B_DOWN_ARROW:
1184 		{
1185 			int32 start, end;
1186 			if (modifiers & B_SHIFT_KEY) {
1187 				if (fKeySelectionStart == fEnd) {
1188 					start = fEnd;
1189 					end = fStart + int32(kBlockSize);
1190 				} else {
1191 					start = fStart;
1192 					end = fEnd + int32(kBlockSize);
1193 				}
1194 				if (end >= int32(fSizeInView))
1195 					end = int32(fSizeInView) - 1;
1196 			} else {
1197 				end = fEnd + int32(kBlockSize);
1198 				if (end >= int32(fSizeInView))
1199 					start = fEnd;
1200 
1201 				start = end;
1202 			}
1203 
1204 			SetSelection(start, end);
1205 			MakeVisible(end);
1206 			break;
1207 		}
1208 
1209 		case B_PAGE_UP:
1210 		{
1211 			// scroll one page up, but keep the same cursor column
1212 
1213 			BRect frame = SelectionFrame(fFocus, fStart, fStart);
1214 			frame.OffsetBy(0, -Bounds().Height());
1215 			if (frame.top <= kVerticalSpace)
1216 				frame.top = kVerticalSpace + 1;
1217 			ScrollBy(0, -Bounds().Height());
1218 
1219 			int32 position = PositionAt(fFocus, frame.LeftTop());
1220 			SetSelection(position, position);
1221 			break;
1222 		}
1223 		case B_PAGE_DOWN:
1224 		{
1225 			// scroll one page down, but keep the same cursor column
1226 
1227 			BRect frame = SelectionFrame(fFocus, fStart, fStart);
1228 			frame.OffsetBy(0, Bounds().Height());
1229 
1230 			float lastLine = DataBounds().Height() - 1 - kVerticalSpace;
1231 			if (frame.top > lastLine)
1232 				frame.top = lastLine;
1233 			ScrollBy(0, Bounds().Height());
1234 
1235 			int32 position = PositionAt(fFocus, frame.LeftTop());
1236 			SetSelection(position, position);
1237 			break;
1238 		}
1239 		case B_HOME:
1240 			SetSelection(0, 0);
1241 			MakeVisible(fStart);
1242 			break;
1243 		case B_END:
1244 			SetSelection(fDataSize - 1, fDataSize - 1);
1245 			MakeVisible(fStart);
1246 			break;
1247 		case B_TAB:
1248 			SetFocus(fFocus == kHexFocus ? kAsciiFocus : kHexFocus);
1249 			MakeVisible(fStart);
1250 			break;
1251 
1252 		case B_FUNCTION_KEY:
1253 			// this is ignored
1254 			break;
1255 
1256 		case B_BACKSPACE:
1257 			if (fBitPosition == 0)
1258 				SetSelection(fStart - 1, fStart - 1);
1259 
1260 			if (fFocus == kHexFocus)
1261 				fBitPosition = (fBitPosition + 4) % 8;
1262 
1263 			// supposed to fall through
1264 		case B_DELETE:
1265 			SetSelection(fStart, fStart);
1266 				// to make sure only the cursor is selected
1267 
1268 			if (fFocus == kHexFocus) {
1269 				const uint8 *data = DataAt(fStart);
1270 				if (data == NULL)
1271 					break;
1272 
1273 				uint8 c = data[0] & (fBitPosition == 0 ? 0x0f : 0xf0);
1274 					// mask out region to be cleared
1275 
1276 				fEditor.Replace(fOffset + fStart, &c, 1);
1277 			} else
1278 				fEditor.Replace(fOffset + fStart, (const uint8 *)"", 1);
1279 			break;
1280 
1281 		default:
1282 			if (fFocus == kHexFocus) {
1283 				// only hexadecimal characters are allowed to be entered
1284 				const uint8 *data = DataAt(fStart);
1285 				uint8 c = bytes[0];
1286 				if (c >= 'A' && c <= 'F')
1287 					c += 'A' - 'a';
1288 				const char *hexNumbers = "0123456789abcdef";
1289 				addr_t number;
1290 				if (data == NULL || (number = (addr_t)strchr(hexNumbers, c)) == 0)
1291 					break;
1292 
1293 				SetSelection(fStart, fStart);
1294 					// to make sure only the cursor is selected
1295 
1296 				number -= (addr_t)hexNumbers;
1297 				fBitPosition = (fBitPosition + 4) % 8;
1298 
1299 				c = (data[0] & (fBitPosition ? 0x0f : 0xf0)) | (number << fBitPosition);
1300 					// mask out overwritten region and bit-wise or the number to be inserted
1301 
1302 				if (fEditor.Replace(fOffset + fStart, &c, 1) == B_OK && fBitPosition == 0)
1303 					SetSelection(fStart + 1, fStart + 1);
1304 			} else {
1305 				if (fEditor.Replace(fOffset + fStart, (const uint8 *)bytes, numBytes) == B_OK)
1306 					SetSelection(fStart + 1, fStart + 1);
1307 			}
1308 			break;
1309 	}
1310 }
1311 
1312 
1313 void
1314 DataView::SetFont(const BFont *font, uint32 properties)
1315 {
1316 	if (!font->IsFixed())
1317 		return;
1318 
1319 	BView::SetFont(font, properties);
1320 
1321 	font_height fontHeight;
1322 	font->GetHeight(&fontHeight);
1323 
1324 	fFontHeight = int32(fontHeight.ascent + fontHeight.descent + fontHeight.leading);
1325 	fAscent = fontHeight.ascent;
1326 	fCharWidth = font->StringWidth("w");
1327 }
1328 
1329 
1330 float
1331 DataView::FontSize() const
1332 {
1333 	BFont font;
1334 	GetFont(&font);
1335 
1336 	return font.Size();
1337 }
1338 
1339 
1340 void
1341 DataView::SetFontSize(float point)
1342 {
1343 	bool fit = (point == 0.0f);
1344 	if (fit) {
1345 		if (!fFitFontSize)
1346 			SendNotices(kDataViewPreferredSize);
1347 		fFitFontSize = fit;
1348 
1349 		FrameResized(Bounds().Width(), Bounds().Height());
1350 		return;
1351 	}
1352 
1353 	fFitFontSize = false;
1354 
1355 	BFont font = be_fixed_font;
1356 	font.SetSize(point);
1357 
1358 	SetFont(&font);
1359 	UpdateScroller();
1360 	Invalidate();
1361 
1362 	SendNotices(kDataViewPreferredSize);
1363 }
1364 
1365 
1366 void
1367 DataView::GetPreferredSize(float *_width, float *_height)
1368 {
1369 	BRect bounds = DataBounds();
1370 
1371 	if (_width)
1372 		*_width = bounds.Width();
1373 
1374 	if (_height)
1375 		*_height = bounds.Height();
1376 }
1377 
1378