Category: Programming

get netbeans current row highlight color

		FontColorSettings fcs = MimeLookup.getLookup(MimePath.EMPTY).lookup(FontColorSettings.class);
		Coloring c = Coloring.fromAttributeSet(fcs.getFontColors(FontColorNames.CARET_ROW_COLORING));
		g.setColor(c.getBackColor());

read count : 3

Netbeans minimap design

I think atom editor has the best minimap, but there are places for enhancements:

1) Ignore the middle white space can increase the clarity.
2) If the document is too long, atomic editor’s minimap will become scrollable. Because it is scrollable so it will not display the whole code map, this make programmer can’t feel the overall code look like.

read count : 31

Netbeans mini code map

I am creating Netbeans mini code map, now eye ball comfortable. Netbeans’ editor is using different mechanism to store syntax hightlight, in traditional swing, we use “Element” and “AttributeSet” to represent a tree-view for syntax highlighting in JEditorPane. But Mr Miloslav Metelka told me :

Elements are perfect for advanced styling i.e. word like documents e.g. when a text is selected and made bold. It's also natural that this change is an undoable Element update. But we don't find Elements useful for things like syntax highlighting etc. since they are too heavyweight to operate - we would have to update the (nested) element structure upon each its modification and handle undoability.
Instead we use z-ordered highlighting layers i.e. a sequence of an attributed offset ranges." , 

so netbeans is using “HighlightsContainer” to store highlighting information, below is the example code to dump out the syntax highlighting information:

try {
	JEditorPane editorPane = (JEditorPane) jtc;
	Lookup lookup = MimeLookup.getLookup(editorPane.getContentType());
	FontColorSettings settings = lookup.lookup(FontColorSettings.class);
	Color defaultColor = (Color) settings.getTokenFontColors("default").getAttribute(StyleConstants.Foreground);

	HighlightsContainer hc = HighlightingManager.getInstance(jtc).getBottomHighlights();
	HighlightsSequence hq = hc.getHighlights(0, document.getLength());
	String lines[] = jtc.getText().split("\n");
	int noOfLine = lines.length;

	int longestLined = Integer.MIN_VALUE;
	for (int x = 0; x < lines.length; x++) {
		if (lines[x].length() > longestLined) {
			longestLined = lines[x].length();
		}
	}

	final int blockWidth = 10;
	final int blockHeight = 10;
	final int margin = 2;
	BufferedImage tempImage = new BufferedImage(longestLined * blockWidth, noOfLine * blockHeight, BufferedImage.TYPE_INT_ARGB);
	Graphics2D imageG = tempImage.createGraphics();
	int offsetX = 0;
	int offsetY = 0;
	Color lastColor = Color.white;
	while (hq.moveNext()) {
		AttributeSet as = hq.getAttributes();
		for (int x = 0; x < hq.getEndOffset() - hq.getStartOffset(); x++) {
			String text = document.getText(hq.getStartOffset() + x, 1);
			Color fc;
			if (text.equals(" ") || text.equals("\t")) {
				fc = lastColor;
			} else if (text.equals("\n")) {
				offsetX = 0;
				offsetY += blockHeight;
				lastColor = Color.white;
				continue;
			} else {
				if (as == null || as.getAttribute(StyleConstants.Foreground) == null) {
					fc = defaultColor;
				} else {
					fc = (Color) as.getAttribute(StyleConstants.Foreground);
				}
			}
			lastColor = fc;
			//ModuleLib.log(text + " : " + hq.getStartOffset() + " -> " + hq.getEndOffset() + " = (" + offsetX + "," + offsetY + ") " + fc);
			imageG.setColor(fc);
			imageG.fillRect(offsetX, offsetY + margin, blockWidth, blockHeight - (margin * 2));
			offsetX += blockWidth;
		}
	}
	return tempImage;
} catch (BadLocationException ex) {
	ModuleLib.log(CommonLib.printException(ex));
	return null;
}

read count : 22

This code print all elements and styles of JEditorPane

This code print all elements and styles of JEditorPane

		HTMLDocument doc = (HTMLDocument) jEditorPane1.getDocument();
		printElements(doc.getRootElements(), "");
	void printElements(Element elements[], String tabs) {
		for (Element element : elements) {
			//System.out.println("element=" + element.getDocument());
			int start = element.getStartOffset();
			int end = element.getEndOffset();
			try {
				System.out.println(tabs + element.getDocument().getText(start, end - start));
			} catch (BadLocationException ex) {
				ex.printStackTrace();
			}
			AttributeSet as = element.getAttributes();
			Enumeration e = as.getAttributeNames();
			while (e.hasMoreElements()) {
				Object o = e.nextElement();
				//System.out.println("	o=" + o.getClass());
				if (o instanceof String) {
					String attrName = (String) o;
					System.out.println(tabs + "	string=" + attrName);
				} else if (o instanceof StyleConstants) {
					System.out.println(tabs + "	FontSize=" + as.getAttribute(StyleConstants.Size));
					System.out.println(tabs + "	FontFamily=" + as.getAttribute(StyleConstants.FontFamily));
					System.out.println(tabs + "	Foreground=" + as.getAttribute(StyleConstants.Foreground));
				} else if (o instanceof CSS.Attribute) {
					CSS.Attribute a = (CSS.Attribute) o;
					System.out.println(tabs + "	" + a.toString() + " - " + a.getDefaultValue());
				} else {
					System.out.println("	o=" + o.getClass());
				}
			}
			System.out.println(tabs + "------------------------------------------------------------------");
			for (int x = 0; x < element.getElementCount(); x++) {
				printElements(new Element[]{element.getElement(x)}, tabs + "   ");
			}
		}
	}

