임베디드/기반지식2015. 4. 22. 14:35


make


파일관리유틸리티로 각파일간의 종속관계를 파악하고 Makefile에 기술된대로 컴파일명령이나 쉘명령을 순차적으로 실행해주는것으로 빌드를 자동화하여 개발자의 수고를 덜어준다.

프로그램의 종속구조를 파악하고 관리가 용이해진다.

all : diary

diary : main.o calendar.o memo.o

gcc -W -Wall -o diary memo.o calendar.o main.o

main.o : main.c

gcc -W -Wall -c -o main.o main.c

calendar.o : calendar.c

gcc -W -Wall -c -o calendar.o calendar.c

memo.o : memo.c

gcc -W -Wall -c -o memo.o memo.c


첫번째 타겟 의 dependency인 diary로 이동 diary: 는 main, calendar, memo 디펜던시가 있는데 main.o calendar.o main.o가 생성이 되었는지 확인하고 안되어 있으면 해당 타겟을 먼저 실행한다.

해당 타겟이 모두 준비되면 gcc -W -Wall -o diary memo.o calendar.o main.o 가 실행되어 diary라는 실행파일을 만들어낸다.


빌드 및 실행하면..

leeyosam$ make

gcc -W -Wall -c -o main.o main.c

gcc -W -Wall -c -o calendar.o calendar.c

gcc -W -Wall -c -o memo.o memo.c

gcc -W -Wall -o diary memo.o calendar.o main.o

leeyosam$ ./diary 

function memo.

function calendar.


위 상태에서 calendar.c파일을 수정하면 이 파일만 다시 빌드 한 후 링크한다.

leeyosam$ make

gcc -W -Wall -c -o calendar.o calendar.c

gcc -W -Wall -o diary memo.o calendar.o main.o


Makefile기본 구조 및 규칙


CC    = gcc

target1 : dependency1 dependency2

command1

command2

1) 명령의 시작은 반드시 탭으로 시작된다.

2) 비어 있는 행은 무시된다.

3) #을 만나면 개행을 만날때까지 무시한다.

4) 행이 길어지면 \ 문자로 다음행에 이어서 기술이 가능하다.

diary : memo.o calendar.o\

main.o

==> diary : memo.o calendar.o main.o

5) ;는 명령행을 나눌때 사용한다.

target1 : dependency1 dependency2; command1

6) 종속항목이 없는 타겟도 가능하다

clean :

rm -rf *.0 target1 target2


매크로 규칙


1) 매크로명    = 매크로내용 형식

2) #은 주석의 시작

3) 여러행 기술시 \ 사용

4) 매크로 참조시에는 소괄호나 중괄호사용 가능하고 $를 앞에 붙이는데 쉘의 환경변수를 사용할때 중괄호를 사용하므로 해깔리지 않도록 소괄호사용이 권장된다.

NAME    = string

$(NAME)

5) 정의되지 않은 매크로는 빈문자(null)로 치환된다.

6) 중복정의하게 되면 마지막 값이 사용된다.

7) 매크로 정의시 이전에 정의된 매크로참조가 가능하다.

8) =, :=, +=, ?= 등 대입이 가능하다.

=  는  매크로정의 순서와 상관없이 매크로들을 모두 반영한다.

:= 는 매크로정의 순서 그대로 반영한다.

+= 는 기존 매크로에 추가한다.

?= 는 정의되지 않았으면 새로 반영하고 정의되어 있으면 반영하지 않는다.

A    = $(B) BB

B    = $(C) CC

C    = D

==> 이 경우 A는 D CC BB 가 된다.

a    := $(b) bb

b    := $(c) cc

c    := d

==> 이 경우 a 는 bb가 된다. 순차적으로 반영이 되므로 a를 정의할때의 bb가 b의 값이 새로 정의되더라도 a에 반영되지 않는다.


내부적으로 정의되어 있는 매크로의 사용


make -p명령으로 내부 매크로리스트를 확인할 수 있다. 미리 정의된 매크로들을 추가로 정의할 필요가 없다. 

많이 사용하는 매크로들은 다음 명령어로 확인 가능하다

make -p | grep ^[[:alpha:]]*[[:space:]]*=[[:space:]]

매크로 이름

설명

기본값

AR

아카이브 관리 프로그램

ar

AS

어셈블러

as

CC

C 컴파일러

cc

CXX

C++ 컴파일러

g++

CO

RCS checkout 프로그램

co

CPP

C 전처리기

cc E

FC

포트란 컴파일러

f77

GET

SCCS 관련 프로그램

get

LD

링크

ld

LEX

스캐너 코드 생성기

lex

PC

파스칼 컴파일러

pc

YACC

파서 코드 생성기

yacc

MAKEINFO

Texinfo 파일을 Info 파일로 변환

makeinfo

TEX

TeX 문서로부터 TeX DVI 생성

tex

TEXI2DVI

Texinfo 파일을 dvi 파일로 변환 프로그램

texi2dvi

WEAVE

Web TeX로 변환

weave

CWEAVE

C Web TeX로 변환

cweave

TANGLE

Web을 파스칼로 변환

tangle

CTANGLE

C Web C로 변환

ctangle

RM

파일을 지우는 명령

rm f

ARFLAGS

ar 플래그

rv

ASFLAGS

어셈블러 플래그

 

CFLAGS

C 컴파일러 플래그

 

CXXFLAGS

C++ 컴파일러 플래그

 

COFLAGS

RCS co 플래그

 

CPPFLAGS

C 전처리기 플래그

 

FFLAGS

포트란 컴파일러 플래그

 

GFLAGS

SCCS get 플래그

 

LDFLAGS

링크 플래그

 

LFLAGS

Lex 플래그

 

PFLAGS

파스칼 컴파일러 플래그

 

YFLAGS

Yacc 플래그

 


make -p로 확인불가능한 추가 내부 매크로

$?

현재의 타겟보다 최근에 변경된 종속 항목 리스트

(확장자 규칙에서 사용 불가)

$^

현재 타겟의 종속 항목 리스트

(확장자 규칙에서 사용 불가)

$@

현재 타겟의 이름

$<

현재 타겟보다 최근에 변경된 종속 항목 리스트

(확장자 규칙에서만 사용 가능)

$*

현재 타겟보다 최근에 변경된 현재 종속 항목의 이름(확장자 제외)

(확장자 규칙에서만 사용 가능)

$%

현재의 타겟이 라이브러리 모듈일 때 .o 파일에 대응되는 이름

${@F}현재 타겟의 파일 부분(target)

${<F}: 현재 디펜던시항목의 파일 부분(test.c)

${@D}: 현재 타겟의 디렉토리 부분(/temp)

${<D}: 현재 디펜던시항목의 디렉토리 부분(/usr/local/c)


$@와 $^는 다음과 같이 사용될 수 있다.

target : dependency1.c dependency2.c

             gcc -o target dependency1.c dependency2.c

==> 

target : dependency1.c dependency2.c

             gcc -o $@ $^


${@F}와 ${<F}, 그리고 ${@D}와 ${<D}는 다음 타겟과 디펜던시가 있을 경우

 /temp/target : /usr/local/c/test.c

==>

${@F} : target

${<F} : test.c

${@D} : /temp

${<D} : /usr/local/c


확장자 규칙의 사용


make -p로 출력되는 내용 중에 %.o : %c 가 있다.

%o : %c

$(COMPILE.c) $(OUTPUT_OPTION) $<

이는 *.o타겟이고 확장자가 c인 c 코드파일을 만나면 c -o $@ $<를 수행하라는것이다.

다음 Makefile은 맨처음 이 문서에서 작성한 Makefile과 동일한 동작을 수행한다.

OBJECTS    = memo.o calendar.o main.o

all : diary

diary : $(OBJECTS)

$(CC) -o $@ $^

OBJECTS에 정의된 dependency들을 처리하는데 타겟이 *.o이고 확장자가 *.c인것들을 만나게 된다. 이 때 make는 다음 순서로 처리하게 된다.

1) Makefile에서  diary를 생성하기 위해 make는 dependency들을 살펴보고 각 각을 타겟으로 설정한다.

2) diary는 memo.o에 의존하고 있고 memo.o는 만들어져 있지 않으면 memo.o를 만들어야 하는게 룰이 정의되어 있지 않다. 

3) 따라서 make는 내부 확장자 규칙 .o를 참조하여 다음 기준으로 현재 디렉토리에서 memo.o를 생성할 파일을 찾는다

- 확장자를 제외하고 memo.0와 같은 이름이 있어야 한다. memo.c가 해당된다.

- 중요확장자를 가지고 있어야 한다. .c, .cc, .cpp, .s, .S, ... 등

- 내부확장자 규칙에 따라 memo.o를 만드는데 사용할 수 있어야 한다. make -p로 확인해본바 %.o : %.c가 있기 떄문에 가능하다.

4) 내부정의 확장자 규칙에 따라 memo.o를 생성한다. cc -c -o memo.o memo.c 가 수행된다.


내부확장자 규칙을 변경하고자 하는 경우에는 .SUFFIXES 타겟으로 가능하다. 다음 Makefile예는 -DDEBUG 옵션을 추가하는 예제이다.

OBJECTS    = memo.o calendar.o main.o

.SUFFIXES : .o .c

$(CC) -DDEBUG -c -o $@ $<

all : diary

diary : $(OBJECTS)

$(CC) -o $@ $^



명령어 사용 규칙

echo :
@echo "echo test!"
위 명령어를 실행하면 새로운 쉘이 뜨고 echo명령이 실행된다고 함. 그런데 우분투와 맥에서 안그러던데???. 내가 참조한 책이 좀 옜날 얘기를 하는것인지 모르겠음.
무튼 주의할것은...
어떤 명령이 성공했을때만 다음 작업을 해야 하는 경우가 있을 수 있다.
del :
cd ./backup
rm -rf*
위 명령의 cd ./backup이 실패한다면 현재 폴더의 모든 내용이 삭제될것이다. 아마 머리를 쥐어잡고 울부짖게 되겠지...
이걸 피하기 위해서 아래와 같이 한다.
del :
cd ./backup && rm -rf*
&&은 명령이 성공하였는지를 추가로 검사한다.
명령의 성공이라함은 c의 main함수가 반환하는 수가 0인경우를 말한다.
c로 만든 프로그램에서 0반환은 성공을 의미하며 0이 아닌 수를 반환하는것은 어떤 에러가 났음을 의미한다.
리눅스에서 바로전에 호출한 명령이 반환한 값을 확인하고 싶으면 $?를 입력해보면 된다.
del :
cd ./backup; rm -rf* 
위 와 같이 하면 하나의 쉘에서 연달아 명령을 수행할 수 있다고 한다. 하지만 이것도 우분투와 맥에서 ; 없이도 하나의 쉘에서 잘 동작한다.

모든 명령에 대해 에코기능을 끄려면 .SILENT : 타겟을 정의한다. 이 타겟에 등록한 디펜던시들의 명령어들은 모두 에코기능이 꺼지게 된다.

make는 명령어가 에러를 발생시키면 중단시킨다. 그런데 에러가 나도 중단시키기 않고 빌드를 계속 진행하고자 한다면 - 를 명령어 앞에 넣으면 된다.
cat :
-cat dummy.txt

Makefile전체에서 명령어 오류를 무시하고자 한다면 .IGNORE : 타겟을 사용한다. 여기에 적시한 디펜던시들은 명령어가 오류가 나도 무시하고 진행된다.


재귀적 make사용

소스가 많아지면 여러 폴더로 소스를 나누어서 빌드하면 관리가 아주 유용하다.
재귀적 make말고 VPATH를 이용하는 방법도 있으나 파일명에 종속되기 때문에 재귀적 make가 더 효율적이도 더 많이 사용된다.

아래와 같이 소스파일이 분포 시켰다.

leeyosam$ tree

.

├── Makefile

├── calendar

│   ├── Makefile

│   └── calendar.c

├── include

│   └── diary.h

├── main

│   ├── Makefile

│   └── main.c

└── memo

    ├── Makefile

    └── memo.c


여기서 calendar, main,  memo폴더 내의 Makefile은 모두 아래와 같이 정의된다.

OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
CFLAGS = -I../include

all : $(OBJECTS)
cp -f $^ ../
clean :
rm -rf *.o

$(patsubst %.c, %.o, $(wildcard *.c)) 구문은 함수에서 다시 설명하겠지만 해석하자면 확장자가 c인파일을 찾아서 o로 바꾸는 동작을 수행한다.

그리고 최상위 위치의 Makefile은 아래와 같다.

DIRS = memo calendar main
OBJECTS = memo.o calendar.o main.o
TARGET = diary

all : objs
$(CC) -o $(TARGET) $(OBJECTS)

objs :
@for dir in $(DIRS); do \
make -C $$dir || exit $?; \
done
clean :
@for dir in $(DIRS); do \
make -C $$dir clean; \
done
-rm -rf *.o $(TARGET)

@for구문을 사용해서 단순화하였는데 DIRS에 기술한 폴더들을 루프를 돌면서 make를 수행하고 exit $? 이전 경로로 돌아가고 있다.
위와 같이 구성하면 소스폴더가 생길때마다 폴더를 추가하는것으로 끝나게 된다.

서브 Makefile에 대한 매크로 전달

최상위 Makefile에서 정의한 매크로를 서브 Makefile에서도 사용하고자 하는 경우가 있을것이다. 이 때는 export키워드를 사용한다.

export CC    = gcc

조건부 수행

C의 if else에 해당하는 구문
ifeq ($(CC),gcc)        # 반대는 ifneq
@echo "GNU GCC compiler.."
else
@echo "$(CC) compiler"
endif


함수의 사용


make는 Makefile에서 사용할 수 있는 여러 함수들을 제공한다.

$(shell 쉘명령어) : 쉘명령어를 수행하고 결과를 리턴한다.

SRCS = $(shell ls *.c)

echo :

@echo $(SRCS)

$(subst 찾을문자열, 변경할문자열, 목표문자열)  : 목표문자열에서 찾을문자열을 찾아서 변경할문자열로 변경한다.

STR    = $(subst like, LIKE, I like you)

==>  I LIKE you 를 찍게 된다.

$(patsubst 패턴, 변경문자열, 목표문자열) : subst와 다른점은 패턴을 발견하면 변경문자열로 변경한다. %기호가 사용될 수 있다.

