Category: Programming

netbeans api to read bookmark line numbers

Below code can read out bookmark line numbers for netbeans. For Java project, the bookmark line number are stored in nbproject/private/private.xml. If it is maven project, the private.xml is not exist but this code still work, there must be some place to store the bookmark info but I just don’t know. These code has a weak point, it won’t read the latest line numbers unless you close the project/netbeans.

			Project project = NetbeansUtil.getProject();
			AuxiliaryConfiguration config = ProjectUtils.getAuxiliaryConfiguration(project);
			org.w3c.dom.Element element = config.getConfigurationFragment("editor-bookmarks", "http://www.netbeans.org/ns/editor-bookmarks/2", false);
			ModuleLib.log("element=" + element);
			if (element != null) {
				NodeList list = element.getElementsByTagNameNS("http://www.netbeans.org/ns/editor-bookmarks/2", "bookmark");
				for (int x = 0; x < list.getLength(); x++) {
					org.w3c.dom.Element enEl = (org.w3c.dom.Element) list.item(x);
					String lineNo = enEl.getTextContent().trim();
					ModuleLib.log("line no=" + lineNo);
				}
			}

read count : 9

Netbeans plugins, able to compile and build != able to install in a clean netbeans

People reported my minimal plugins can’t install in their netbeans. I concluded these:

1) able to compile and build NOT EQUAL to able to install in a clean netbeans
2) able to install your plugin in your netbeans NOT EQUAL to able to install in a clean netbeans

When you meet this error : Project depends on packages not accessible at runtime

Just add the library to in pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.github.mcheung63</groupId>
        <artifactId>netbeans-minimap</artifactId>
        <version>2.8</version>
        <packaging>nbm</packaging>
        <name>Minimap</name>
        <description>Display the code minimap, programmer can overlook their code.</description>
        <developers>
                <developer>
                        <name>Peter</name>
                        <email>mcheung63@hotmail.com</email>
                        <roles>
                                <role>Founder</role>
                        </roles>
                </developer>
        </developers>
        <build>
                <plugins>
                        <plugin>
                                <groupId>org.codehaus.mojo</groupId>
                                <artifactId>nbm-maven-plugin</artifactId>
                                <version>3.13</version>
                                <extensions>true</extensions>
                                <configuration>
                                        <!--<useOSGiDependencies>false</useOSGiDependencies>-->
                                        <moduleDependencies>
                                                <dependency>
                                                        <id>org.netbeans.api:org-netbeans-modules-editor-lib2</id>
                                                        <type>impl</type>
                                                </dependency>

read count : 19

old netbeans api code to get each line

g.setColor(Color.red);
		int lastLineNo = -1;
		while (hq.moveNext()) {
			AttributeSet as = hq.getAttributes();
			if (as != null) {
				try {
					lineNo = NbDocument.findLineNumber((StyledDocument) document, hq.getStartOffset());
					if (lineNo != lastLineNo) {
						lastLineNo = lineNo;
						g.drawString(String.valueOf(lineNo + 1), 0, fontHeight * (lineNo + 1) - 3);
					}
				} catch (Exception ex) {
					ModuleLib.log(CommonLib.printException(ex));
				}
			}
		}

read count : 15

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 : 2

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 : 28

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 : 19

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 : 6

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 : 61