read count : 5

open default editor using netbeans api

		try {
			DataObject.find(FileUtil.toFileObject(new File("/Users/peter/workspace/PeterI/kernel/kernel.cpp"))).
					getLookup().lookup(OpenCookie.class).open();
		} catch (DataObjectNotFoundException ex) {
			Exceptions.printStackTrace(ex);
		}

read count : 7

Visual c++ example to read mbr

Install windows ddk and run it using admin permission, otherwise all bytes that read from mbr are 0xcd. It can be compile using visual c++ community exition.

virus

#include "stdafx.h"
#include <cstdlib>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#define FILE_SHARE_VALID_FLAGS (0x00000007) 
using namespace std;

short ReadSect
(
	const char *_dsk,    // disk to access
	char *&_buff,         // buffer where sector will be stored
	unsigned int _nsect   // sector number, starting with 0
)
{
	DWORD dwRead;
	wchar_t wdsk[100];
	size_t count;
	mbstowcs_s(&count, wdsk, sizeof(wdsk) / sizeof(wdsk[0]), _dsk, _TRUNCATE);
	HANDLE hDisk = CreateFile(wdsk, GENERIC_READ, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, 0, 0);
	if (hDisk == INVALID_HANDLE_VALUE) // this may happen if another program is already reading from disk
	{
		CloseHandle(hDisk);
		return 1;
	}
	SetFilePointer(hDisk, _nsect * 512, 0, FILE_BEGIN); // which sector to read

	ReadFile(hDisk, _buff, 512, &dwRead, 0);  // read sector
	CloseHandle(hDisk);
	return 0;
}

int main()
{
	char *dsk = "\\\\.\\PhysicalDrive0";
	int sector = 0;

	char *buff = new char[512];
	ReadSect(dsk, buff, sector);
	for (int x = 0; x < 512; x++) {
		printf("%x ", buff[x] & 0xff);
	}
	if ((unsigned char)buff[510] == 0x55 && (unsigned char)buff[511] == 0xaa) {
		cout << "Disk is bootable!" << endl;
	}

	getchar();
	return 0;
}

read count : 69

ignore reflections library warning

to ignore this kind of warning:

[WARN] [10:16:57] [Reflections.java:208]	 could not create Vfs.Dir from url. ignoring the exception and continuing
org.reflections.ReflectionsException: could not create Vfs.Dir from url, no matching UrlType was found [file:/System/Library/Java/Extensions/libAppleScriptEngine.jnilib]
either use fromURL(final URL url, final List<UrlType> urlTypes) or use the static setDefaultURLTypes(final List<UrlType> urlTypes) or addDefaultURLTypes(UrlType urlType) with your specialized UrlType.
	at org.reflections.vfs.Vfs.fromURL(Vfs.java:109)
	at org.reflections.vfs.Vfs.fromURL(Vfs.java:91)
	at org.reflections.Reflections.scan(Reflections.java:237)
	at org.reflections.Reflections.scan(Reflections.java:204)
	at org.reflections.Reflections.<init>(Reflections.java:129)
	at com.titansolutions.HibernateUtil.buildSessionFactory(HibernateUtil.java:49)
	at com.titansolutions.HibernateUtil.<clinit>(HibernateUtil.java:28)

Just call ReflectionsHelper.registerUrlTypes(); before you use reflections

package com.titansolutions;

import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.reflections.vfs.Vfs;

import com.google.common.collect.Lists;

public class ReflectionsHelper {
	public static void registerUrlTypes() {

		final List<Vfs.UrlType> urlTypes = Lists.newArrayList();

		// include a list of file extensions / filenames to be recognized
		urlTypes.add(new EmptyIfFileEndingsUrlType(".mar", ".jnilib"));

		urlTypes.addAll(Arrays.asList(Vfs.DefaultUrlTypes.values()));

		Vfs.setDefaultURLTypes(urlTypes);
	}

	private static class EmptyIfFileEndingsUrlType implements Vfs.UrlType {

		private final List<String> fileEndings;

		private EmptyIfFileEndingsUrlType(final String... fileEndings) {

			this.fileEndings = Lists.newArrayList(fileEndings);
		}

		public boolean matches(URL url) {

			final String protocol = url.getProtocol();
			final String externalForm = url.toExternalForm();
			if (!protocol.equals("file")) {
				return false;
			}
			for (String fileEnding : fileEndings) {
				if (externalForm.endsWith(fileEnding))
					return true;
			}
			return false;
		}

		public Vfs.Dir createDir(final URL url) throws Exception {

			return emptyVfsDir(url);
		}

		private static Vfs.Dir emptyVfsDir(final URL url) {

			return new Vfs.Dir() {
				@Override
				public String getPath() {

					return url.toExternalForm();
				}

				@Override
				public Iterable<Vfs.File> getFiles() {

					return Collections.emptyList();
				}

				@Override
				public void close() {

				}
			};
		}
	}
}

read count : 34

Dtrace inspired me

Reading a Dtrace book in library made me suddenly remember, awk-like language syntax is very suitable for quantitive programming language, so i write down the first draft of my quant language based on the syntax of dtrace.

dtrace_5973_1024

dtrace_5970_1024

dtrace_5972_1024

dtrace_5971_1024

dtrace_5970_1024

read count : 30