STR    = $(patsubst %.c, %.o, memo.c main.c ABCD)

==> memo.o main.o ABCD

$(매크로명: 패턴=치환할문자열) : 매크로에서 패턴을 발견하면 변경한다.

MACRO    = memo.c main.c ABCD

STR       = $(MACRO:%.c=%.o)

$(sort 문자열) : 문자열의 인자들을 정렬하며 중복된것은 하나로 인식한다.

MACRO    = bbb aaa ccc aaa ddd

STR    = $(sort $(MACRO))

==> aaa bbb ccc ddd

$(strip 문자열) : 인자로 오는 문자열의 앞뒤의 공백을 제거하고 문자열내의 공백은 한칸으로 줄인다. 가령 'I love you.      ' 같은 문자열은 'I love you.'로 변경된다.

$(filter 패턴, 문자열) : 패턴과 일치하는 문자열만 걸러준다. 소스와 헤더파일이 섞여 있는 경우 소스와 헤더파일을 각각 읽어올때 유용하다.

FILES    = memo.c head.h mein.c asm.S diary.h

SRCS    = $(filter %c %S, $(FILES))

HEADERS    = $(filter %h, $(FILES))

$(filter-out 패턴, 문자열) : filter 의 반대

$(findstring 찾을 문자열, 대상문자열)

$(words 문자열) : 문자열내에서 사용된 단어들의 개수를 리턴한다.

$(word [n], 문자열) : 문자열내의 n번째 문자열을 리턴한다.

$(wordlist 시작번호, 끝번호, 문자열) : 문자열의 시작번호와 끝번호사이의 문자열을 리턴한다.

$(firstword 문자열) : 문자열에서 첫번째 단어를 리턴한다.

$(join 문자열, 문자열) : 앞뒤의 문자열을 합친다.

$(dir 문자열) : 문자열에서 디렉토리부분만 리턴한다.

PATHS    = /bin/ls /sbin/ifconfig memo/memo.c Makefile

echo : 

@echo $(dir $(PATHS))

==> /bin/ /sbin/ memo/ ./  

$(notdir 문자열) : 문자열에서 디렉토리부분만 제외하고 리턴한다.

==> ls i fconfig memo.c Makefile

$(suffix 문자열) : 문자열에서 확장자만 리턴한다.

FILES    = src/memo.c asm/asm.S for.f ls /etc/resolv.conf

echo :

@echo $(suffix $(FILES))

==> .c .S .f .conf

$(basename 문자열) : 문자열에서 점과 확장자를 제외한 순수한 파일명만 리턴한다.

==> src/memo asm/asm for ls /etc/resolv

$(addsuffix 접미사, 문자열) : 문자열에 접미사를 추가한다.

$(addprefix 접두사, 문자열) : 문자열에 접두사를 추가한다.

$(wildcard 패턴) : wildcard 패턴결과를 리턴한다.

$(foreach 변수명, 대입문자열, 확장문자열) : 변수명에 대입문자열을 단어별로 대입하여 넣고 그 변수를 ㅎ ㅘㄱ장문자열에서 사용한다.

SRCS    = $(foreach str, a b c, $(str).c)

echo :

@echo $(SRCS)

==> a.c b.c c.c

주로 다음과 같이 반복확장시 유용하다.

SRCS    = $(foreach dir, . memo main calendar, $(wildcard $(dir)/*.c))

echo :

@echo $(SRCS)

Posted by 삼스
임베디드/개발툴2009. 3. 21. 21:59
Posted by 삼스
임베디드/개발툴2009. 3. 17. 15:28

저장소 만들기

svnadmin create [디렉토리명]

 

Import

svn import (-m) . [저장소경로]

 

체크아웃

svn  checkout  [저장소경로]  [workspace]

checkout = co

 

Workspace 정보

svn  info  [workspace]

 

커밋

svn commit (-m)

 

갱신(update)

svn  update

: 기본으로 하위 디렉토리 모두 갱신

[ A ] 저장소에 새로 추가된 파일을 Workspace로 받아옴

[ U ] 저장소에 새 버전이 체크인 되어 Workspace의 파일을 그 버전으로 갱신함 (Workspace 파일의 버전이 체크 아웃된 이후 변경되지 않아야 함)

[ D ] 저장소에서 해당파일이 삭제되어 Workspace에서도 삭제됨

[ G ] 여러 사람이 동일한 파일을 수정했더라도 서로 다른 부분을 변경했다면 서브버전이 그 변경들을 자동으로 합쳐준다. 자동으로 병합된 경우 (Workspace 파일의 버전이 체크 아웃된 이후 변경되었고, 저장소의 버전이 체크 아웃 당시의 버전보다 최신인 경우)

[ C ] [ G ]의 상황에서 같은 부분을 변경한 경우에 서브버전이 자동적으로 병합하지 못해, 충돌(Conflict)이 발생하였음, 사람이 해결해야 함

 

저장소에 추가 위해 Workspace의 항목을 지정

svn  add  [항목]

: 반영은 항상 commit 할 때

 

COPY

svn  copy  [원본항목]  [복사될 항목]

copy = cp

 

Log

svn  log  [-r옵션]  [항목]

 

MOVE = 이름 변경

svn  move  [이전항목]  [이후항목]

move = mv

 

저장소에서 삭제 위해 Workspace에서 설정

svn  delete  [항목]

 

차이 보기

svn  diff  [-r옵션]  [항목]

 

변경 제거

svn  revert  [항목]

: 체크 아웃 상태로 돌아감

 

충돌 해결

svn  resolved  [항목]

 

책임

svn  blame  [항목]

 

Merge

svn  merge  [-r옵션]  [항목]

 

상태

svn  status  (-show-updates=-u)

 

 

[-r옵션]

-rHEAD : 저장소의 가장 최신 리비전

-rBASE : 작업장의 기반 리비전, 체크아웃(or 갱신) 했을 당시의 리비전

-rCOMMITTED : BASE 또는 그 이전 리비전들 중에서 해당 항목이 마지막으로 변경된 리비전

-rPREV : COMMITTED 직전 리비전

-r [#revision]:[#revision] : 해당 리비전의 범위 지정

-r [#revision] : 해당 리비전

 

[항목] : 파일 이나 디렉토리를 의미


Posted by 삼스

FreeType 2 Tutorial
Step 1 — simple glyph loading

© 2003, 2006, 2007 David Turner (david@freetype.org)

Introduction

This is the first section of the FreeType 2 tutorial. It will teach you how to:

  • initialize the library 라이브러리의 초기화
  • open a font file by creating a new face object 파일로부터 새로운 faceobject의 생성
  • select a character size in points or in pixels 문자크기를 point나 pixel로 선택
  • load a single glyph image and convert it to a bitmap 하나의 glyph image를 로드하고 비트맵으로 변환하는 과정
  • render a very simple string of text  간단한 문자표시
  • render a rotated string of text easily 쉬운 문자회전방법

1. Header files

The following are instructions required to compile an application that uses the FreeType 2 library. 아래는 FreeType2 library를 사용하는 app에서 컴파일하는대 필요한 과정이다.

  1. Locate the FreeType 2 include directory.include directory로 위치를 잡을것.

    You have to add it to your compilation include path. 컴파일 경로상에 include path를 포함할것. 

    Note that on Unix systems, you can now run the freetype-config script with the --cflags option to retrieve the appropriate compilation flags. This script can also be used to check the version of the library that is installed on your system, as well as the required librarian and linker flags.

  2. Include the file named ft2build.h.

    It contains various macro declarations that are later used to #include the appropriate public FreeType 2 header files. 관련되는 header file들을 적절히 호함시켜주는 ft2build.h를 포함시킬것

  3. Include the main FreeType 2 API header file.

    You should do that using the macro FT_FREETYPE_H, like in the following example: 아래와 같이 FT_FREETYPE_H를 추가할것.

    #include <ft2build.h> 
    #include FT_FREETYPE_H

    FT_FREETYPE_H is a special macro defined in the file ftheader.h. It contains some installation-specific macros to name other public header files of the FreeType 2 API. FT_FREETYPE_H는 설치관련 macro를 포함한다.

    You can read this section of the FreeType 2 API Reference for a complete listing of the header macros. header macro의 전체를 보려면 API Reference를 참조하라 

The use of macros in #include statements is ANSI-compliant. It is used for several reasons:

  • It avoids some painful conflicts with the FreeType 1.x public header files.

  • The macro names are not limited to the DOS 8.3 file naming limit; names likeFT_MULTIPLE_MASTERS_H or FT_SFNT_NAMES_H are a lot more readable and explanatory than the real file names ftmm.h and ftsnames.h.

  • It allows special installation tricks that will not be discussed here.

NOTE: Starting with FreeType 2.1.6, the old header file inclusion scheme is no longer supported. This means that you now get an error if you do something like the following:

#include <freetype/freetype.h> #include <freetype/ftglyph.h> ...

2. Initialize the library

Simply create a variable of type FT_Library named, for example, library, and call the function FT_Init_FreeType as in

#include <ft2build.h> 
#include FT_FREETYPE_H 
FT_Library library; 
... 
error = FT_Init_FreeType( &library ); 
if ( error ) 
... an error occurred during library initialization ... 
}

This function is in charge of the following:

  • It creates a new instance of the FreeType 2 library, and sets the handlelibrary to it. Freetype2 library의 인서턴스를 생성하고 핸들을 설정한다.

  • It loads each module that FreeType knows about in the library. Among others, your new library object is able to handle TrueType, Type 1, CID-keyed & OpenType/CFF fonts gracefully. 서로다른 폰트타입(Truetype, Type1, CID-keyed...)들을 다른 library로 생성하여 모듈로 로등하여 사용할수 있다.

As you can see, the function returns an error code, like most others in the FreeType API. An error code of 0 always means that the operation was successful; otherwise, the value describes the error, and library is set to NULL. 대부분의 함수의 리턴되는 error code중 0은 successfull을 의미한다.


3. Load a font face

a. From a font file

Create a new face object by calling FT_New_Face. A face describes a given typeface and style. For example, ‘Times New Roman Regular’ and ‘Times New Roman Italic’ correspond to two different faces.

FT_Library library; /* handle to library */ FT_Face face; /* handle to face object */error = FT_Init_FreeType( &library ); if ( error ) { ... } error = FT_New_Face( library, "/usr/share/fonts/truetype/arial.ttf", 0, &face ); if ( error == FT_Err_Unknown_File_Format ) { ... the font file could be opened and read, but it appears ... that its font format is unsupported } else if ( error ) { ... another error code means that the font file could not ... be opened or read, or simply that it is broken... }

As you can certainly imagine, FT_New_Face opens a font file, then tries to extract one face from it. Its parameters are

library

A handle to the FreeType library instance where the face object is created.

filepathname

The font file pathname (a standard C string).

face_index

Certain font formats allow several font faces to be embedded in a single file.

This index tells which face you want to load. An error will be returned if its value is too large.

Index 0 always work though.

face

pointer to the handle that will be set to describe the new face object.

It is set to NULL in case of error.

To know how many faces a given font file contains, simply load its first face (this is, face_index should be set to zero), then check the value of face->num_faceswhich indicates how many faces are embedded in the font file.

b. From memory

In the case where you have already loaded the font file into memory, you can similarly create a new face object for it by calling FT_New_Memory_Face as in

FT_Library library; /* handle to library */ FT_Face face; /* handle to face object */error = FT_Init_FreeType( &library ); if ( error ) { ... } error = FT_New_Memory_Face( library, buffer, /* first byte in memory */ size, /* size in bytes */ 0, /* face_index */ &face ); if ( error ) { ... }

As you can see, FT_New_Memory_Face simply takes a pointer to the font file buffer and its size in bytes instead of a file pathname. Other than that, it has exactly the same semantics as FT_New_Face.

Note that you must not deallocate the memory before calling FT_Done_Face.

c. From other sources (compressed files, network, etc.)

There are cases where using a file pathname or preloading the file into memory is simply not sufficient. With FreeType 2, it is possible to provide your own implementation of i/o routines.

This is done through the FT_Open_Face function, which can be used to open a new font face with a custom input stream, select a specific driver for opening, or even pass extra parameters to the font driver when creating the object. We advise you to refer to the FreeType 2 reference manual in order to learn how to use it.


4. Accessing face content

face object models all information that globally describes the face. Usually, this data can be accessed directly by dereferencing a handle, like in face−>num_glyphs.

face object는 face에 대한 전체를 기술하는 모든 정보를 표현(model)한다. 보통 handle로부터 역참조하는 방식으로 데이터에 접근한다(예: face->num_glyphs)

The complete list of available fields in in the FT_FaceRec structure description. However, we describe here a few of them in more details: FT_FaceRec구조체에 모든 데이터필드가 정의되어 있다. 그중 중요한 몇가지만 자세히 설명하겟다.

num_glyphs

This variable gives the number of glyphs available in the font face. A glyph is simply a character image. It doesn't necessarily correspond to a character code though. font face에서 실제 유용한 glyph의 개수이다. 하나의 glyph는 하나의 문자이미지이다.character code와 일치할필요 없다.

flags

A 32-bit integer containing bit flags used to describe some face properties. For example, the flag FT_FACE_FLAG_SCALABLEis used to indicate that the face's font format is scalable and that glyph images can be rendered for all character pixel sizes. For more information on face flags, please read theFreeType 2 API Reference32bit정수값으로 face 속성을 기술한다. 예를 들어 FT_FACE_FLAG_SCALABLE은 font format이 scalable한지를 나타내고 glyph image가 모든 문자 픽셀크기로 렌더가능한지를 의미한다. 자세한 정보는 API Reference를 참조하라.

units_per_EM

This field is only valid for scalable formats (it is set to 0 otherwise). It indicates the number of font units covered by the EM. scalable format에서만 유효하며, EM이 커버가능한 font unit의 개수를 나타낸다.

num_fixed_sizes

This field gives the number of embedded bitmap strikes in the current face. A strike is simply a series of glyph images for a given character pixel size. For example, a font face could include strikes for pixel sizes 10, 12 and 14. Note that even scalable font formats can have embedded bitmap strikes! 현재face에 strike된 embedded bitmap의 개수를 나타낸다. 하나의 strike는 주어진 character pixel size로 된 glyph image들의 시리즈이다. 예를 들면 어떤 font face는 pixel size로 10, 12, 14를 strike한다. saclable font format도 embedded bitmap 을 strike할수 있다.

fixed_sizes

A pointer to an array of FT_Bitmap_Size elements. EachFT_Bitmap_Size indicates the horizontal and vertical character pixel sizes for each of the strikes that are present in the face.FT_Bitmap_Size요소 배열의 포인터, 각 FT_Bitmap_Size는 face에서 제공하는 strike들의 각각의 가로/세로 픽셀사이즈를 나타낸다.

Note that, generally speaking, these are not the cell size of the bitmap strikes.


5. Setting the current pixel size

FreeType 2 uses size objects to model all information related to a given character size for a given face. For example, a size object will hold the value of certain metrics like the ascender or text height, expressed in 1/64th of a pixel, for a character size of 12 points.

When the FT_New_Face function is called (or one of its cousins), it automaticallycreates a new size object for the returned face. This size object is directly accessible as face−>size.

NOTE: A single face object can deal with one or more size objects at a time; however, this is something that few programmers really need to do. We have thus decided to simplify the API for the most common use (i.e., one size per face) while keeping this feature available through additional functions.

When a new face object is created, all elements are set to 0 during initialization. To populate the structure with sensible values, simply call FT_Set_Char_Size. Here is an example where the character size is set to 16pt for a 300×300dpi device:

error = FT_Set_Char_Size( face, /* handle to face object */ 0, /* char_width in 1/64th of points */ 16*64, /* char_height in 1/64th of points */ 300, /* horizontal device resolution */ 300 ); /* vertical device resolution */

Some notes:

  • The character widths and heights are specified in 1/64th of points. A point is a physical distance, equaling 1/72th of an inch. Normally, it is not equivalent to a pixel.

  • The horizontal and vertical device resolutions are expressed in dots-per-inch, or dpi. Normal values are 72 or 96 dpi for display devices like the screen. The resolution is used to compute the character pixel size from the character point size.

  • A value of 0 for the character width means ‘same as character height’, a value of 0 for the character height means ‘same as character width’. Otherwise, it is possible to specify different character widths and heights.

  • A value of 0 for the horizontal resolution means ‘same as vertical resolution’, a value of 0 for the vertical resolution means ‘same as horizontal resolution’. If both values are zero, 72 dpi is used for both dimensions.

  • The first argument is a handle to a face object, not a size object.

This function computes the character pixel size that corresponds to the character width and height and device resolutions. However, if you want to specify the pixel sizes yourself, you can simply call FT_Set_Pixel_Sizes, as in

error = FT_Set_Pixel_Sizes( face, /* handle to face object */ 0, /* pixel_width */16 ); /* pixel_height */

This example will set the character pixel sizes to 16×16 pixels. As previously, a value of 0 for one of the dimensions means ‘same as the other’.

Note that both functions return an error code. Usually, an error occurs with a fixed-size font format (like FNT or PCF) when trying to set the pixel size to a value that is not listed in the face->fixed_sizes array.


6. Loading a glyph image 

a. Converting a character code into a glyph index

Usually, an application wants to load a glyph image based on its character code, which is a unique value that defines the character for a given encoding. For example, the character code 65 represents the ‘A’ in ASCII encoding. 일반적으로 application은 char code에 기반한 glyph image를 load하기를 기대한다. 이 code는 encoding방식내에서 유일한 값이다. 예를 들면 ASCII encoding에서 code 65는 'A'이다.

A face object contains one or more tables, called charmaps, that are used to convert character codes to glyph indices. For example, most TrueType fonts contain two charmaps. One is used to convert Unicode character codes to glyph indices, the other is used to convert Apple Roman encoding into glyph indices. Such fonts can then be used either on Windows (which uses Unicode) and Macintosh (which uses Apple Roman). Note also that a given charmap might not map to all the glyphs present in the font. face object는 하나이상의 charmap을 가지고 있으며 char code를 glyph index로 변환하는데 사용된다. 예를 들면 대부분의 Truetype font는 2개의 charmap을 가지고 있다. 하나는 unicode char codemap이고 다른 하나는 Apple roman encoding map이다. 따라서 이는 윈도만이 아니라 매킨토시에서도 동작한다. 폰트가 모든 charmap을 지원하지 않는다.

By default, when a new face object is created, it selects a Unicode charmap. FreeType tries to emulate a Unicode charmap if the font doesn't contain such a charmap, based on glyph names. Note that it is possible that the emulation misses glyphs if glyph names are non-standard. For some fonts, including symbol fonts and (older) fonts for Asian scripts, no Unicode emulation is possible at all. 기본적으로 새로운 face object가 생성될 때 unicode charmap을 선택하게된다. freetype은 font가 charmap이 없으면 unicode charmap을 emulate를 glyph name으로 시도한다. 이는 glyph name이 non-standard이면 emulation이 실패할수 있음을 말한다.  일부 폰트의 경우 symbol이나 asian scriptr를 위한 (오래된) 폰트들은 더이상 unicode emulation을 지원하지 않는다.

We will describe later how to look for specific charmaps in a face. For now, we will assume that the face contains at least a Unicode charmap that was selected during a call to FT_New_Face. To convert a Unicode character code to a font glyph index, we use FT_Get_Char_Index, as in 나중에 face에서 특정 charmap을 찾는 방법에 대해 설명할 것이다. 여기서는 FT_New_Face로 선택한 font가 최소한 unicode charmap은 포함한다는 가정을 할것이다. unicode char code를 glyph index로 변환하기 위해서 우리는 FT_Get_Char_Index를 사용한다.

glyph_index = FT_Get_Char_Index( face, charcode );

This will look the glyph index corresponding to the given charcode in the charmap that is currently selected for the face. If no charmap was selected, the function simply returns the charcode. 위코드는 charmap상에서 charcode에 해당하는 glyph index를 얻어낸다. charmap이 선택되지 않았다면 그냥 charcode를 리턴한다.

Note that this is one of the rare FreeType functions that do not return an error code. However, when a given character code has no glyph image in the face, the value 0 is returned. By convention, it always correspond to a special glyph image called the missing glyph, which is commonly displayed as a box or a space. 이 함수는 에러코드를 리턴하지 않는 드문 freetype함수중 하나이다. charcode가 face내에서 유효한 glyph image를 얻지 못하면 0을 리턴한다. 

b. Loading a glyph from the face

Once you have a glyph index, you can load the corresponding glyph image. The latter can be stored in various formats within the font file. For fixed-size formats like FNT or PCF, each image is a bitmap. Scalable formats like TrueType or Type 1 use vectorial shapes, named outlines to describe each glyph. Some formats may have even more exotic ways of representing glyphs (e.g., MetaFont — but this format is not supported). Fortunately, FreeType 2 is flexible enough to support any kind of glyph format through a simple API. 하나의 glyph index를 얻으면 대응되는 glyph image를 로드할수 있다. font file에 다양한 포맷으로 저장되어 있다. fixd-size포맷(FNT, PCF)는 각 이미지가 하나의 비트맵으로 되어 있다. Scalable format(Truetype, Type1)은 vectorial shape(outline으로 불림.)을 가지고 있다. 어떤 포맷은 훨씬 징그러운 방법으로 glyph을 표현한다(MetaFont같은 폰트-지원하지 않음). Freetype은 다행히 많은 포맷을 지원한다.

The glyph image is always stored in a special object called a glyph slot. As its name suggests, a glyph slot is simply a container that is able to hold one glyph image at a time, be it a bitmap, an outline, or something else. Each face object has a single glyph slot object that can be accessed as face->glyph. Its fields are explained by the FT_GlyphSlotRec structure documentation.  glyph image는 glyph slot이라는 틀별한 객채에 항상 저장된다. 이름에서 느껴지듯이 glayph slot은 단순히 bitmap, outline등으로 되어 있는 하나의 glayph image을 한번에 하나씩 가지고 있다. 각 face object는 하나의 glyph slot object를 가지고 있으며 face->glyph로 접근 가능하다. 이 필드는 FT_GlyphSlotRec구조체에 설명되어 있다.

Loading a glyph image into the slot is performed by calling FT_Load_Glyph as inFT_Load_Glyph를 호출하여 slot으로 glyph image를 로드한다.

error = FT_Load_Glyph( face, /* handle to face object */ 
glyph_index, /* glyph index */ 
load_flags ); /* load flags, see below */

The load_flags value is a set of bit flags used to indicate some special operations. The default value FT_LOAD_DEFAULT is 0. load_flag(bit flag의 set)가 몇가지 특별한 동작을 위해 사용된다.

This function will try to load the corresponding glyph image from the face: 이 함수는 face로부터 대응되는 glyph image를 로드한다.

  • If a bitmap is found for the corresponding glyph and pixel size, it will be loaded into the slot. Embedded bitmaps are always favored over native image formats, because we assume that they are higher-quality versions of the same glyph. This can be changed by using the FT_LOAD_NO_BITMAP flag.대응하는 glyph와 pixel size에 맞는 비트맵이 발견되면 slot으로 로드될것이다. ??

  • Otherwise, a native image for the glyph will be loaded. It will also be scaled to the current pixel size, as well as hinted for certain formats like TrueType and Type 1.  그렇지 않으면 native image가 로드될것이다. 

The field face−>glyph−>format describes the format used to store the glyph image in the slot. If it is not FT_GLYPH_FORMAT_BITMAP, one can immediately convert it to a bitmap through FT_Render_Glyph as in: face->glyph->format은 slot에서 사용되는 glyphimage의 포맷을 나타낸다. 만일 FT_GLYPH_FORMAT_BITMAP이 아니면 FT_Render_Glyph로 즉시 bitmap으로 변환할수 있다.

error = FT_Render_Glyph(
  face->glyph, /* glyph slot */ 
  render_mode ); /* render mode */

The parameter render_mode is a set of bit flags used to specify how to render the glyph image. Set it to FT_RENDER_MODE_NORMAL to render a high-quality anti-aliased (256 gray levels) bitmap, as this is the default. You can alternatively useFT_RENDER_MODE_MONO if you want to generate a 1-bit monochrome bitmap.render_mode파라메터는 bit flag set으로 glyph image의 렌더링 방식을 나타낸다. FT_RENDER_MODE_NORMAL은 고품질 anti-aliased(256 gray level) bitmap으로 렌더링함을 말한다(default setting).  FT_RENDER_MODE_MONO로 1-bit monochrome bitmap으로 생성할 수도 있다.

Once you have a bitmapped glyph image, you can access it directly through glyph->bitmap (a simple bitmap descriptor), and position it through glyph->bitmap_leftand glyph->bitmap_top glyph image로 bitmap으로 만들어지면 glyph->bitmap(간단한 bitmap descriptor)로 바오 접근가능하며 glyph->bitmap_left와 glyph->bitmap_top으로 위치에 접근할 수 있다.

Note that bitmap_left is the horizontal distance from the current pen position to the leftmost border of the glyph bitmap, while bitmap_top is the vertical distance from the pen position (on the baseline) to the topmost border of the glyph bitmap. It is positive to indicate an upwards distance bitmap_left는 glyph bitmap의 가장좌측 경계에서 현재 pen위치의 가로거리를 말한다. bitmap_top은 최상단경계 에서 현재위치(baseline)까지의 새로거리이다. 

The next section will give more details on the contents of a glyph slot and how to access specific glyph information (including metrics). 다음섹션에서 더 자세히 설명한다.

c. Using other charmaps

As said before, when a new face object is created, it will look for a Unicode charmap and select it. The currently selected charmap is accessed via face->charmap. This field is NULL when no charmap is selected, which typically happens when you create a new FT_Face object from a font file that doesn't contain a Unicode charmap (which is rather infrequent today).  앞서 말한것 처럼, 새로운 face object가 생성될때 unicode charmap을 찾아서 선택한다. 현재 선택된 charmap은 face->charmap으로 접근가능하다. 이 field가 NULL이면 charmap이 선택되지 않은 것이다. 이 경우 font가 unicode charmap을 포함하지 않는 것이다.

There are two ways to select a different charmap with FreeType 2. The easiest is when the encoding you need already has a corresponding enumeration defined inFT_FREETYPE_H, for example FT_ENCODING_BIG5. In this case, you can simply callFT_Select_CharMap as in:  FreeType2에서 다른 charmap을 선택하는 두가지 방법이 제공된다.  가장 쉬운 방법은 FT_FREETYPE_H에 이미 열거하여 정의 해둔 값을 사용하는 것이다. 예를 들어 FT_ENCODING_BIG5의 경우 FT_Select_CharMap함수로 간단하게 사용가능하다.

error = FT_Select_CharMap( 
    face, /* target face object */ 
    FT_ENCODING_BIG5 ); /* encoding */

Another way is to manually parse the list of charmaps for the face; this is accessible through the fields num_charmaps and charmaps (notice the ‘s&rsquo) of the face object. As you could expect, the first is the number of charmaps in the face, while the second is a table of pointers to the charmaps embedded in the face. 다른 방법은 face의 charmap을 수동으로 검사하는 방법이다. num_charmaps필드와 charmaps필드를 통해서 접근가능하다. 기대한대로 첫번째는 num_charmaps는 face내의 charmaps의 개수이고 두번째는 charmap을 갖고 있는 배열을 포인터이다.

Each charmap has a few visible fields used to describe it more precisely. Mainly, one will look at charmap->platform_id and charmap->encoding_id that define a pair of values that can be used to describe the charmap in a rather generic way.  각 charmap은 더 자세한 정보를 표현하기 위해 몇가지 필드를 더 가지고 있다. charmap을 표현하는 일반적인 방법보다는 charmap->platform_id와 charmap->encoding_id의 쌍으로 정의된 값을 볼수 있다.

Each value pair corresponds to a given encoding. For example, the pair (3,1) corresponds to Unicode. The list is defined in the TrueType specification but you can also use the file FT_TRUETYPE_IDS_H which defines several helpful constants to deal with them. 각 쌍의 값들은 주어진 encoding에 대응된다. 예를 들어 쌍(3,1)은 unicode에 대응된다. 그 리스트는 truetype spec에 정의되어 있지만 FT_TRUETYPE_IDS_H파일을 사용할 수 있으며 이는 다루기 편하도록 몇가지 상수가 정의되어 있다.

To select a specific encoding, you need to find a corresponding value pair in the specification, then look for it in the charmaps list. Don't forget that there are encodings which correspond to several value pairs due to historical reasons. Here some code to do it:  특정encoding을 선택하려면, spec에서 대응되는 쌍의값을 찾아야 한다. 역사적인 이유들로 인해서 대응되는 몇가지 쌍의값들이 encoding값이라는 것을 기억하라.

FT_CharMap found = 0; 
FT_CharMap charmap; 
int n; 
for ( n = 0; n < face->num_charmaps; n++ ) 
{
    charmap = face->charmaps[n];
    if ( charmap->platform_id == my_platform_id && 
         charmap->encoding_id == my_encoding_id ) 
    { 
        found = charmap;
        break; 
    }
if ( !found ) { ... } /* now, select the charmap for the face object */
error = FT_Set_CharMap( face, found );
 if ( error ) { ... }

Once a charmap has been selected, either through FT_Select_CharMap orFT_Set_CharMap, it is used by all subsequent calls to FT_Get_Char_Index.FT_Select_CharMap이나 FT_Set_CharMap으로 charmap이 한번 선택되면, 이후의 모든 FT_Get_Char_Index의 호출에 영향을 준다.

d. Glyph transformations

It is possible to specify an affine transformation to be applied to glyph images when they are loaded. Of course, this will only work for scalable (vectorial) font formats. glyph image가 로드되었을 때 적용하기 위한 유사한 변환방식을 지정하는것이 가능하다.

To do that, simply call FT_Set_Transform, as in: FT_Set_Transform을 호출하면 된다.

error = FT_Set_Transform( face, /* target face object */ 
    &matrix, /* pointer to 2x2 matrix */ 
    &delta ); /* pointer to 2d vector */

This function will set the current transform for a given face object. Its second parameter is a pointer to a simple FT_Matrix structure that describes a 2×2 affine matrix. The third parameter is a pointer to a FT_Vector structure that describes a simple two-dimensional vector that is used to translate the glyph image after the 2×2 transformation. 이 함수는 현재의 변환을 face object에 set할것이다. 두번째 파라메터는 FT_Matric의 포인터이다. 이것은 2x2 affine matrix를 기술한다. 세번째 파라메터는 FT_Vector의 포인터이다. 이것은 2D vector를 기술하며 2x2 변환(transformation) 후에 glyph image을 변형(translate)하는데 사용된다.

Note that the matrix pointer can be set to NULL, in which case the identity transform will be used. Coefficients of the matrix are otherwise in 16.16 fixed float units. matrix pointer는 NULL로 설정가능하다. 이경우 identity transform이 사용될것이다. matrix의 계수는 16.16의 고정된 부동소수단위이다.

The vector pointer can also be set to NULL (in which case a delta of (0,0) will be used). The vector coordinates are expressed in 1/64th of a pixel (also known as 26.6 fixed floats). vector pointer도 NULL로 설정할 수 있다(이경우 delta값은 (0,0)이 사용된다). vector좌표는 하나의 픽셀의 1/64 로 표현된다(고정된 26.6 부동소수값).

NOTE: The transformation is applied to every glyph that is loaded throughFT_Load_Glyph and is completely independent of any hinting process. This means that you won't get the same results if you load a glyph at the size of 24 pixels, or a glyph at the size at 12 pixels scaled by 2 through a transform, because the hints will have been computed differently (except you have disabled hints). 

If you ever need to use a non-orthogonal transformation with optimal hints, you first have to decompose your transformation into a scaling part and a rotation/shearing part. Use the scaling part to compute a new character pixel size, then the other one to call FT_Set_Transform. This is explained in details in a later section of this tutorial.  향상된 힌트로 비직교변환을 할 필요가 있다면, 먼저 하나의 scaling part와 rotation/shearing part로 변환을 분해해야 한다. 새로운 character pixel size를 계산하기위해 scaling part를 사용하라, 이어서 이에 대해 더 자세히 설명할것이다.

Loading a glyph bitmap with a non-identity transformation works; the transformation is ignored in this case.


7. Simple text rendering

We will now present a very simple example used to render a string of 8-bit Latin-1 text, assuming a face that contains a Unicode charmap. 우리는 지금 8비트 라틴-1 으로된 문자열을 렌더링하는 간단한 예제를 제공할것이다.

The idea is to create a loop that will, on each iteration, load one glyph image, convert it to an anti-aliased bitmap, draw it on the target surface, then increment the current pen position.  루프안에서 계속해서 과정을 반복할것이다. 하나의 glyph image를 로드하고 -> anti-aliased bitmap으로 변환하고, 결과를 target surface에 그리고나서 pen위치를 증가시킨다.

a. Basic code

The following code performs our simple text rendering with the functions previously described. 아래코드가 위에서 기술한 방식으로 문자를 그리는 예제이다.

FT_GlyphSlot slot = face->glyph; /* a small shortcut */ 
int pen_x, pen_y, n;
 ... initialize library ... 
 ... create face object ...
 ... set character size ...

 pen_x = 300; pen_y = 200; 

 for ( n = 0; n < num_chars; n++ ) { 
    FT_UInt glyph_index; /* retrieve glyph index from character code */
    /* load glyph image into the slot (erase previous one) */
    glyph_index = FT_Get_Char_Index( face, text[n] ); 
       
    error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
    if ( error ) continue; /* ignore errors */

    /* convert to an anti-aliased bitmap */
    error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );
    if ( error ) continue; /* now, draw to our target surface */

    my_draw_bitmap( &slot->bitmap, pen_x + slot->bitmap_left,
                              pen_y - slot->bitmap_top ); /* increment pen position */
    pen_x += slot->advance.x >> 6;
    pen_y += slot->advance.y >> 6; /* not useful for now */ 
}

This code needs a few explanations:

  • We define a handle named slot that points to the face object's glyph slot. (The type FT_GlyphSlot is a pointer). That is a convenience to avoid usingface->glyph->XXX every time. face object의 glyph slot을 지정하는 handle을 정의한다(FT_GlyphSlot은 포인터이다). 그러면 매번 face->glyph->XXX로 호출할 불편함이 없다.

  • We increment the pen position with the vector slot->advance, which correspond to the glyph's advance width (also known as its escapement). The advance vector is expressed in 1/64th of pixels, and is truncated to integer pixels on each iteration. vector값인 slot->advance로 pen위치를 증가시킨다. 이 값은 glyph의 advance width에 대응되며 escapement로 알려져있다. advance vector는 1/64 pixel로 표현되고 각 반복시마다 integer로 truncate된다.

  • The function my_draw_bitmap is not part of FreeType but must be provided by the application to draw the bitmap to the target surface. In this example, it takes a pointer to a FT_Bitmap descriptor and the position of its top-left corner as arguments. my_draw_bitmap함수는 FreeType의 일부가 아니지만 target surface에 비트맵을 그리기 위해 app에서 반드시 제공되어야 한다. 여기서는 FT_Bitmap descriptor의 포인터를 취하여 파라메터로 top-left의 위치를 사용했다.

  • The value of slot->bitmap_top is positive for an upwards vertical distance. Assuming that the coordinates taken by my_draw_bitmap use the opposite convention (increasing Y corresponds to downwards scanlines), we subtract it from pen_y, instead of adding to it. slot->bitmap_top값은 positive for an upward이다. my_draw_bitmap에서 반대로 좌표를 취하는것을 보라(?), pen_y값을 더하지 않고 뺐다.

b. Refined code

The following code is a refined version of the example above. It uses features and functions of FreeType 2 that have not yet been introduced, and which are explained below: 다음은 위의 예제를 더 손좀 본 것이다. 아직 소개되지 않은 방법으로 구현한 예이다.

FT_GlyphSlot slot = face->glyph; /* a small shortcut */
FT_UInt glyph_index;
int pen_x, pen_y, n;

... initialize library ... 
... create face object ... 
... set character size ... 
pen_x = 300; pen_y = 200; 
for ( n = 0; n < num_chars; n++ ) { 
    /* load glyph image into the slot (erase previous one) */ 
    error = FT_Load_Char( face, text[n], FT_LOAD_RENDER ); 
    if ( error ) continue; /* ignore errors */ 
    /* now, draw to our target surface */ 
    my_draw_bitmap( &slot->bitmap, pen_x + slot->bitmap_left, 
           pen_y - slot->bitmap_top ); /* increment pen position */ 
    pen_x += slot->advance.x >> 6; 
}

We have reduced the size of our code, but it does exactly the same thing: code size를 줄였다. 죽이지 않는가? 

  • We use the function FT_Load_Char instead of FT_Load_Glyph. As you probably imagine, it is equivalent to calling FT_Get_Char_Index thenFT_Get_Load_Glyph. FT_Load_Char를 FT_Load_Glyph대신 사용했다. 예상하겠지만 FT_Get_Char_Index와 FT_Get_Load_Glyph를 호출한것과 동일하다.

  • We do not use FT_LOAD_DEFAULT for the loading mode, but the bit flagFT_LOAD_RENDER. It indicates that the glyph image must be immediately converted to an anti-aliased bitmap. This is of course a shortcut that avoids calling FT_Render_Glyph explicitly but is strictly equivalent. 여기서 loading mode로 FT_LOAD_DEFAULT를 사용하지 않고 FT_LOAD_RENDER를 사용했다. 이는 glyph image가 anti-aliased bitmap으로 바로 변환하게 한다. 문론 이것은 명시적으로 FT_Render_Glyph를 호출하는것을 피하는 쉬운방법이지만 정확하게 동일하다.

    Note that you can also specify that you want a monochrome bitmap instead by using the addition FT_LOAD_MONOCHROME load flag. FT_LOAD_MONOCHROME 을 사용하여 monochrome bitmap을 사용할수 있다.

c. More advanced rendering

Let us try to render transformed text now (for example through a rotation). We can do this using FT_Set_Transform. Here is how to do it: rotation으로 text를 변환해보자. FT_Set_Transform을 이용하면 된다. 아래처럼 해보자.

FT_GlyphSlot slot; 
FT_Matrix matrix; /* transformation matrix */ 
FT_UInt glyph_index; 
FT_Vector pen; /* untransformed origin */ 
int n; 

... initialize library ... 
... create face object ... 
... set character size ... 

slot = face->glyph; /* a small shortcut */ 
/* set up matrix */ 
matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); 
matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L ); 
matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L ); 
/* the pen position in 26.6 cartesian space coordinates */ 
matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); /* start at (300,200) */ 
pen.x = 300 * 64; pen.y = ( my_target_height - 200 ) * 64; 

for ( n = 0; n < num_chars; n++ ) { /* set transformation */ 
    /* load glyph image into the slot (erase previous one) */
    FT_Set_Transform( face, &matrix, &pen ); 
    error = FT_Load_Char( face, text[n], FT_LOAD_RENDER ); 
    if ( error ) continue; /* ignore errors */ 
    /* now, draw to our target surface (convert position) */ 
    my_draw_bitmap( &slot->bitmap, slot->bitmap_left, 
             my_target_height - slot->bitmap_top ); /* increment pen position */ 
    pen.x += slot->advance.x; pen.y += slot->advance.y; 
}

Some remarks:

  • We now use a vector of type FT_Vector to store the pen position, with coordinates expressed as 1/64th of pixels, hence a multiplication. The position is expressed in cartesian space.

  • Glyph images are always loaded, transformed, and described in the cartesian coordinate system in FreeType (which means that increasing Y corresponds to upper scanlines), unlike the system typically used for bitmaps (where the topmost scanline has coordinate 0). We must thus convert between the two systems when we define the pen position, and when we compute the topleft position of the bitmap.

  • We set the transformation on each glyph to indicate the rotation matrix as well as a delta that will move the transformed image to the current pen position (in cartesian space, not bitmap space).

    As a consequence, the values of bitmap_left and bitmap_top correspond to the bitmap origin in target space pixels. We thus don't add pen.x or pen.yto their values when calling my_draw_bitmap.

  • The advance width is always returned transformed, which is why it can be directly added to the current pen position. Note that it is not rounded this time.

A complete source code example can be found here.

It is important to note that, while this example is a bit more complex than the previous one, it is strictly equivalent for the case where the transform is the identity. Hence it can be used as a replacement (but a more powerful one).

It has however a few shortcomings that we will explain, and solve, in the next part of this tutorial.


Conclusion

In this first section, you have learned the basics of FreeType 2, as well as sufficient knowledge how to render rotated text.

The next section will dive into more details of the API in order to let you access glyph metrics and images directly, as well as how to deal with scaling, hinting, kerning, etc.

The third section will discuss issues like modules, caching and a few other advanced topics like how to use multiple size objects with a single face. [This part hasn't been written yet.]

Posted by 삼스
임베디드/Algorithm2009. 3. 3. 13:45
http://chem.skku.ac.kr/~kle/main/%BB%F5%B3%AA%B7%E7



새로운 Windows용 한글 입력기 새나루


개발자로 퍼키님 WkPark님이 참여하고 있습니다.

기존 입력기와 차별화된 점은, 자판 개발을 염두해두고 개발된 력기라는 것이며, KLDPWiki:오픈소스프로젝트이다.

준비중인 사이트 http://saenaru.i18n.org/

기존에 있던 한글 IME와 차별되는 점은

  1. krisna님의 유닉스/리눅스용 한글 입력기 nabi의 소스와 KLDP:libhangul 프로젝트와 연계성 있게 개발되고 있습니다. 현 새나루의 Automata엔진은 nabi의 소스를 krisna님의 허락을 얻어 차용하고 개선된 것입니다.
  2. 오픈소스이며 자유 소프트웨어입니다. 소스가 완전히 개방되어 있어 누구나 소스를 보실 수 있으며, 오픈소스 라이센스하(BSD라이센스에 준함)에 자유롭게 소스를 쓰실 수 있습니다.

특징 

  1. 두벌식세벌식벌식390, 벌식순아래를 기본지원.
  2. 보락 자판 자체 지원: Key Hook를 이용하여 드보락 자판을 자체 지원합니다.
  3. 보락용 키보드 드라이버도 제공하므로 콘솔에서도 드보락을 지원합니다. (개발판)
  4. shift-space 자체 지원: 리눅스 및 아래아 한글 사용자들이 자주 쓰는 shift-space를 지원하며, 101 Type 3키보드 드라이버와 같이 사용하는 경우에도 충돌하지 않습니다.
  5. 편리한 자판 설정: 세벌식 사용자를 위해 자판을 쉽게 바꿀 수 있도록 했습니다.
  6. 사용자 자판 지원: 사용자가 원하는 자판을 만들 수 있습니다.
  7. 한자<->한글 변환 지원. 

한글 IME 2002에 비해 좋은 점 

  1. 커서 위치가 옳게 표시된다: 한글 IME 2002는 커서 위치가 올바르지 않습니다.
  2. gvim에서 한글 입력이 자연스럽다: 한글 상태에서도 i,o,a등의 명령이 곧바로 먹힙니다.
  3. IME를 지원하지 않은 어플에서도 한글 IME 2002보다 한결 자연스러운 한글 입력
  4. 드보락을 한글과 자연스럽게 쓸 수 있습니다. (자체 key hook 혹은 자체 키보드 드라이버 사용)
  5. 한자<->한글 변환 지원: 윈도우에 기본으로 지원되는 한글 IME 2002/2003보다 좀 더 편리한 한자<->한글 변환을 지원합니다. 


실험적 기능
  1. 동시치기 지원: 실험적 기능이며, 동시치기가 지원되는 키보드를 이용하면 동시치기를 무리없이 쓸 수 있도록 했습니다.
  2. 일본어 입력기와 마찬가지로, 한글 조합이 "단어"단위 입력도 지원. 기존 입력기는 한글 한 음절 단위로 commit했으나, 단어 단위 입력도 지원하기 때문에, 한자 사전도 쓸 수도 있습니다.
  3. Mode_Switch 기능: 한글 입력 상태에서 오른쪽 Alt키를 누른채로 자판을 누르면 영문이 눌러집니다. (리눅스/유닉스의 Mode_Switch기능 구현)

Download 

이제 설치 프로그램으로 설치하실 수 있습니다.

새나루/개발버전: 최신 개발판 

새나루/Build 

빌드하기 위해서는 WindowsDDK와 WindowSDK가 필요하다. DDK의 빌드 환경 CMD를 실행한후 TopSourceDir에서 build 라고 치면 된다.

ScreenShots 

Please see also 새나루/ScreenShots

Language bar 

langbar1.png
(IME 2002 )
langbar2.png
(IME 2002 TSF)
langbar3.png
(새나루)

빠른 메뉴 

qmenu.png

환경 설정 

langenv.png

개발 일지 

한자/기호 지원 2003-11-25 추가

saenaru_han.png
saenaru_sym.png

한자 뜻 지원 04/10/10:

nabi에서 사용하는 파일을 읽을 수 있습니다.

nhanja.png

cmd_han.png

saenaru2.png

2003-11-22: 삽질 끝에 XP 언어 툴바에 붙이고, 자판설정에 한해서 기본적인 동작이 되게끔 만들습니다. 위의 그림에서, 툴바의 키보드 아이콘을 누르면 자판을 쉽게 변경할 수 있고, 설정창에서 또한 자판을 바꿀수도 있습니다. 현재, imhangul/nabi의 루틴을 그대로 가져왔습니다. 오토마타 부분은 imhangul/nabi를 참조해서 만들었으나 새로 작성했으며 두벌식/세벌식 오토마타만 지원하며 옛한글을 지원하기 위해서는 거의 다시 만들어야 합니다. --WkPark

lua 대신에 SUN에서 만든 오토마타 전용 언어를 사용하도록 변경

2003-11-14: #gnome에서 말씀하길, lua 스크립트 엔진을 붙이고 계시다고 합니다. lua는 매우 작은 스크립트 언어로서,새나루의 오토마타 엔진이 될 것이라고 합니다. 오토마타 엔진을 lua로 써서 만들면, 입력기의 특성을 거의 자유 자재로 만들 수 있게 될 것입니다.

루리님의 소개글 

윈도우즈 98에서 작동 안됨 

saenaru98.png
윈98에서 새나루를 설치할 때 에러를 내고 설치가 안됩니다. --김수구

saenaru.inf를 살짝 고치니 이 에러는 나지 않더군요. 98에서 쓰려면 MSDN에서 unicows.dll도 받아서 설치해야 할것으로 생각됩니다. --WkPark

윈도우즈 2000에서는 오피스 없이도 돌아갑니다. (한글 윈도우즈 2000 프로페셔널, SP4, 그밖에 대다수 올림) -- 이 정민

windows 2000에서는 IME 상태표시를 해도 화면에 나타나지 않는군요.--황수진

IME상태표시는 현재 제대로 고치지 않아서, 소스상으로 꺼둔 상태입니다. --WkPark
fakeime는 윈도우즈 98이상에서 모두 작동되는 IME였습니다. 그러므로, XP와 관련된 툴바에 나오는 메뉴 등등을 제외하고는 98/2000에서 작동하게끔 개발될 것입니다. 제 개발 환경이 XP여서 XP상에서 컴파일하고, 테스트를 XP에서만 했기 때문에 98및 2000에서의 작동여부는 알 수 없고, 그곳에서 컴파일 할 수 있는 환경이 되면 문제점을 알게 되지 않을까 합니다. --WkPark

Windows2000에서 새나루가 됩니다. 제 컴에는 Office 2000이 깔려있지만, Office2003을 깔아야만 되는지는 모르겠습니다. 새나루를 설치하면 제어판-국가별옵션-입력로케일에서 새나루가 나타나는데요.--황수진

프로그램이 사용한 API를 보니 새나루는 유니코드 기반이네요. 9x에서 동작하지 않는 게 당연합니다. 개발자 누리집에 "Windows 98에서는 안된다는 보고가 있습니다"라고 적어 놓는 정도가 아니라, MSDN에 있는 유니코드 호환성 레이어로 프로그램을 다시 빌드하든가, 윈도우 2000/XP 전용이라고 선언을 해야 합니다. (김 용묵*님의 글) --루리

fakeime 소스는 원래 95도 지원되고 유니코드(98 이상)도 지원되었습니다. 새나루는 2바이트 문자 지원을 아예 빼고 유니코드만 지원하기때문에, 소스코드상으로는 98부터 지원됩니다. 설마 요즘까지 95쓰시는 분은 없겠고요 :)새나루소스가 OpenSource이기 때문에, 소스를 다운받아서 98쓰시는 분이라면 98DDK를 받아서 컴파일해 보시기 바랍니다. --WkPark

XPDDK에는 컴파일러가 내장되어있으나, 98DDK는 VC++을 설치해야 하는군요. ㅡㅡ;; --WkPark

windows 2000 의 경우 office xp 의 입력기를 설치하면 트레이에 상태표시가 나옵니다. (설치하지 않으면 태극기만 나오네요.)

기호 문제 

기호가 많이 부족하군요(일본어 히라가나 따위). ㄲ, ㄸ, ㅃ, ㅆ, ㅉ 자리가 아직 비어 있으니.. 그곳에 채워넣으면 될 듯하네요. 그리고 기호 배당도 다시 체계적으로 정리해야겠읍니다.--루리

히라가나 입력은 버그였네요. 윈도우즈의 기호입력체계는 저의 개인적인 의견으로는 없느니만 못하다고 생각합니다. 현재는 KSX 1001의 한글 자모 영역만 제외하고 거의 전체 기호를 모두 집어넣은 형태이고, 다음과 같이 제 임의대로 다시 할당했습니다.
ㅁ: 그림문자
ㄱ: 괄호문자
ㄲ: 그리스 문자
ㅅ: 수학문자
ㅍ: 표문자
ㅊ: 첨자
ㅈ: 전각
ㄴ: 한글 낱자
ㅎ: 히라가나
ㅋ: 카다가나
ㄹ: 로마숫자
ㅇ: 원문자
ㅂ: 박스문자
ㄷ: 단위문자
ㅌ: 괄호문자
ㄸ: 미배당
ㅃ: 미배당
ㅉ: 미배당
ㅆ: 미배당

기호입력 부분은 saenaru.dic을 고치면 사용자가 원하는 대로 고칠 수 있습니다. 기호 입력에 대한 입력 의견이 있으시면 saenaru.dic을 고쳐서 올려주시면 고맙겠습니다. --WkPark

2006년 버전부터 기호를 분리하고, 윈도우즈 호환용 기호 사전을 symwin.dic이라는 이름으로 따로 배포에 포함시켰습니다.

질문과 답변 

Q: 새로 업데이트되는 새나루는 그냥 설치만 하면 되는겁니까? --황수진 A: 그냥 설치하시면 됩니다. 단, 현재 선택된 입력기가 새나루가 아니어야 합니다. 현재 선택된 기본 입력기 새나루라면 다른 입력기로 고치신 후에 재부팅하고 설치해야하지만, 기본 입력기가 새나루가 아닐 경우는 재부팅하지 않아도 됩니다.

RootRightMenu1,RootRightMenu2,RootRightMenu3는 무얼 말합니까? 저는 Windows 2000을 씁니다.--황수진
fakeime 원 소스에 있는 부분입니다. 아마도 그렇게 만들 수 있다는 예를 들어놓은 것일텐데, XP에서는 그 메뉴가 아예 나오지 않습니다. 그것이 어떤 모양인지도 잘 모릅니다 ^^;; --WkPark

프로그램마다 설정이 따로 존재하는 것처럼 보이는군요. 예로 메모장을 두개 띄워 메모장 a에서 세벌식으로 고쳐도 메모장 b에서는 두벌식으로 설정되어 있습니다. xp 를 쓰고 있습니다. --네엉
언어 툴박스(자판 아이콘을 누를 때 나오는)를 통해서 설정하면 열린 프로그램마다 다르게 쓰게끔 되며, "환경 설정"을 통해서 설정하면 전체 설정이 바뀝니다. 즉, "환경설정"에 들어가셔서 고치면 원하는 설정을 하실 수 있게 됩니다. --WkPark 

Windows 2000에서는 "환경설정"이 없네요. ---황수진

11월29일자 버전인데 윈2000서버에서 잘되네요.. 오피스같은거 안깔린 상태인데..

Dvorak 자판 

다음이나, 프리챌등 로그인할때 아이디까지는 제대로 드보락으로 입력할 수 있는데, 비밀번호 입력시엔 쿼티로 입력을 해야되네요. 그 문제도 해결가능한지요? 윈도상에서 제공해주는 드보락 입력기로는 되거든요. 그리고 어쩌다보면 드보락도, 쿼르티로 아닌 배열이 나올때가 있습니다. 12일버전에서는 한글모드로 들어가서 태극기표시 나온상태에서 영문으로 전환하면 그 문제가 해결되었었는데.. 15일자버전은 태극기 모양이 안나오고 그냥 '가', 'A'표시만 나오네요. 윈도상에서 제공해주는 드보락입력기랑 혼용(시프트 스페이스때문에 그랬었거든요^^)해서 그런가.. 지금은 제거했습니다. 그래도 엉뚱한 배열 나오면 다시 올릴께요. --박영석

새나루에서는 드보락 입력을 표준적인 방법이 아닌 hook방법을 쓰기때문에, 프로그램에 따라서 제대로 작동하기도 하고 그렇지 않기도 합니다. 동시 지원을 위해서는 어쩔 수 없는 선택이지만 모든 프로그램에서 일관되게 작동하는 것을 보장할 수 없습니다. ㅡㅡ;; --WkPark

메모장이나...익스플로어, 워드패드등에서 단축키는 쿼티로 먹히네요. 아.. 이건 일부러 그렇게 하셨나보다.. 기존배열이 더 편할수도 있으니... --박영석

새나루가 드보락을 지원하는 구현방식(hook)때문에 그런 식으로 작동하는 것입니다. 일부러 그렇게 의도한 것은 아닌데 파생 효과네요. 새나루는 "드보락"이 활성화 되어 있을 경우 WM_CHAR를 가로채서 드보락 자판 배열로 바꿔줍니다. 단축키의 경우는 WM_CHAR가 아닌 WM_SYSKEYDOWN에 의해 작동합니다. --WkPark

윈도2000 커맨드창(도스창)에서 드보락 안 먹히고 쿼티로 되네요... --박영석

도스창은 뭔가 다른 방법을 쓰나보군요 ^^;; 내년에나 볼 수 있을 듯 하네요 --WkPark

2006년 개발판 버전부터는 콘솔 커맨드창에서도 드보락을 지원합니다. --WkPark

동시치기 문제 

ㅕ+ㅣ=ㅖ,ㅑ+ㅣ=ㅒ 때문에 세벌식 모아치기에 문제가 생긴다는 지적이 있군요. 두벌식에서는 쉬프트 누름 횟수를 줄이기 위해서 그런 조합이 필요한지도 모르겠으나 공세벌식은 ㅖ,ㅒ를 그냥 치는 것이 조합하는 것보다 편합니다(배열을 보시면 아실테죠..이동거리 증가에 한손가락 련타에). 그리고 ㅡ+ㅣ=ㅢ 조합도 세벌식 모아치기에서는 도움이 안됩니다. 또 세벌식 모아치기를 위해서 날개셋*에서 지원하는 것은 겹모음용 ㅗ,ㅜ 와 홑모음용 ㅗ,ㅜ 를 구분해서 인식하는 것입니다. 그래서 홑모음용 ㅗ,ㅜ 를 쳤을 때는 모음 조합을 하지 않는 것입니다. 즉 겹모음용 ㅗ,ㅜ 만 '중성2'를 받을 수 있는 것이지요. 결론은 공세벌식 부류에서는 ㅕ+ㅣ=ㅖ,ㅑ+ㅣ=ㅒ 조합을 없애고, 환경설정에서 세벌식 모아치기를 선택하면 ㅡ+ㅣ=ㅢ 조합을 없애주며 동시에 겹모음용 ㅗ,ㅜ 와 홑모음용 ㅗ,ㅜ 를 구분해서 인식하게 해 주어야 합니다. --루리

ㅕ+ㅣ 조합과 동시치기와는 전혀 상관없이 작동합니다. 각 자판의 조합지도를 지정할 수 있게끔 구현되면 이 문제는 모두 해결됩니다. --WkPark 

ㅕ+ㅣ,ㅑ+ㅣ 조합은 모아·동시치기가 안되기 때문이 아니라 도깨비불 현상을 없애기 위해서 지워야 합니다. 여->예->여이->여인. 그리고 나머지 지적한 조합은 모아치기를 온전히 실현하기 위해서 필요한 것이고요. --루리

'각 자판의 조합지도를 지정할 수 있게끔 구현되면 이 문제는 모두 해결됩니다.'라고 말씀해주셨는데, 그렇다면 동시치기에서 '계계'라고 칠 경우 '겨기ㅖ'가 되는 경우와 '모장'을 칠 경우 '뫄장'이 되는 경우,'묵묵묵'칠때 '묵묶무'등도 해결 가능하겠죠? --박영석

앗. 동시치기가 제대로 구현되지 않았던 것이였습니다. 12일자로 수정해서 올려놓습니다. --WkPark

감사합니다. 근데 모장을 동시치기할때 '뫄장'으로 되는 문제는 아직 해결이 안된듯하네요.아마도 초성과 종성이 쳐질때 자동으로 'ㅏ'가 들어가는 이유로 뒤에 가야될 'ㅏ'가 앞으로 가버리는 거 같네요. '모'치고 '장'칠때 'ㅈ'과'ㅇ'만 쳐도 'ㅏ'가 자동 생성되는데 그 이유로 'ㅏ'가 모에 붙네요. 물론 그냥 '장'칠때 'ㅈ'과 'ㅇ'만 치는게 더 편하긴하네요.. ^^ 습관들이면 되겠지만...이것도 설정에 옵션으로 해놓으면 좋겠네요. 암튼 감사합니다.--박영석

이건 좀 까다롭습니다. "모장" "조장" "고단" 등등의 (초/중) + (중+종+초)에서 발생하는 현상입니다. 이것은 "초 + 중 + 중 + 종 + 초"이 되는데, 현재의 오토마타로는 (초 + 중1 + 중2) + (종 +초)로 해석이 되어서 생기는 문제입니다. 이걸 제대로 되게 하려면, 앞에 입력된 자모 "두개"의 상태를 기억해야 합니다. (현재는 최종으로 입력된 키의 VKey값을 한개만 저장합니다) --WkPark

안마태 자판을 위한 동시치기를 제대로 구현하려면, 이 이외에 몇가지를 더 추가해야 합니다. 현재의 동시치기 오토마타는 초+중 중+종 종+초 결합에 대해서만 고려하고 있지만 안마태 자판의 쌍초성,겹중성,쌍종성 등등을 구현하려면 동시치기용 매핑이 따로 고려되어야 합니다.

최소 구현비용이 무엇일지 생각해보고 있습니다. --WkPark

초성+종성을 눌렀을 때 자동으로 중성 "ㅏ"가 들어가는 것은 별로 좋아보이지 않기 때문에 다른 방법을 생각하고 있습니다. 예를 들어, 아예 글자 조합을 하지 않는다거나 (안마태 자판 키보드 Hook 드라아버처럼)하는.. --WkPark

모아치기 동시치기 문제 

겹모음용 ㅗ,ㅜ 와 홑모음용 ㅗ,ㅜ 를 구분해서 홑모음용 ㅗ,ㅜ 다음에는 '중2'를 받지 않게 하면 "동시치기의 겹중성 문제"는 해결될 문제입니다. --루리

현재로서 홑모음 겹모음을 따로 인식하는 문제는 고려하고 있지 않습니다. 겹중성 문제로 이것을 고려하는 것 보다는 차라리 동시치기를 정확하게 구현하는 것이 구현비용이 더 적게 듭니다. --WkPark

반대로 겹모음일경우 받침이 먼저오더라도 중성이 오면 결합이 되야될거 같네요. '된'을 칠 경우 '도'를 먼저 친후 '인'을 치는데.. '도인'이 될때가 많네요.아마 이것도 홑모음 겹모음 구분이 안되있어서 그런거 같네요. --박영석

불편하지요 ? 마지막에 조금 고친 부분이 있습니다. 다시 그부분을 비활성화 시키고 12월12일자로 돌려야겠네요.

아.. '모장'이 '뫄장'되는 거 고치셨었네요. 몰랐습니다.. --박영석

새나루 잘 쓰고 있습니다. 종성+초성을 하면 ㅏ 가 삽입되는 것 외에는 아주 좋군요. 그 정도야 참을 수 있지요. 다른 문제가 있는지는 아직 모르겠습니다. 이제는 새나루로 쓰는 일이 많답니다. 고맙습니다. --황수진

종성+초성을 하면 ㅏ 가 삽입되는 문제는 김용묵님에게서 조언을 구하면 안되나요?--황수진

"ㅏ"가 넣어지는 것은 현재 편법입니다. 안마태키보드 드라이버처럼 아예 화면에 표시 안되게 하거나 하는 방법을 쓰면 되겠죠. 종성+초성이 표시되게 하는 방법은 없습니다. --WkPark

안마태 자판 문제 

안마태 자판은 ㄱ+ㅇ = ㄲ이 되는데, 그 역변환 (ㄲ->ㄱ+ㅇ)을 하려면 버퍼가 따로 필요하군요. 안마태 자판은 이러한 문제점 때문에, 새나루+안마태드라이버를 같이 쓰는 방식으로 해결을 한다고 합니다. --WkPark

한자입력 문제 

입력방식에서 '한글', '영문' 말고 '한자'는 기능이 무엇입니까.(일본어 입력기에서 딸려 온 것입니까?)--루리*

한자를 많이 입력할 경우 특별히 한자 입력모드를 만들기 위해서 실험적으로 그렇게 해 두었습니다. 일본어 입력기의 손쉬운 한자입력 부분에서 쓰는 방법을 사용할 것입니다. --WkPark

저는 한자를 거의 쓰지 않으므로 상관없읍니다만 한자 배열 기준은 무엇인지요? 전에 일본웹 검색을 하려고 自를 치는데 세번째 목록에 있더군요. --루리*

한자 배열은 KS X 1001배열 순서 그대로입니다. 한글 IME 2002의 한자 배열은 유니코드 배열순서도 아니고 KS X 1001배열 순서도 아니더군요. 아마도 한자 빈도수를 고려하거나 한 ?? --WkPark

검색창 같은 데에서는 선택 목록도 뜨지 않아 한자키나 화살표를 계속 눌러야만 합니다. 선택목록이 뜨지 않는 이유도 알았으면 합니다. --루리*

버그입니다. 선택목록(candidata창)이 뜨지 않는 문제는.. fakeime에서 원래 있던 문제점입니다. --WkPark 

저는 한자를 많이 쓴답니다. 그래서 저로서는 아래아한글을 안 쓸 수가 없지요. 다른 MS word나 훈민워드(통일워드)는 한자가 약한 것 같아서. 그래서 저의 바램은 한자를 제대로 쓸 수 있도록 많이 보강을 해 주셨으면 좋겠습니다. (아래아한글 가격이 만원 정도만 하면 얼마나 좋을고!) --황수진

예. 그래서, 한자를 많이 입력하는 경우를 고려해서 일본어 입력기식의 한자 입력방법 지원을 고려하고 있습니다. 이른바 한자 입력 모드가 바로 그것입니다. --WkPark

2006년 한자 입력을 제대로 지원하기 위한 Reconversion 기능을 구현했습니다. 적어도 IME 2003보다는 똑똑하게 작동합니다. --WkPark

Shift-space 한글 전환 

모질라 1.5에서 텍스트 영역에 입력하는 도중에, shift-space 로 한영 전환을 하면 한영 전환은 되지만, 공백이 하나 입력됩니다. --wafe
저는 XP일 경우인데 잘 됩니다 --WkPark

아 그리고 Shift-space로 전환하는거 옵션에서 끌 수 있게도 가능하게해 주시겠죠? 영어를 열심히 치다보면 대문자 칠 때 자꾸 한글로 변환되기 쉽더군요. 제 손이 이상한건지 자꾸 대문자 치다보면 한글로 전환되더라고요. --박영석

이 옵션은 200412xx 버전 이후부터 적용되었습니다

고고타자 

개발자님 오랫만입니다. 작년부터 매일매일 오는데 업데이트는 없더군요. ㅅ.ㅅ; 제가 실력이 뒤따라준다면 소스를 분석해서 어떻게 해보고싶기도 한데... ㅋㅋ 암튼 고고타자에서 예전부터 제가 지나쳤었던게 있었는데.. 채팅중 말고 겜중이나 연습시에 문장을 동시입력으로 할 경우 종종 '있, 을, 은, 연, 억, 였, 악, 안'등등으로 끝나는 어절다음에 'ㅇ'이 들어가는 현상때문에 곤란한때(맥이 끊겨서 더이상 진행이 안되고 버벅대죠)가 많습니다. 어쩔경우에는 모음('ㅏ')도 들어가는거 같기도 한데... 암튼 세이클럽에서는 기가막히게 잘 되거든요 ㅎㅎㅎ 아마도 프로그램상 '종성+중성' 혹은 '중성+종성'일 경우 자동으로 'ㅇ'이 삽입되고 '초성+종성' 혹은 '종성+초성'일때는 자동으로 'ㅏ'가 삽입되기때문일 거라 생각되네요. 고고타자 같은 경우 겜진행시 문장을 칠때 일단 글자 하나를 맞게 치면 더 이상 수정이 불가한데 중성과 종성이 초성보다 먼저 눌러질경우 'ㅇ'이 자동 삽입되어 글자가 더 이상 수정이 불가능한 상태에서 추가(사실 추가는 아니지만 고고타자에서는 추가로 인식하겠죠)로 'ㅇ'이 눌러져서 그 다음 음절에 찍히죠. 'ㅏ'문제도 마찬가지인거 같네요. 그래서 제가 어떻게 해결할까 생각해봤더니 답이 나오더군요. 그렇잖아도 동시입력시 눌러야될 키 갯수가 조금 부담스러운데....프로그램상에서 지원해주는데로 간편하게 '초+중+종'로 된 글자일 경우 'ㅇ'나 'ㅏ'를 생략하는거더군요. 진작에 그렇게 깊은 뜻을 못헤아린 제가 부끄럽네요 ㅎㅎ

근데 그렇게 해봤더니 아마도 고고타자 게임 진행시엔 문제가 전혀 없겠지만... 반대로 고고타자상에서 채팅시나 세이클럽, 혹은 딴데서 타자칠경우 생각지도 않은 또다른 문제에 봉착되더군요.

'감사합니다'를 위에 간편한 방식으로 입력해보면, '감ㅅ힙나ㄷ'가 되더군요. -ㅅ- 'ㄱ+ㅁ=감' 로 보이지만 상태는 ㄱㅁ상태가 유지 되는거 같네요.그래서 그다음에 사를 칠경우.. 'ㅏ'를 훔쳐가더군요. 'ㅎ+ㅂ=합'처럼 보이지만 상태는 'ㅎㅂ'라서 '니'란 글자를 치면 'ㅣ'를 빼앗아서 '힙'이 되네요. 그러니 연쇄반응으로 이어지더군요. '온천'도 마찬가지 효과로 '촌언'이 될 수도 있습니다. 화학반응에서 분자끼리 서로 빼앗고 뺏기는거 같네요 ㅅ.ㅅ

그러고 보면 12월15일자 첫번째 버전(12월 12일자로 되돌리기 전 버전인 '모장'이 '뫄장' 되는거 수정해 주셨던게)이 최종(12월30일)보다 훨씬 더 편한거 같네요 ㅅ.ㅅ 솔직히 그래서 오늘까지도 12월 15일자의 첫번째 버전을 고수해왔습니다. '수정'이 '숴장'이 될 염려도 없고, '될' 처럼 이중모음에 받침 들어간거야 뭐 '도'먼저 치고 그담 순서대로 풀어치면 문제 될것이 없으니...

암튼 아쉬운게 있다면.. 자동으로 'ㅇ', 'ㅏ' 삽입되는걸 100% 오타없이 쓸 수 없는다는거죠. 정말 간편하고 좋은거 같은데 다음 글자의 음소를 빼앗을 수 있다는 약점때문에..... 좀 불편하네요.

개인적인생각으로 단기적으로는 15일자 버전(첫번째)에서 'ㅇ', 'ㅏ'문제가 해결되었으면 좋겠네요 ㅅ.ㅅ

물론 개발자님은 최종적으로는 이중모음까지도 완벽 동시입력 지원을 지향하시겠지만요..(저도 그럴날이 빨리 오길 바랍니다 ㅅ.ㅅ) --박영석

한메타자교사 

한메타자교사는 한글 입력상태에서 기호가 입력되지 않는 문제점이 있습니다. 한메타자교사 자체적으로 WM_IME_COMPOSITION을 한글만 허용하는 것 같습니다. --WkPark

Shift-Home 

한글 상태에서 글을 쓰다가 쓰고 있는 줄을 블럭으로 묶기 위해 쉬프트+Home 키를 누르면 쉬프트 키가 적용이 안되서 블럭이 안잡힌 상태로 커서만 이동하는데.. 방법이 없을까요?(다시 해보니 저도 되네요-_-; 아까는 계속 안되었었는데.. 죄송합니다 ^^;) --착이

XP에서 노트패드, 워드패드, 모질라, 익스플로러 모두에서 문제가 없습니다. --WkPark

음 위의 문제 다시 발생 했는데-_-; 어떤 환경일 때 나타나는 현상일까요..; 윈2003에 오피스는 아직 설치하지 않은 상태입니다.. 원격데스크톱으로 연결해서 그런가? 조금 더 지켜보고 신고하겠습니다 ^^;--착이

저도 윈도2000서버 사용하는데 노트패드, 워드패드, 익스플로어(지금 글 쓰고 있는 여기서조차)등에서 안먹히네요. 기호로 끝나거나 한번 지웠다가 다시 쓰거나 처음 실패후 다시하는 경우만 되네요. 처음 시도시는 안먹히고 커서만 이동하네요. 아마 윗분도 되었다 안되었다 해서 헷갈리셨을거 같네요. 되긴 되는데.. 순수 한글로만 백스페이스 없이 치다 블럭 씌울 경우에는 안 먹히네요. --박영석

처음에 쓰다가 보니 정상적으로 작동을 안해서.. 이곳에 문의 했는데 답변을 보고 나서 다시 해보니 정말 다시 되더라구요(당황스러웠음-_-) 그래서 한동안 정말 제대로 됬었는데 지금도 제대로 동작을 안하네요..; --착이

포멧하고 XP를 깔았는데.. 처음 새나루 설치 하니 잘 동작했는데 조금 쓰다가 지금은 또 안되네요-_-; 재부팅 하면 안되는건가.. --착이

Esc로 한글 -> 영문 전환 (for Vim mania :> ) 

2004년 11월30일 버전에 적용됨

Mode_switch키 기능 

아주 좋네요..그런데 오른쪽 alt는 어떤 손가락으로 눌러야 하나요? 엄지! 혹은 새끼?

간단히 Windows XP의 메모장과 모질라 1.5에서 사용해 보았습니다. 메모장에서는 잘 동작하는데, 모질라에서 웹페이지의 텍스트 영역에 글을 쓰는 도중에는 Alt를 누른 상태에서 자판을 누르면 메뉴가 떠버리더군요. --wafe
저는 둘 다 잘 됩니다. --WkPark
아... 그렇군요. 뭔가 정보를 더 드렸으면 좋겠는데, 모질라 1.5에서 동작이 잘 안된다는 것 외에는 별로 드릴 말씀이 없고, 좀더 관찰해보겠습니다. --wafe 

Capslock 

흠..장점도 있고 단점도 있읍니다. 공세벌식에서 숫자 칠 때 편하기는 하겠으나, 두벌식에서는 소용 없고, 한글 입력상태에서 Capslock을 신경써야 한다는 것을 반기지 않는 사람이 있기도 하지요. --루리

caps lock을 누르면 숫자키와 부호만 나오도록 하면 좋을 것 같습니다. 아니면 caps lock상태의 키배열을 사용자가 정의할 수 있게하여, 자판에 없으나 각자 자주쓰는 특수기호를 caps를 눌러 바로 쓸 수 있게한다면 어떨까 하는 생각도 들고, 이런걸 오히려 불편해 할 사람도 있을테니, 환경설정에서 사용자정의Caps배열을 켜고 끌 수 있으면 더할 나위 없겠다는 생각도 듭니다. 그냥 의견입니다...(ㅅ.ㅅ) 지금의 새나루도 너무나 만족하며 잘 쓰고있습니다. 감사합니다. 즐거운 성탄, 그리고 행복한 새해 되세요. --박경남

Caps Lock은 한글 IME2002의 방식만을 따르도록 할것입니다. 특별한 아이디어가 아니라면, 새로운 기능은 새나루가 릴리즈된 이후에 고려하게 될 것 같습니다. 현재는 버그를 잡는 것 / 작동되지 않는 어플에 대한 고려 등등이 우선입니다 --WkPark

벌레 보고 합니다. 1.메뉴에서 키보드보기가 나타났다 사라졌다 합니다. 처음에는 없다가 주소창을 한번 클릭하고 나면 메뉴에 나타납니다. 2.주소창에 입력시에는 키보드 보기를 클릭하면 소프트키보드가 나타나고 다시 클릭하면 소프트키보드가 사라지지만, 메모장에서는 소프트키보드를 한번 띄우면 메뉴에서 다시 클릭해도 사라지지 않습니다.그리고 메모장을 종료하면 함께 사라집니다. 3.메모장 입력시 소프트키보드가 떠있을 경우에도 메뉴에는 체크 표시가 안나타납니다. --바람

의견하나! 메뉴에 “문자표”도 있었으면 좋겠습니다. 주소창등에서 특수문자입력기능이 제대로 작동하지 않거나, 배당된 글쇠를 잘 모를때 바로 문자표를 불러내어 입력할 수 있도록하는 것도 좋을 것 같습니다. --바람

소프트키보드 보기는 ime에 원래 있는 기능이지만 문자표 보기 기능은 ime에 없습니다. 새나루에서 외부 프로그램이 실행되는 작은 메뉴같은 것을 원하시는 듯? --WkPark

버그? 아래아한글 2004 버전에서 “윈도우 입력기(새나루)”를 사용할 경우 스페이스바(띄어쓰기)가 작동하지 않습니다. 아래아한글의 자체 입력기의 세벌식 자판이 별로 마음에 들지 않아 새나루의 세벌식 최종을 사용하는데 이 문제 때문에 꽤나 불편합니다. 운영체제는 한글 Windows Server 2003입니다. -- 정원호

또하나. 버그인지는 모르겠지만 프로그램을 전환하면 자꾸 한글자판에서 영문자판으로 바뀝니다. 기본이 영문인가요? 한번 설정한 자판이 계속 유지되었으면 합니다. --정원호

Shift+스페이스로 한영변환시에 정확한 이유는 모르겠지만, 어쩌다가 2벌식으로 변환되는 문제가 있습니다. 이것은 어쩌다가 한/영키를 누르면 해결이 가능하였습니다만 버그인듯 합니다. 환경은 타입3형태의 키보드 타입을 사용합니다. --강정한

글자를 쓰면서 마우스 휠기능을 사용할 경우 다시 한글을 적을땐 “ㅇ ㅖ ㅈ ㅔ : ㅇ ㅏ ㄴ ㄴ ㅕ ㅇ ㅎ ㅏ ㅅ ㅔ ㅇ ㅛ” 이런씩으로 글자가 나타납니다. -- 강정한

자동 "ㅏ" 삽입의 경우 ㄱ + ㅇ 눌러 "강"이 만들어 졌을때 지우게 되면 백스페이스키로 지우게 되면 "ㄱ"이 남아 다시 글자를 조합하려고 하려면 조합되지 않고, 다음글자로 가는 현상이 있습니다. -- 강정한

한글패치한 디아블로2 게임에서 새나루 사용시에 스페이스키를 2번 눌러야 스페이스 기능이 됩니다. -- 강정한

OFFICE 2000 제품의 경우 한자를 선택시에 팝업메뉴처럼 한자가 나오지 않고, 한자키를 반복적으로 눌러서 찾아야 하는 불편함이 있습니다. 한자 선택은 어쩔 수 없다고 하더라도 한자키를 누르고 있으면 선택할 한자가 변환되게 해 주시면 감사하겠습니다. -- 강정한

관련된 문제점을 발견하였고 해결법도 찾았습니다. 보고해주셔서 감사합니다 :) --WkPark

울트라 에디트류의 2바이트 문자 지원이 완벽하지 않는 프로그램에서는 마지막 글자가 짤리는 현상이 생깁니다. IME 2002에서는 정상동작 -- 강정한

다른 사람과 같이 쓸 경우에는 한자 기능을 쓸 때 두 번 누르는 것이 불편합니다. 두 칸 위에 "누르고 있으면 변환되는" 방식과 "한자키 누르면 목록이 나오는 방식을" 변환(토글)할 수 있었으면 좋겠습니다. 그리고 지금 세 칸 위에 "디아블로2 게임에서 스페이스키를 2번 눌러야" 한다고 했는데, 저는 "지금 이 글을 쓰는데 스페이스키를 2번 눌러야" 합니다. 아무래도 새나루에서 한 자 치고 스페이스키 누르면 글자 만드는 모드(왜 "잘"을 칠 때 ㅈ→자→잘 되는 거)에서 스페이스를 누르면 "탈출을 하고 스페이스를 눌러야" 되는데 "탈출만 하는" 그런 버그 같군요. --lsch

새나루에서 트레이 아이콘에 나오는 한자아이콘은 IME2002와는 다른 의미를 가집니다. 이른바 "한자입력"모드가 됩니다. lsch님은 새나루의 한자입력방식을 잘 못 이해하고 계십니다. 보통의 방법으로 한자를 입력하려면 그냥 한자키만 누르세요. --WkPark 

음.. 다시 읽어보니 디아블로에서 스페이스를 두번 눌러야 하는 버그가 한자키 기능과 관련이 있는게 아닌가 하군요. --WkPark

/!\ 내용이 갑자기 없어졌을 경우 놀라지 마세요 :) 다른 분들도 모두 읽었을만큼 충분히 시간이 지난 내용중에 특별히 새나루와 관련 없는 내용은 지워지며, 필요한 내용들은 적절한 위치로 재 조정됩니다.

엔키퍼를 깔았더니 웹상에서 새나루가 이상하게 타이핑되네요. --황수진

Wish List 

로마자 입력, 영문 메시지. 한국어가 모국어가 아닌 사람들도 쓸 수 있는 한글 입력기가 있어야 하지 않을까요? 로마자 입력은 HWP 등에 들어있는 오토마타와 호환이 되게 하면 될테고요. -- 박종대

한글입력기/로마자한글페이지에 관련 토론을 열었습니다 -- WkPark 2006-11-11 17:20:41

Bug Report 

<!> 적당한 위치 혹은 관련된 곳을 찾거나, 혹은 적당한 위치가 없으면 이곳에 버그보고를 해주세요.

Posted by 삼스
임베디드/Algorithm2009. 3. 2. 17:53

POSIX 함수에 대해 글 쓴 지가 너무 오래 전이라 까맣게 잊고 있었다. 오늘은 두서 없이 세마포어라는 놈을 건들여보도록 하자. 일단 세마포어 하면 유명한 예제가 있다. 철학자라는 것들이 가서 포크랑 나이프랑 한 벌 씩 더 가져오면 해결할 수 있는 문제를 굳이 앉아서 남이 썼던 것 더럽게 씻지도 않고 빌려쓰고... 암튼 그런 드러운 문제를 해결하기 위해 세마포어가 탄생했다...라고 하는데 드럽긴 마찬가지고 좀 그렇다. 세마포어 개념은 안드로메다 같은 곳에서 찾아보길 바란다. 그래도 귀찮은 사람은 세마포어를 들어갈 수 있는 사람 수를 한정한 매점(PX?)이라고 생각해도 좋을 것이다. '세마포어 값'은 매장에 들어갈 수 있는 사람 수 여분을 뜻한다.

일단 세마포어도 SysV에서 뛰쳐나온 
IPC개념인데, 일전에 알아봤던 것과 비슷한 API를 제공한다. semget, semop, semctl 이 바로 그것인데, 역시나 유명한 녀석이라 자세한 설명은 생략한다. 대충 semget으로 커널에 세마포어 객체 만들어달라고 떼를 쓴 뒤에 semop을 통해 세마포어 값을 증감하고, semctl을 통해 커널에 세마포어 객체 파괴하여 정리하는 역을 한다. 이 역시 IPC이므로 명시적으로 세마포어 객체를 커널에서 제거하지 않으면 리부팅할 때까지는 커널자원을 차지한다. - 설명 끝 -

이번에도 SysV는 별 관심사는 아니고, 세마포어 
개념을 거의 그대로 가져온 POSIX API가 있다. 아, 그전에 미리 설명해야할 것이 있는데, 세마포어에도 이름이 있는 녀석(named-)이 있고, 없는 녀석(unnamed-)이 있다. 뭐더게 이름 있고 없는 녀석을 만들었는지는 각자가 판단해야할 것 같지만, 보통 이름이 있는 녀석은 세마포어를 만든 녀석과 그것을 공유하고 싶은 녀석끼리 별 관련 없을 때 사용하고, 이름 없는 녀석은 동일 프로세스 내 쓰레드끼리 또는 부모자식 같은 관계가 있을 경우에만 공유해서 사용하고 싶을 때 사용한다. 이름이 있냐 없냐 따라 생성 및 해체 API가 다르지만, 락을 걸고(값 감소), 푸는(값 증가) API는 동일하다.

먼저 이름이 있는 녀석부터 알아보자. 이름이 있는 녀석은 마치 세마포어 객체를 파일처럼 관리한다. 물론 정확히 파일은 아니므로, read/write/close 함수를 쓸 수 없다. 초기화는 sem_open 함수를 이용하며 형태는 아래와 같다.
sem_t* sem_open(const char* name, int oflag, mode_t mode, unsigned int value);

name은 이름 있는 녀석이므로 당연히 이름이 들어가야하고, 공유메모리처럼 '/'으로 시작하는 파일명을 써주는 것을 추천하는 바이다.

oflag는 열 때 어떤 방식으로 여는 가인데, O_CREAT, O_EXCL 말고는 쓸 일이 거의 없을 것 같다.

mode는 접근제어로 'S_'로 시작하는 매크로를 OR연산으로 묶어서 사용할 수 있다. 이것 역시 공유메모리 그것처럼 사용하는 것이다.

value는 세마포어 초기값을 설정할 때 사용한다.

당연한 이야기이겠지만, mode, value는 oflag에 O_CREAT를 설정해야만 의미가 있으며, man페이지에서 sem_open이 다른 모습으로 같이 소개하는 것도 있다. 뭐 이렇다~하는 정도만 알고 넘어 가자.

제대로 초기화를 끝내면 sem_t 포인터 형으로 세마포어 컨텍스트를 퉤!하고 뱉어준다. 물론 실패하면 NULL과 함께 그에 상응하면 errno를 세팅한다.

이렇게 만들어진 세마포어 객체는 sem_wait, sem_timedwait, sem_trywait 등을 통해 락을 걸고, sem_post를 통해 락을 푼다. 가용 락 개수는 sem_getvalue를 통해 얻을 수 있으며, 이것이 가지는 초기값은 sem_open에서 준 value와 동일하다.

잘 사용하고 더 이상 쓸 필요가 없는 세마포어 객체는 sem_close 함수를 통해 닫을 수 있지만, 없어지진 않는다. 파일과 마찬가지로 생성한 뒤에 닫는다고 파일이 없어지는 것이 아니듯, sem_unlink를 통해 세마포어 객체를 OS에 반환 신청을 해야한다. 물론 파일과 마찬가지로 반환신청했다고 바로 없어지는 것은 아니고, 해당 세마포어를 참조하는 프로세스가 모두 없어져야 비로소 세마포어 객체가 사라진다.

다음은 이름이 없는 세마포어. 이것 역시 이름 있는 녀석과 살짝 다르게 sem_t 객체를 미리 만들어놓고 시작해야한다. sem_t 라는 구조체 내부는 POSIX에서 정의하지 않았으며, 알 필요도 없다. 다만 사용범위에 따라 동일 프로세스 안에 쓰레드끼리 공유하는 객체로 사용하려면, 쓰레드끼리 같이 접근할 수 있는 메모리 영역(예를 들면 전역변수!)에 만들어야하며, 부모자식 프로세스끼리 공유하기 위해서는 semget+semat이나 shm_open+mmap으로 얻은 공유메모리에 만들지 않으면 원하는 결과를 얻을 수 없다. 이게 좀 귀찮다.

아무튼, 이름 없는 세마포어는 sem_open/sem_close 대신 sem_init/sem_destroy를 사용한다. sem_init은 다음과 같다.
int sem_init(sem_t* sem, int pshared, int value);

sem은사용범위에 따라 전역변수 또는 공유메모리에 선언한 변수 포인터이다.

pshared는 프로세스끼리 공유하는지 여부를 알려주는 플래그이며, sem을 전역변수 선언하여 쓰레드끼리만 쓰는 것이라면 '0'을, 그렇지 않고 부모자식 프로세스끼리 공유까지 열어주려면 '0' 이외 값으로 설정한다.

value는 sem_open에서 설명한 value와 동일하다. 세마포어 초기값이다.

논외지만, pshared라는 값을 지정해줘야 하는 까닭은 API 내부 입장에서 sem이 전역변수영역인지 공유메모리영역인지 모르며 또한 프로세스끼리 공유한다고 치면 sem_t 내부에 레퍼런스 카운터 같은 것이 있어 그것을 증감시켜야하기 때문이 아닐까 조심스레 
추측해본다. 아님 말고~ (딴따라당스러워~)

sem_destroy를 할 때는 반드시 락을 걸려고 시도하는 쓰레드가 없어야 한다. 또한 sem_destroy를 하지 않으면, 구현방식에 따라 메모리가 좔좔 샐 수도 있다고 하니 주의하도록 하자.

예제도 있으면 참 좋겠지만, 귀찮은 관계로 그냥그냥 넘어가자.


덧글: 살째기 재밌는 사실 하나 덧붙이자면, Linux2.6에서 sem_open하면 shm_open처럼 /dev/shm에 파일이 생긴다.
Posted by 삼스
임베디드/개발툴2009. 3. 2. 15:35

Are legacy objects and libraries compatible with my project?

Applies to: ARM Developer Suite (ADS)RealView Developer Kit (RVDK) for OKIRealView Developer Kit for XScale (RVXDK)RealView Developer Suite (RVDS) 2.0RealView Developer Suite (RVDS) 2.1RealView Developer Suite (RVDS) 2.2RealView Development Suite (RVDS) 3.0RealView Development Suite (RVDS) 3.1

ARM strongly recommends that you rebuild your entire project, including your own libraries and any libraries or code supplied by a third party using our most recent compilation tools. This allows you to take full advantage of the improved optimization, bug fixes and new features of the latest tools. There are some restrictions and potential incompatibilities if you build your project with legacy objects and libraries, for example, you may see the following error message:

Error: L6242E: Cannot link object foo.o as its attributes are incompatible with the image attributes.

This error can be avoided as described below.


http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0255hk/BABDGDGD.html


3.10. RVCT 버전 4.0과 레거시 객체 및 라이브러리와의 호환성

빌드 시 --apcs /adsabi를 사용하지 않았으며 RVCT 버전 4.0 링커와 C/C++ 라이브러리를 사용하는 경우 RVCT 버전 2.x 및 버전 3.x 객체/라이브러리 코드의 역방향 호환성이 지원됩니다. 정방향 호환성은 보장되지 않습니다.

이러한 제한 사항이 있으므로 사용자나 타사에서 제공하는 라이브러리를 비롯한 프로젝트 전체를 RVCT 버전 4.0으로 다시 빌드하는 것이 좋습니다. 이렇게 하면 비호환성을 방지하고 RVCT 버전 4.0에서 제공하는 개선된 최적화 기능, 향상 기능 및 새로운 기능을 모두 사용할 수 있습니다


http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/1347.html


Posted by 삼스
http://www.motobit.com/util/charset-codepage-conversion.asp

Online sample of a CharSet property for conversion texts and files.

      This online sample demonstrates functionality of ByteArray class for conversion between severalCodepages/CharSets. You can convert text or multibyte in any available code page to another code page or Unicode with this script. 
      The Form.SizeLimit is 1000000bytes. Please, do not post more source data. 

      Type some text to a textbox bellowCharset of this document and textbox is 

      or select a file and its charset as a source data:
 
Select character set of the source file: 
 or custom charset 

Select destination character set:  

  Output data: 
output to a textbox (as a string) 
export to a file, filename: 

     Note: The source file is handled as a text data with specified character set. The textbox is handled as a string data, default character set for the textbox is the same as a charset of this document.

     Change html charset (default character set for this document)

Another character set:  

or try other custom charset (see ConvertCodePages): 
  This charset is sent to a browser as a meta charset element of this HTML document and Content-Type: http header. Client browser handles the data from the source form as a string data encoded by document charset (utf-8 in the case of this document) and sends the data as a binary http stream to a web server. You can choose another character set for the conversion of the source text data (the textarea).
Posted by 삼스

I18n Guy, your character encoding advisor

Character Sets And Code Pages At The Push Of A Button

Logo for XenCraft - We make business work around the world

Code Pages, Character Encodings from Software Vendors and Standards Bodies

Here you can find character set and code page information from software vendors (Microsoft, HP, IBM, Sun, etc.) and international standards organizations (e.g. ISO, ECMA, INCITS, etc.). Push any "button" and you will be taken either to the chart of a code page provided by the vendor, or the vendor's web page of links to code page charts. This gives you fast access to popular code pages, as well as access to more complete lists of code page charts.

ABLE Innovations - Content and Product Globalization
Content and Product Globalization

Organization

The links are (mostly) organized by vendor or standard organization. Some code pages are listed redundantly, usually because the code page is being described by different vendors. Sometimes the difference is important. For example, one vendor's view of a code page may be different from another's. Certainly character conversion or mapping tables may be very different. Sometimes a code page has been updated and one vendor is still referring to an earlier version of the code page.

Character Encodings, Transformation Formats, Double-Byte, Multi-byte, UTF...

Note that a "code page" is also known by various other names: codepage, encoding, charset, character set, coded character set, (CCS), graphic character set, character map et al. Some of these have more specific names DBCS (double-byte character set), MBCS (multi-byte character set). Some encodings are the result of transformations, and are known as transformation formats, examples include Unicode UTF-8, UTF-16, UTF-32.

Unicode UTF-16 Surrogate Code Points, or Supplementary Characters

If you are interested in UTF-16 surrogate code points, or supplementary characters, see 
Setting up Microsoft Windows NT, 2000 or Windows XP to Support Unicode Supplementary Characters and 
Conversion Table: Unicode Surrogates to Scalar Value/UTF-32

Other Unicode pages on this site that may be of interest include: Cheat Sheet: Unicode-Enabling Microsoft C/C++ Source Code,Hiragana CharactersHebrew CharactersBenefits of the Unicode Standard, and the Compelling Unicode Demo.

TABLE OF CONTENTS
Push A Button To Get Code Page Information

Czyborra's Site

www.czyborra.com/charsets is offline. Fortunately, Kevin Atkinson has mirrored it at aspell.net/charsets. These buttons now link to his mirror. Thanks Kevin.

Roman Czyborra's site

Czyborra's Vendor Codepages

Czyborra's Vietnamese page

Czyborra's ASCII/ISO 646 page

Czyborra's ISO 8859 Alphabet Soup

So vat's Unicode? Chicken soup?

Hong Kong Supplementary Character Set (HKSCS)

Hong Kong Supplementary Character Set (HKSCS)

Hong Kong ITF on ISO 10646

Here are many transcoding tables expressed in XML files using theCharacter Mapping Markup Language (CharMapML, UTR 22). The encoding conversion data is used in the Internationalization Components for Unicode (ICU) open source library.

In the following web pages, leadbytes are indicated by light gray background shading. Each of these leadbytes links to a new page showing the 256 character block associated with that leadbyte. Unused leadbytes are identified by a darker gray background.

Posted by 삼스

 

The Unicode conversion filter offers conversions between the following code pages:

For more information on code pages, please see

Code-Page Identifiers

(*) The list of available code pages may be different on your system. You can install additional code pages using Control Panel\Regional Options.

IdentifierName
037 IBM EBCDIC - U.S./Canada
437 OEM - United States
500 IBM EBCDIC - International
708 Arabic - ASMO 708
709 Arabic - ASMO 449+, BCON V4
710 Arabic - Transparent Arabic
720 Arabic - Transparent ASMO
737 OEM - Greek (formerly 437G)
775 OEM - Baltic
850 OEM - Multilingual Latin I
852 OEM - Latin II
855 OEM - Cyrillic (primarily Russian)
857 OEM - Turkish
858 OEM - Multlingual Latin I + Euro symbol
860 OEM - Portuguese
861 OEM - Icelandic
862 OEM - Hebrew
863 OEM - Canadian-French
864 OEM - Arabic
865 OEM - Nordic
866 OEM - Russian
869 OEM - Modern Greek
870 IBM EBCDIC - Multilingual/ROECE (Latin-2)
874 ANSI/OEM - Thai (same as 28605, ISO 8859-15)
875 IBM EBCDIC - Modern Greek
932 ANSI/OEM - Japanese, Shift-JIS
936 ANSI/OEM - Simplified Chinese (PRC, Singapore)
949 ANSI/OEM - Korean (Unified Hangeul Code) -> EUC-KR
950 ANSI/OEM - Traditional Chinese (Taiwan; Hong Kong SAR, PRC)
1026 IBM EBCDIC - Turkish (Latin-5)
1047 IBM EBCDIC - Latin 1/Open System
1140 IBM EBCDIC - U.S./Canada (037 + Euro symbol)
1141 IBM EBCDIC - Germany (20273 + Euro symbol)
1142 IBM EBCDIC - Denmark/Norway (20277 + Euro symbol)
1143 IBM EBCDIC - Finland/Sweden (20278 + Euro symbol)
1144 IBM EBCDIC - Italy (20280 + Euro symbol)
1145 IBM EBCDIC - Latin America/Spain (20284 + Euro symbol)
1146 IBM EBCDIC - United Kingdom (20285 + Euro symbol)
1147 IBM EBCDIC - France (20297 + Euro symbol)
1148 IBM EBCDIC - International (500 + Euro symbol)
1149 IBM EBCDIC - Icelandic (20871 + Euro symbol)
1200 Unicode UCS-2 Little-Endian (BMP of ISO 10646)
1201 Unicode UCS-2 Big-Endian
1250 ANSI - Central European
1251 ANSI - Cyrillic
1252 ANSI - Latin I
1253 ANSI - Greek
1254 ANSI - Turkish
1255 ANSI - Hebrew
1256 ANSI - Arabic
1257 ANSI - Baltic
1258 ANSI/OEM - Vietnamese
1361 Korean (Johab)
10000 MAC - Roman
10001 MAC - Japanese
10002 MAC - Traditional Chinese (Big5)
10003 MAC - Korean
10004 MAC - Arabic
10005 MAC - Hebrew
10006 MAC - Greek I
10007 MAC - Cyrillic
10008 MAC - Simplified Chinese (GB 2312)
10010 MAC - Romania
10017 MAC - Ukraine
10021 MAC - Thai
10029 MAC - Latin II
10079 MAC - Icelandic
10081 MAC - Turkish
10082 MAC - Croatia
12000 Unicode UCS-4 Little-Endian
12001 Unicode UCS-4 Big-Endian
20000 CNS - Taiwan
20001 TCA - Taiwan
20002 Eten - Taiwan
20003 IBM5550 - Taiwan
20004 TeleText - Taiwan
20005 Wang - Taiwan
20105 IA5 IRV International Alphabet No. 5 (7-bit)
20106 IA5 German (7-bit)
20107 IA5 Swedish (7-bit)
20108 IA5 Norwegian (7-bit)
20127 US-ASCII (7-bit)
20261 T.61
20269 ISO 6937 Non-Spacing Accent
20273 IBM EBCDIC - Germany
20277 IBM EBCDIC - Denmark/Norway
20278 IBM EBCDIC - Finland/Sweden
20280 IBM EBCDIC - Italy
20284 IBM EBCDIC - Latin America/Spain
20285 IBM EBCDIC - United Kingdom
20290 IBM EBCDIC - Japanese Katakana Extended
20297 IBM EBCDIC - France
20420 IBM EBCDIC - Arabic
20423 IBM EBCDIC - Greek
20424 IBM EBCDIC - Hebrew
20833 IBM EBCDIC - Korean Extended
20838 IBM EBCDIC - Thai
20866 Russian - KOI8-R
20871 IBM EBCDIC - Icelandic
20880 IBM EBCDIC - Cyrillic (Russian)
20905 IBM EBCDIC - Turkish
20924 IBM EBCDIC - Latin-1/Open System (1047 + Euro symbol)
20932 JIS X 0208-1990 & 0121-1990
20936 Simplified Chinese (GB2312)
21025 IBM EBCDIC - Cyrillic (Serbian, Bulgarian)
21027 Extended Alpha Lowercase
21866 Ukrainian (KOI8-U)
28591 ISO 8859-1 Latin I
28592 ISO 8859-2 Central Europe
28593 ISO 8859-3 Latin 3
28594 ISO 8859-4 Baltic
28595 ISO 8859-5 Cyrillic
28596 ISO 8859-6 Arabic
28597 ISO 8859-7 Greek
28598 ISO 8859-8 Hebrew
28599 ISO 8859-9 Latin 5
28605 ISO 8859-15 Latin 9
29001 Europa 3
38598 ISO 8859-8 Hebrew
50220 ISO 2022 Japanese with no halfwidth Katakana
50221 ISO 2022 Japanese with halfwidth Katakana
50222 ISO 2022 Japanese JIS X 0201-1989
50225 ISO 2022 Korean
50227 ISO 2022 Simplified Chinese
50229 ISO 2022 Traditional Chinese
50930 Japanese (Katakana) Extended
50931 US/Canada and Japanese
50933 Korean Extended and Korean
50935 Simplified Chinese Extended and Simplified Chinese
50936 Simplified Chinese
50937 US/Canada and Traditional Chinese
50939 Japanese (Latin) Extended and Japanese
51932 EUC - Japanese
51936 EUC - Simplified Chinese
51949 EUC - Korean
51950 EUC - Traditional Chinese
52936 HZ-GB2312 Simplified Chinese
54936 Windows XP: GB18030 Simplified Chinese (4 Byte)
57002 ISCII Devanagari
57003 ISCII Bengali
57004 ISCII Tamil
57005 ISCII Telugu
57006 ISCII Assamese
57007 ISCII Oriya
57008 ISCII Kannada
57009 ISCII Malayalam
57010 ISCII Gujarati
57011 ISCII Punjabi
65000 Unicode UTF-7
65001 Unicode UTF-8
Posted by 삼스