지도 도구
이 장은 SDK에 들어 있는 지도 도구(이동, 정보, 측정, 선택, 만들기, 개체 이동, 꼭짓점 편집)를 응용 프로그램에 붙이는 방법을 설명합니다. 도구가 응용 프로그램에 요구하는 호스트를 구현하고, 도구 컨트롤러를 만들어 지도 뷰와 편집 객체에 연결하고, 마우스와 키 입력을 넘기고, 도구가 보내는 요청, 문맥 메뉴, 오버레이, 메시지에 응답하는 순서입니다. 호스트 호출 안에서 컨트롤러를 다시 부를 때의 규칙과 객체의 수명도 다룹니다.
이 장의 코드는 sdk_samples의 maptools 예제에서 가져왔습니다. 실행할 때는 데이터 폴더를 첫 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더>). 예제는 화면 없이 입력을 직접 만들어 넘깁니다. 편집 도구를 쓰므로 데이터 폴더의 harbor_town.gpkg를 임시 폴더에 복사해 쓰기로 열고, 끝에 편집을 취소한 뒤 임시 폴더를 지웁니다. 데이터 폴더의 파일은 바뀌지 않습니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).
선택 서비스는 9장 선택에서, 편집 모드와 편집 컨트롤러는 10장 편집에서 설명했습니다. 지도 좌표와 화면 좌표의 변환은 7장에 있습니다.
이 장이 다루지 않는 것. 오버레이를 실제로 화면에 그리는 방법과, 화면 컨트롤(창, 위젯)의 마우스와 키 이벤트를 도구 입력으로 바꾸어 연결하는 방법은 UI 계층이 정할 일이므로 이 장에서 다루지 않습니다. 이 장은 SDK가 무엇을 받고 무엇을 돌려주는지만 설명합니다.
누가 무엇을 하는가
도구의 상태 기계는 SDK 안에 있습니다. 끌기를 시작했는지, 스케치에 점이 몇 개인지, 어떤 피처를 옮기는 중인지는 도구 컨트롤러 glsMapToolController가 압니다. 응용 프로그램은 두 가지를 합니다.
- 입력을 넘깁니다. 마우스 누름, 이동, 놓음, 더블 클릭과 키를 컨트롤러의
PointerDown,PointerMove,PointerUp,PointerDoubleClick,KeyDown으로 넘깁니다(입력 넘기기). 지금 어떤 도구를 쓸지는SetMode로 정합니다(모드). - 호스트 호출에 응답합니다. 도구는 화면, 선택, 피처 만들기, 편집 허가처럼 SDK 밖의 일이 필요할 때 응용 프로그램이 구현한 호스트를 부릅니다(호스트 구현).
화면에 보이는 것은 응용 프로그램이 그립니다. 도구는 그릴 내용을 오버레이 스냅숏으로, 상태 문구를 메시지의 종류 번호로, 문맥 메뉴를 메뉴 스냅숏으로 줍니다. SDK는 화면에 보일 문구를 만들지 않습니다.
예제는 화면 없이 이 흐름을 따라갑니다. 지도 좌표의 장소를 WorldToScreen으로 화면 좌표로 바꾸어 입력을 만들고, 호스트는 받은 호출을 세고 메시지를 종류 번호로 출력합니다.
호스트 구현
호스트는 도구가 부르는 함수의 묶음입니다. 모든 호스트 함수는 컨트롤러 호출 안에서, 그 호출을 한 스레드에서 동기로 불립니다. 컨트롤러 밖에서 따로 불리는 일은 없습니다.
| 함수 | 언제 불리는가 | 응답 | 예제의 구현 |
|---|---|---|---|
RequestMapUpdate |
이동 도구가 뷰를 옮길 때, 편집 도구가 피처를 바꾼 뒤 | 지도를 다시 그립니다 | 셉니다 |
RequestOverlayUpdate |
도구가 오버레이의 새 판을 낼 때마다. 이동 도구는 뷰를 옮길 때도 부릅니다 | GetOverlay로 읽어 다시 그립니다 |
셉니다 |
NotifyViewChanged |
이동 도구가 뷰의 중심을 바꿀 때(이동마다, 놓을 때) | 축척, 좌표 표시처럼 뷰에 따르는 것을 고칩니다 | 셉니다 |
SyncViewport |
이동 도구가 끌기를 시작할 때(누를 때) | 끌기 전에 지도 뷰를 화면 상태와 맞출 기회입니다 | 셉니다 |
ShowMessage |
도구가 상태 문구나 실패를 알릴 때 | 종류 번호로 문구를 만들어 보입니다(메시지) | 종류 번호를 출력합니다 |
SetPointerCapture |
끌기를 시작하고 끝낼 때. 놓는 쪽은 잡은 뒤에만 부릅니다 | 화면 컨트롤의 마우스 캡처를 켜고 끕니다 | 상태를 기록합니다 |
GetDragThresholdPixels |
누른 뒤의 이동이 끌기인지 클릭인지 가를 때 | 기기 픽셀. 0 이하이면 4를 씁니다 | 4 |
GetSnapSettings |
스냅하는 도구가 점을 정할 때 | 스냅 모드, 허용 거리(기기 픽셀), 범위. false이면 스냅하지 않습니다 |
false |
GetSnapTargetLayerId |
위와 같음. 또 선, 다각형 만들기의 스케치에 점이 있거나 사각형, 타원 만들기로 끄는 동안에는 스냅 설정과 관계없이 바깥 컨트롤러 호출이 끝날 때마다 | 범위가 TargetLayer일 때 대상 레이어 id. 비었으면 그 범위로는 스냅하지 않습니다. 만들기 도구는 이 레이어를 지금 그려 넣는 레이어로 다루므로, 그리는 동안 그 레이어를 히트맵 스타일로 바꾸는 것은 거절됩니다 |
빈 문자열 |
ExecuteSelection |
선택 도구가 선택을 정했을 때 | 요청대로 선택합니다(선택 도구) | 선택 서비스로 실행합니다 |
IdentifyAt |
정보 도구의 클릭, 메뉴의 IdentifyHere |
그 점의 피처를 보여 줍니다 | 셉니다 |
IdentifyInRect |
정보 도구로 끈 사각형(두 변이 모두 2픽셀보다 길 때) | 사각형 안의 피처를 보여 줍니다 | 셉니다 |
CreateFeature |
만들기 도구가 모양을 끝냈을 때 | 피처를 만듭니다(만들기 도구) | 편집 컨트롤러로 점을 더합니다 |
GetAppCommandState |
메뉴를 만들 때, 기본 키를 처리할 때, 메뉴 항목을 실행할 때, 개체 이동 도구가 선택을 지우기 전 | 응용 프로그램 명령의 상태 Hidden, Disabled, Enabled |
선택이 있으면 ClearSelection만 Enabled |
InvokeAppCommand |
명령 메뉴 항목, 기본 키, 개체 이동 도구가 선택을 지울 때 | 명령을 실행합니다(문맥 메뉴) | ClearSelection을 실행합니다 |
SelectEditTargetAt |
편집 도구에서 대상을 고를 때(개체 이동과 꼭짓점 편집) | 편집할 수 있는 레이어로 한정한 단일 선택을 하고 결과를 돌려줍니다. 후보 레이어가 없으면 NoHit입니다 |
레이어 필터를 건 선택 서비스로 실행합니다 |
CanEditFeatureGeometry |
편집 도구가 선택을 대상으로 불러올 때 | 그 레이어의 지오메트리를 바꿔도 되는지 | 편집 컨트롤러의 IsOperationAllowed(layerId, Update) |
BeginFeatureGeometryEdit |
편집 도구가 지오메트리를 쓰기 직전 | false이면 아무것도 쓰지 않습니다 |
위와 같음 |
EndFeatureGeometryEdit |
true를 돌려준 BeginFeatureGeometryEdit 뒤에는 언제나 |
속성 표처럼 편집에 따르는 화면을 고칩니다 | 바뀐 개수를 기록합니다 |
뒤의 네 함수는 개체 이동과 꼭짓점 편집에만 쓰입니다. 그 도구를 쓰지 않으면 SelectEditTargetAt은 NoHit, CanEditFeatureGeometry와 BeginFeatureGeometryEdit는 false를 돌려주고, EndFeatureGeometryEdit는 아무것도 하지 않아도 됩니다. 아무것도 하지 않아도 되는 함수(다시 그리기, 캡처, 식별 등)도 도구가 그 결과를 기다리지는 않으므로, 화면이 없는 예제처럼 세기만 해도 도구는 동작합니다.
예제의 선택 반경(3픽셀)과 끌기 임계값(4픽셀)은 예제가 고른 값입니다. 끌기 임계값과 스냅 허용 거리는 기기 픽셀입니다. 입력 좌표와 같은 단위입니다.
IGlsMapToolHost(gdk_dll/maptools/glsMapToolHost.h)의 순수 가상 함수 19개를 모두 구현합니다. 모든 함수가 noexcept이므로 예외를 밖으로 내보내면 안 됩니다. 예제의 호스트는 SDK 호출이 실패하면 첫 메시지를 failure에 두고(값을 돌려줘야 하는 함수는 C# 컨트롤러가 주는 것과 같은 기본값을 돌려줍니다), 단계가 컨트롤러 호출마다 돌아온 뒤 그것을 출력합니다. SelectEditTargetAt에서 후보 레이어가 없는 실패(NotFound, NoVisibleSelectableLayers)는 실패로 두지 않고 NoHit을 돌려줍니다. GetSnapTargetLayerId가 돌려준 문자열은 다음 호스트 호출 전까지 유효해야 합니다. ShowMessage의 ErrorDiagnostic과 ExecuteSelection의 Points는 그 호출 동안만 유효합니다.
// What the application gives the map tools. The tools call it on the thread
// that drives the controller, from inside a controller call. This host has no
// screen: it counts the calls, prints the tool messages with their kind
// number, runs selections through the selection service, creates points
// through the edit controller and lets the edit tools change layers the edit
// controller allows. Every function is noexcept: a failed SDK call is kept in
// `failure` and the step reports it after the controller call returns.
class SampleHost final : public GDK::IGlsMapToolHost
{
public:
SampleHost(GDK::glsMapView& view, GDK::glsSelectionService& selection, GDK::glsEditController& editor)
: view_(view), selection_(selection), editor_(editor)
{
}
// Set after the controller is created; used for the mode change below.
GDK::glsMapToolController* controller = nullptr;
// When set, CreateFeature asks for this mode from inside the call.
std::optional<GDK::glsMapToolMode> modeAfterCreate;
GDK::glsMapToolMode modeInsideCreate = GDK::glsMapToolMode::Pan;
int mapUpdates = 0;
int overlayUpdates = 0;
int viewChanges = 0;
int viewportSyncs = 0;
std::vector<GDK::glsMapToolMessageKind> messages; // kinds received, in order
bool captured = false;
int selections = 0;
GDK::glsMapToolSelectionShape lastShape = GDK::glsMapToolSelectionShape::Point;
GDK::glsSelectionApplyMode lastMode = GDK::glsSelectionApplyMode::Replace;
bool lastSingleHit = false;
int identifies = 0;
int targetPicks = 0;
int editsBegun = 0;
int editsEnded = 0;
int lastChangedCount = 0;
mutable std::string failure; // the first failed SDK call, empty when none failed
// The map and the overlay would be repainted here.
void RequestMapUpdate() noexcept override { ++mapUpdates; }
void RequestOverlayUpdate() noexcept override { ++overlayUpdates; }
// A scale or coordinate display would be updated here.
void NotifyViewChanged() noexcept override { ++viewChanges; }
// Pan calls this when a drag starts; the view already has the screen's size.
void SyncViewport() noexcept override { ++viewportSyncs; }
void ShowMessage(const GDK::glsMapToolMessage& message) noexcept override
{
messages.push_back(message.Kind);
if (message.Kind == GDK::glsMapToolMessageKind::OperationFailed) {
std::printf("[sample] tool message: kind %d, error domain %d, error kind %d\n",
static_cast<int>(message.Kind), static_cast<int>(message.ErrorDomain), message.ErrorKind);
} else {
std::printf("[sample] tool message: kind %d\n", static_cast<int>(message.Kind));
}
}
void SetPointerCapture(bool capture) noexcept override { captured = capture; }
int32_t GetDragThresholdPixels() const noexcept override { return kDragThreshold; }
bool GetSnapSettings(GDK::glsMapToolSnapSettings*) const noexcept override { return false; } // no snapping
const char* GetSnapTargetLayerId() const noexcept override { return ""; }
// The tool fixes shape, apply mode and single hit; the host picks the click
// radius and the spatial operation (here the default, Intersects).
void ExecuteSelection(const GDK::glsMapToolSelectionRequest& request) noexcept override
{
++selections;
lastShape = request.Shape;
lastMode = request.Mode;
lastSingleHit = request.SingleHit;
GDK::glsSelectionRequest options;
options.Mode = request.Mode;
options.SingleHit = request.SingleHit;
options.PreferAfterCurrent = request.PreferAfterCurrent;
check(request.Shape == GDK::glsMapToolSelectionShape::Point
? selection_.ExecuteAtScreenPoint(request.DevicePos.X, request.DevicePos.Y, kClickRadius, options,
nullptr)
: selection_.Execute(request.Points, request.PointCount, options, nullptr));
}
// An application would show the features at the point (for example with a hit test).
void IdentifyAt(GDK::glsScreenPoint) noexcept override { ++identifies; }
void IdentifyInRect(GDK::glsScreenPoint, GDK::glsScreenPoint) noexcept override { ++identifies; }
// The points are in map coordinates; AddFeatureFromSketch transforms them
// to the layer's coordinate system. places is a point layer, so this host
// creates points only.
void CreateFeature(GDK::glsMapToolMode mode, const GDK::glsMapPoint* points, int32_t count) noexcept override
{
if (points == nullptr || count < 1) {
return;
}
std::printf("[sample] CreateFeature: %s, %d point at %.4f %.4f\n", modeName(mode), count, points[0].X,
points[0].Y);
if (mode != GDK::glsMapToolMode::CreatePoint) {
return;
}
GDK::glsEditMutationOptions options; // the layer's edit session is open
if (!check(editor_.AddFeatureFromSketch(&view_, kPlaces, GDK::glsSketchGeometryKind::Point, points, count,
nullptr, 0, options, nullptr))) {
return;
}
if (modeAfterCreate && controller != nullptr) {
modeInsideCreate = controller->GetMode();
check(controller->SetMode(*modeAfterCreate)); // runs after the outer call returns
}
}
// Selection commands: enabled while something is selected. Others hidden.
// When the selection cannot be read, the command is hidden.
GDK::glsMapAppCommandState GetAppCommandState(GDK::glsMapAppCommand command) const noexcept override
{
if (command != GDK::glsMapAppCommand::ClearSelection) {
return GDK::glsMapAppCommandState::Hidden;
}
size_t required = 0;
const GDK::glsStatus status = selection_.GetSelectedLayerId(nullptr, 0, &required);
if (status.Code == GDK::glsResultCode::NotFound) {
return GDK::glsMapAppCommandState::Disabled; // nothing is selected
}
return check(status) ? GDK::glsMapAppCommandState::Enabled : GDK::glsMapAppCommandState::Hidden;
}
void InvokeAppCommand(GDK::glsMapAppCommand command) noexcept override
{
if (command == GDK::glsMapAppCommand::ClearSelection) {
check(selection_.ClearAll());
}
}
// ObjectMove / VertexEdit pick a target with a single-hit click selection
// limited to the layers whose geometry the edit tools may change. No such
// layer, or nothing at the point, is NoHit: the tool then shows its own
// message. Failed means the host has reported the failure itself.
GDK::glsMapToolEditTargetResult SelectEditTargetAt(const GDK::glsMapToolSelectionRequest& request) noexcept override
{
++targetPicks;
struct EditableLayers final : GDK::IGlsSelectionLayerFilter {
GDK::glsEditController& editor;
explicit EditableLayers(GDK::glsEditController& e) : editor(e) {}
bool IsCandidate(const char* layerId) noexcept override
{
return editor.IsOperationAllowed(layerId, GDK::glsEditOperation::Update);
}
} filter(editor_);
GDK::glsSelectionRequest options;
options.Mode = request.Mode;
options.SingleHit = true;
options.PreferAfterCurrent = request.PreferAfterCurrent;
GDK::glsSelectionResult result;
selection_.SetLayerFilter(&filter);
const GDK::glsStatus status =
selection_.ExecuteAtScreenPoint(request.DevicePos.X, request.DevicePos.Y, kClickRadius, options, &result);
const GDK::glsErrorDetail detail = GDK::glsGetLastErrorDetail(); // read right after the call
selection_.SetLayerFilter(nullptr);
if (status.Code == GDK::glsResultCode::NotFound && detail.Domain == GDK::glsErrorDomain::Selection &&
detail.Kind == static_cast<int32_t>(GDK::glsSelectionErrorKind::NoVisibleSelectableLayers)) {
return GDK::glsMapToolEditTargetResult::NoHit;
}
if (!check(status)) {
return GDK::glsMapToolEditTargetResult::Failed;
}
return result.GetApplied() ? GDK::glsMapToolEditTargetResult::Selected
: GDK::glsMapToolEditTargetResult::NoHit;
}
// The edit tools may change a layer when edit mode allows updates on it.
bool CanEditFeatureGeometry(const char* layerId) noexcept override
{
return editor_.IsOperationAllowed(layerId, GDK::glsEditOperation::Update);
}
bool BeginFeatureGeometryEdit(const char* layerId) noexcept override
{
++editsBegun;
return editor_.IsOperationAllowed(layerId, GDK::glsEditOperation::Update);
}
// Attribute tables or edit buttons would be refreshed here.
void EndFeatureGeometryEdit(const char*, int32_t changedCount) noexcept override
{
++editsEnded;
lastChangedCount = changedCount;
}
private:
bool check(const GDK::glsStatus& status) const noexcept
{
if (!status.IsOk() && failure.empty()) {
const char* message = GDK::glsGetLastErrorMessage();
failure = message ? message : "";
}
return status.IsOk();
}
GDK::glsMapView& view_;
GDK::glsSelectionService& selection_;
GDK::glsEditController& editor_;
};
컨트롤러 만들기와 연결
컨트롤러는 호스트를 받아 만들고, 지도 뷰와 편집 객체를 연결합니다.
- 지도 뷰. 도구는 이 뷰로 좌표를 바꾸고, 이동 도구는 이 뷰의 중심을 바꿉니다. 다른 뷰를 연결하면 진행 중인 조작이 취소됩니다(이유
SessionChanged). 같은 뷰를 다시 연결하면 아무 일도 없습니다. - 편집 연결.
SetEditBinding(editController, sessionState)은 10장의 편집 컨트롤러와 그 세션 상태를 개체 이동과 꼭짓점 편집 도구에 연결합니다. 다른 쌍을 연결하면 진행 중인 조작이 취소되고 편집 도구가 불러온 대상이 버려집니다. 같은 쌍을 다시 연결하면 아무 일도 없습니다. 연결하지 않으면 두 도구는 대상을 불러오지 않습니다.VertexEdit는 켤 때 연결되지 않았다는 메시지(VertexEditNotConnected)를 보내고,ObjectMove는 켤 때 대상을 클릭하라는 메시지(MoveSelectOrClick)를, 지도를 누를 때MoveNotConnected를 보냅니다. - 모드.
SetMode로 도구를 고릅니다. 같은 모드를 다시 고르면 아무 일도 없고, 다른 모드를 고르면 앞의 도구가 끝나며(오버레이가 비고 캡처가 풀림) 새 도구가 시작합니다.GetMode는 마지막으로 고른 모드,IsActive는 도구가 켜져 있는지입니다.
예제는 편집 객체와 선택 서비스를 만든 뒤 호스트와 컨트롤러를 만들고, 이동 모드로 시작합니다. 지도 뷰는 640x480이고 구역 전체로 맞추었으며, 선택 도구가 쓰도록 places만 선택 가능하게 바꿨습니다(9장).
gdk_dll/glsGDK.h는 컨트롤러 헤더를 가져오지 않으므로 gdk_dll/maptools/glsMapToolController.h를 포함합니다. glsMapToolController(IGlsMapToolHost*)는 호스트를 빌리며, 만든 직후에는 켜진 도구가 없습니다. SetMapView와 SetEditBinding도 빌린 포인터를 받습니다(수명과 해제). SetMode는 glsMapToolMode의 값이 아니면 NotSupported로 실패합니다. 컨트롤러는 복사할 수 없으므로 예제는 std::unique_ptr에 담습니다.
// The controller borrows the host, the map view and the edit objects; each of
// them must outlive it (or be unbound first). No tool is active until SetMode.
// SetEditBinding connects the edit tools (ObjectMove, VertexEdit) to the edit
// controller and its session state.
static std::unique_ptr<GDK::glsMapToolController> createController(SampleHost& host, GDK::glsMapView& view,
GDK::glsEditController& editor,
GDK::glsEditSessionState& session)
{
auto tools = std::make_unique<GDK::glsMapToolController>(&host);
if (!succeeded(tools->SetMapView(&view)) || !succeeded(tools->SetEditBinding(&editor, &session)) ||
!succeeded(tools->SetMode(GDK::glsMapToolMode::Pan))) {
return nullptr;
}
host.controller = tools.get();
const GDK::glsMapToolMode mode = tools->GetMode();
const bool active = tools->IsActive();
std::printf("[sample] map tool controller created: mode %s, active %s\n", modeName(mode), yesNo(active));
if (mode != GDK::glsMapToolMode::Pan || !active) {
unexpected("expected Pan to be active");
host.controller = nullptr;
return nullptr;
}
return tools;
}
입력 넘기기
포인터 이벤트. 마우스 이벤트 하나가 포인터 이벤트 하나입니다.
| 필드 | 뜻 |
|---|---|
기기 위치 (C++ DevicePos, C# DeviceX, DeviceY) |
화면 좌표, 기기 픽셀. 원점은 지도 화면의 왼쪽 위 |
지도 위치 (C++ WorldPos, C# WorldX, WorldY)와 WorldValid |
같은 점의 지도 좌표. WorldValid가 true일 때만 씁니다 |
Button |
이 이벤트를 일으킨 버튼의 비트(Left 1, Right 2, Middle 4). 이동에는 0 |
Buttons |
지금 눌려 있는 버튼의 비트 |
Modifiers |
수정 키의 비트(Shift 1, Control 2, Alt 4, Meta 8) |
ClickCount |
클릭 횟수. 기본값 1 |
점을 찍거나 옮기는 도구는 그 점의 지도 위치를 스스로 계산하지 않고 이벤트의 값(스냅이 켜져 있으면 기기 위치로 스냅한 점)을 씁니다. 끌어서 그리는 사각형, 원, 타원만 기기 위치를 연결된 지도 뷰로 바꾸고, 정보 도구(IdentifyAt, IdentifyInRect)와 클릭 선택(Point 모양의 ExecuteSelection)은 기기 위치를 그대로 호스트에 넘깁니다. 응용 프로그램은 기기 위치를 지도 뷰의 ScreenToWorld로 바꿔 함께 넣으세요. 고해상도 화면에서 논리 좌표를 쓰는 UI는 기기 픽셀로 바꿔서 넘깁니다(7장). 예제의 pointer 도우미(C# Pointer)가 이렇게 이벤트를 만듭니다.
더블 클릭. 더블 클릭의 두 번째 누름은 PointerDown이 아니라 PointerDoubleClick으로 넘깁니다. 그 뒤의 놓음은 PointerUp으로 넘깁니다. 스케치 도구는 두 번째 누름이 PointerDown으로 오면 점을 하나 더 찍습니다.
처리 여부. 입력 함수는 도구가 그 입력을 썼는지를 돌려줍니다(C++ bool* outHandled, C# 반환값). false이면 응용 프로그램이 그 입력에 자기 기본 동작을 해도 됩니다. 켜진 도구가 없으면 포인터 입력은 모두 false입니다.
키. 키는 glsMapToolKey(Escape, Delete, Backspace, Enter, Undo, 그 밖은 Other)와 수정 키로 넘깁니다. 되돌리기 단축키(Ctrl+Z 등)는 키 그대로가 아니라 Undo로 바꿔 넘깁니다. 도구가 키를 쓰지 않았고 수정 키가 없으면 컨트롤러가 기본 키를 처리합니다. Escape는 ClearSelection, Delete는 DeleteSelection 명령이 Enabled일 때 그 명령을 실행합니다(문맥 메뉴). 켜진 도구가 없을 때도 그렇습니다.
그 밖의 알림.
ViewChanged(): 응용 프로그램이 뷰를 바꿨을 때(확대, 축소, 중심 이동) 부릅니다. 편집 도구는 대상을 새 뷰에 맞춰 다시 그리게 합니다.Cancel(reason): 진행 중인 조작을 취소합니다. 도구는 켜진 채로 남습니다. 이유에 따라 남는 것이 다릅니다. 스케치 도구와 방위 측정은LostFocus에서 점을 남기고, 편집 도구는Escape,CaptureLost,LostFocus,ViewNavigation에서 진행 중인 끌기만 되돌리고 대상을 남깁니다. 그 밖의 이유는 조작 상태를 모두 버립니다.Deactivate(reason): 도구를 끕니다. 응용 프로그램이 만든 다른 도구가 입력을 받을 때 씁니다. 지금은 이유와 관계없이 같은 일을 합니다.
이동 모드에서 왼쪽 버튼으로 끌면 도구가 지도 뷰의 중심을 직접 바꿉니다. 누를 때 SyncViewport와 캡처를, 이동마다 NotifyViewChanged, RequestOverlayUpdate, RequestMapUpdate를, 놓을 때 캡처 해제와 NotifyViewChanged를 부릅니다. 예제는 화면 중앙에서 오른쪽으로 100픽셀 끌어 중심이 서쪽으로 옮겨진 것을 확인하고, 중심을 되돌린 뒤 ViewChanged를 부릅니다.
입력 함수는 glsStatus를 돌려주며, 처리 여부의 출력 포인터가 nullptr이면 InvalidArgument로 실패합니다. 버튼과 수정 키의 비트는 glsMapToolBits(glsMapToolButton::Left)처럼 만듭니다.
// Input goes in as pointer events in device pixels with the map position the
// UI computed for them. In Pan mode a left drag moves the view itself: on each
// move the tool sets the view center and asks the host to repaint
// (RequestMapUpdate) and to update what shows the view (NotifyViewChanged).
// The handled flag says whether the tool used the event. When the application
// changes the view itself, it calls ViewChanged.
static bool panDrag(Tools& t)
{
double x0 = 0;
double y0 = 0;
if (!succeeded(t.view.GetCenter(&x0, &y0))) {
return false;
}
const GDK::glsScreenPoint from{320.0f, 240.0f};
const GDK::glsScreenPoint to{420.0f, 240.0f};
const size_t mark = t.host.messages.size();
const int viewChanges = t.host.viewChanges;
const int mapUpdates = t.host.mapUpdates;
bool down = false;
bool moved = false;
bool up = false;
if (!sent(t, t.tools.PointerDown(pointer(t.view, from, kLeft, kLeft), &down))) {
return false;
}
const bool capturedDuringDrag = t.host.captured;
if (!sent(t, t.tools.PointerMove(pointer(t.view, to, 0, kLeft), &moved)) ||
!sent(t, t.tools.PointerUp(pointer(t.view, to, kLeft, 0), &up))) {
return false;
}
double x1 = 0;
double y1 = 0;
if (!succeeded(t.view.GetCenter(&x1, &y1))) {
return false;
}
const int changed = t.host.viewChanges - viewChanges;
const int updated = t.host.mapUpdates - mapUpdates;
std::printf("[sample] pan: handled %s, center %.4f %.4f -> %.4f %.4f\n", yesNo(down && moved && up), x0, y0, x1,
y1);
std::printf("[sample] pan: captured during the drag %s, after it %s; view changes %d, map updates %d\n",
yesNo(capturedDuringDrag), yesNo(t.host.captured), changed, updated);
if (!succeeded(t.view.SetCenter(x0, y0)) || !sent(t, t.tools.ViewChanged())) {
return false;
}
return (down && moved && up && x1 < x0 - 0.01 && std::abs(y1 - y0) < 1e-9 && capturedDuringDrag &&
!t.host.captured && changed == 2 && updated == 1 && messagesSince(t.host, mark, {})) ||
unexpected("expected the view to move west");
}
모드
glsMapToolMode의 값마다 도구가 하나씩 있습니다. 값은 고정되어 있습니다(값이 고정된 열거형).
| 모드 | 하는 일 | 부르는 호스트 함수 | 필요한 연결 |
|---|---|---|---|
Pan |
왼쪽 버튼으로 끌어 뷰를 옮김 | SyncViewport, NotifyViewChanged, RequestMapUpdate |
지도 뷰 |
Info |
클릭한 점, 또는 끈 사각형의 피처를 식별 | IdentifyAt, IdentifyInRect |
지도 뷰 |
MeasureDistance |
클릭으로 점을 찍어 길이를 잼 | (결과는 오버레이) | 지도 뷰 |
MeasureArea |
클릭으로 점을 찍어 면적과 둘레를 잼 | (결과는 오버레이) | 지도 뷰 |
MeasureBearing |
두 점의 방위각과 거리를 잼 | ShowMessage (결과는 오버레이에도) |
지도 뷰 |
SelectPoint |
클릭으로 선택, 끌면 사각형으로 선택 | ExecuteSelection |
지도 뷰 |
SelectRect, SelectCircle |
끈 사각형, 원으로 선택 | ExecuteSelection |
지도 뷰 |
SelectPolygon |
클릭으로 다각형을 그려 선택 | ExecuteSelection |
지도 뷰 |
CreatePoint, CreateText |
누를 때 그 점 하나를 넘김 | CreateFeature |
지도 뷰 |
CreateLine, CreatePolygon |
클릭으로 선, 다각형을 그려 넘김 | CreateFeature |
지도 뷰 |
CreateRect, CreateEllipse |
끈 사각형, 타원을 다각형으로 넘김 | CreateFeature |
지도 뷰 |
ObjectMove |
선택한 피처를 끌어 옮김 | 편집 도구의 네 함수, InvokeAppCommand |
지도 뷰, 편집 연결 |
VertexEdit |
선택한 피처의 꼭짓점을 옮기고, 더하고, 지움 | 편집 도구의 네 함수 | 지도 뷰, 편집 연결 |
측정. 클릭마다 점을 더하고, 더블 클릭이나 Enter로 끝냅니다. Backspace와 Delete는 마지막 점을 지우고 Escape는 스케치를 지웁니다. 결과는 메시지가 아니라 오버레이의 이름표로 옵니다. 길이는 MeasureDistanceLabel(RealArgs[0] 길이), 면적은 MeasureAreaLabel(RealArgs[0] 면적, RealArgs[1] 둘레)이고, 점이 모자라면 MeasureSelectFirstPoint, SelectAtLeastThreePoints입니다. 값은 지도 뷰의 MeasureLength, MeasureArea 규칙을 따릅니다. 지리 좌표계와 웹 메르카토르(EPSG:3857)는 미터와 제곱미터이며, 수평 선형 단위를 판별할 수 있는 다른 투영 좌표계도 미터와 제곱미터로 환산합니다. 예를 들어 국제 피트 단위 CRS의 길이 100은 30.48미터입니다. CRS가 없거나 수평 단위를 판별할 수 없으면 기존처럼 지도 단위와 지도 단위의 제곱을 반환합니다. 끝낸 결과는 다음 클릭이 새 측정을 시작할 때까지 남습니다. 방위 측정은 다르게 동작합니다. 첫 클릭에 BearingSecondPoint, 두 번째 클릭에 BearingGeodesic(RealArgs[0] 방위각의 도, RealArgs[1] 거리)을 ShowMessage로 보내고, 같은 메시지를 오버레이의 이름표로도 둡니다(첫 점만 있을 때는 포인터까지의 값). 방위각은 지도 뷰의 MeasureBearing, 거리는 MeasureLength의 규칙을 따릅니다. 지도 뷰가 연결되지 않았거나 둘 중 하나를 재지 못하면 지도 좌표로 계산한 BearingGrid(도, 지도 단위)를 보냅니다. 세 번째 클릭은 새 측정을 시작합니다.
예제는 Lighthouse Pier와 Spice Market을 클릭하고 두 번째 점에서 더블 클릭해 끝냅니다. 점은 2개이고 이름표는 MeasureDistanceLabel(10), 길이는 약 3070미터이며 메시지는 없습니다.
// Each click adds a point; a double click finishes. The second press of a
// double click goes in as PointerDoubleClick, not as PointerDown. The result
// is not a message: it is the overlay label (the length in meters) and the
// copy item of the context menu.
static bool measureDistance(Tools& t)
{
GDK::glsScreenPoint a;
GDK::glsScreenPoint b;
const size_t mark = t.host.messages.size();
if (!sent(t, t.tools.SetMode(GDK::glsMapToolMode::MeasureDistance)) || !screenOf(t.view, kLighthousePier, a) ||
!screenOf(t.view, kSpiceMarket, b) || !click(t, a) || !click(t, b)) {
return false;
}
bool handled = false;
if (!sent(t, t.tools.PointerDoubleClick(pointer(t.view, b, kLeft, kLeft), &handled)) ||
!sent(t, t.tools.PointerUp(pointer(t.view, b, kLeft, 0), &handled))) {
return false;
}
GDK::glsMapToolOverlay overlay;
if (!succeeded(t.tools.GetOverlay(&overlay))) {
return false;
}
const GDK::glsMapToolMessage label = overlay.GetLabel();
const size_t messages = t.host.messages.size() - mark;
std::printf("[sample] measure: %d points, label kind %d, %.0f m, tool messages %zu\n", overlay.GetPointCount(),
static_cast<int>(label.Kind), label.RealArgs[0], messages);
return (overlay.GetPointCount() == 2 && label.Kind == GDK::glsMapToolMessageKind::MeasureDistanceLabel &&
label.RealArgs[0] > 3000 && label.RealArgs[0] < 3150 && messages == 0) ||
unexpected("expected a distance of about 3 km");
}
선택 도구
선택 도구는 선택을 직접 하지 않습니다. 선택할 모양이 정해지면 ExecuteSelection으로 요청을 넘기고, 호스트가 그 요청을 실행합니다. 보통은 9장의 선택 서비스로 실행합니다.
| 요청 필드 | 뜻 |
|---|---|
Shape |
Point(클릭) 또는 Polygon(사각형, 원, 다각형) |
기기 위치 (C++ DevicePos, C# DeviceX, DeviceY) |
Point일 때 클릭한 점, 기기 픽셀 |
Points |
Polygon일 때 고리의 점, 지도 좌표. 닫는 점은 없습니다 |
Mode |
Control이 눌렸으면 Toggle, 아니고 Shift이면 Add, 둘 다 아니면 Replace |
SingleHit, PreferAfterCurrent |
클릭에 Alt가 눌렸을 때만 둘 다 true |
점 선택의 반경과 다각형 선택의 공간 연산(Intersects, Contains)은 호스트가 정합니다. 요청을 선택 서비스의 ExecuteAtScreenPoint, Execute로 옮기는 방법과 적용 모드의 뜻은 9장 점으로 선택, 적용 모드에 있습니다.
SelectPoint: 끌기 임계값 안에서 놓으면 누른 점으로Point요청을 보냅니다. 임계값을 넘겨 끌면 사각형을 오버레이에 그리고, 놓을 때 그 사각형으로Polygon요청을 보냅니다.SelectRect,SelectCircle: 끈 모양으로Polygon요청을 보냅니다. 원은 64개 점으로 나타냅니다. 임계값 안에서 놓으면 놓은 점으로Point요청을 보냅니다.SelectPolygon: 측정처럼 점을 찍고, 끝낼 때 점이 3개 이상이면Polygon요청을 보냅니다.- 끌기 중에
Escape를 누르면 아무것도 선택하지 않고 끝냅니다.
예제는 SelectPoint 모드에서 Lighthouse Pier를 클릭합니다. 요청은 하나(Point, Replace, 단일 선택 아님)이고, 호스트가 선택 서비스로 실행해 places에 id 1이 선택됩니다.
// A selection tool does not select by itself: it hands the host a request
// (shape, apply mode, single hit), and the host runs it, here with the
// selection service. A click without modifier keys replaces the selection.
static bool selectWithTool(Tools& t)
{
GDK::glsScreenPoint pier;
const size_t mark = t.host.messages.size();
if (!sent(t, t.tools.SetMode(GDK::glsMapToolMode::SelectPoint)) || !screenOf(t.view, kLighthousePier, pier) ||
!click(t, pier)) {
return false;
}
int64_t id = -1;
int count = 0;
if (!succeeded(t.selection.GetSelectedIds(kPlaces, &id, 1, &count))) {
return false;
}
std::printf("[sample] select: %d request (%s, %s, single hit %s); places has %d selected, id %" PRId64 "\n",
t.host.selections, shapeName(t.host.lastShape), applyModeName(t.host.lastMode),
yesNo(t.host.lastSingleHit), count, id);
return (t.host.selections == 1 && t.host.lastShape == GDK::glsMapToolSelectionShape::Point &&
t.host.lastMode == GDK::glsSelectionApplyMode::Replace && !t.host.lastSingleHit && count == 1 &&
id == kLighthousePierId && messagesSince(t.host, mark, {})) ||
unexpected("expected Lighthouse Pier selected");
}
만들기 도구
만들기 도구도 피처를 직접 만들지 않습니다. 모양이 끝나면 CreateFeature(mode, points)로 모드와 점을 넘기고, 호스트가 피처를 만듭니다. 점은 지도 좌표입니다. 10장의 AddFeatureFromSketch는 지도 좌표의 점을 받아 레이어의 좌표계로 바꾸므로, 호스트는 점을 그대로 넘길 수 있습니다. 어느 레이어에 어떤 속성으로 만들지는 호스트가 정합니다.
| 모드 | 넘기는 점 |
|---|---|
CreatePoint, CreateText |
누른 점 하나. 메뉴의 CreatePointHere는 메뉴를 연 점 하나 |
CreateLine, CreatePolygon |
끝낸 스케치의 점(선 2개 이상, 다각형 3개 이상) |
CreateRect |
끈 사각형의 네 모서리(화면 기준 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래) |
CreateEllipse |
끈 사각형에 내접한 타원의 64개 점 |
선과 다각형의 스케치는 측정과 같은 키로 다룹니다(더블 클릭이나 Enter로 끝냄, Backspace와 Delete로 마지막 점 지움, Escape로 지움). 사각형과 타원은 끌기 임계값 안에서 놓으면 아무것도 넘기지 않습니다. 점, 선, 다각형 만들기는 호스트의 스냅 설정이 켜져 있으면 점을 스냅합니다. 다만 메뉴의 CreatePointHere는 스냅하지 않습니다. 스케치 도구는 자기 상태를 먼저 정리하고 CreateFeature를 부르며, 그동안 오버레이에 모양을 남겼다가 호출이 돌아오면 지웁니다. 그래서 호스트는 이 호출 안에서 속성을 묻는 대화 상자를 띄울 수 있습니다.
예제는 places로 편집 모드를 시작하고 CreatePoint 모드에서 빈 곳을 클릭합니다. 호스트가 AddFeatureFromSketch로 점을 더해 places는 편집 중 13건이 됩니다. 호스트는 이 호출 안에서 SelectPoint 모드를 요청하는데, 바뀐 모드는 바깥 호출이 돌아온 뒤에 적용됩니다(재진입).
// A create tool hands the finished shape to the host (CreateFeature) in map
// coordinates, and the host adds the feature. Here the host also asks for
// SelectPoint from inside that call: the change is deferred until the outer
// call returns, so the mode is still CreatePoint inside the call.
static bool createPointTool(Tools& t)
{
GDK::glsScreenPoint spot;
const size_t mark = t.host.messages.size();
if (!succeeded(t.editor.StartEditing(&t.view, kPlaces)) ||
!sent(t, t.tools.SetMode(GDK::glsMapToolMode::CreatePoint)) || !screenOf(t.view, kNewPoint, spot)) {
return false;
}
t.host.modeAfterCreate = GDK::glsMapToolMode::SelectPoint;
const bool clicked = click(t, spot);
t.host.modeAfterCreate.reset();
if (!clicked) {
return false;
}
const int64_t count = placesCount(t.places);
if (count < 0) {
return false;
}
const GDK::glsMapToolMode after = t.tools.GetMode();
std::printf("[sample] created point: places %" PRId64 " while editing\n", count);
std::printf("[sample] mode asked for inside CreateFeature: %s inside the call, %s after it\n",
modeName(t.host.modeInsideCreate), modeName(after));
return (count == 13 && t.host.modeInsideCreate == GDK::glsMapToolMode::CreatePoint &&
after == GDK::glsMapToolMode::SelectPoint && messagesSince(t.host, mark, {})) ||
unexpected("expected 13 places and a deferred mode change");
}
개체 이동과 꼭짓점 편집
ObjectMove와 VertexEdit는 편집 연결로 지오메트리를 읽고 바꾸는 편집 도구입니다. 필요한 것은 편집 연결과 호스트의 편집 함수 네 개입니다.
대상. 두 도구는 선택을 가진 레이어(선택 서비스의 GetSelectedLayerId가 돌려주는 레이어, 9장)의 선택된 피처를 대상으로 불러옵니다. 도구가 켜질 때 불러오며, 이때 호스트의 CanEditFeatureGeometry(layerId)에 묻습니다. false이면 불러오지 않으며 그 이유는 OperationFailed(영역 Edit, 종류 VertexEditNotSupported)입니다. 켤 때 불러오지 못하면 ObjectMove는 대상을 클릭하라는 메시지(MoveSelectOrClick)만 보내고, VertexEdit는 이유(선택이 없으면 VertexEditNeedsSelection)와 VertexEditClickTarget을 보냅니다. 호스트의 SelectEditTargetAt은 다음 때 부릅니다. ObjectMove에서는 불러온 대상이 없을 때, 대상이 아닌 곳을 눌렀을 때, 대상 위라도 Control, Shift, Alt 가운데 하나를 누른 채 눌렀을 때입니다. VertexEdit에서는 꼭짓점이 아닌 곳을 눌렀을 때입니다(Control을 누른 채 변을 누르면 꼭짓점을 넣으므로 부르지 않습니다). 호스트는 지도 지오메트리를 바꿀 수 있는 편집 레이어로 후보를 한정해 단일 선택을 하고(요청의 SingleHit은 언제나 true, Mode는 Control이면 Toggle, Shift이면 Add, PreferAfterCurrent는 Alt), 선택했으면 Selected, 맞은 것이나 후보 레이어가 없으면 NoHit, 실패해 이미 알렸으면 Failed를 돌려줍니다. Selected이면 도구는 선택을 다시 불러옵니다. NoHit이면 ObjectMove는 피처를 고르라는 메시지(MoveSelectFeatures)를 보내고, Failed이면 아무 메시지도 보내지 않습니다. VertexEdit는 두 경우 모두 메시지를 보내지 않습니다.
ObjectMove는 대상을 불러온 뒤 지도의 선택을 지웁니다(ClearSelection 명령이 Hidden이 아니면 InvokeAppCommand(ClearSelection)). VertexEdit는 선택을 그대로 둡니다.
조작.
ObjectMove: 대상을 눌러 끌면 대상 전체가 옮겨지고, 끌기 임계값 이상 움직인 뒤 놓으면 씁니다.Escape는 끌기 중이면 끌기를 되돌리고, 아니면 대상을 비우고 지도의 선택을 지웁니다.VertexEdit: 꼭짓점을 눌러 끌면 그 꼭짓점(같은 자리의 꼭짓점 포함)을 옮기고, 임계값 이상 움직인 뒤 놓으면 씁니다.Control을 누른 채 변을 누르면 꼭짓점을 넣고 끕니다. 변을 더블 클릭하면 꼭짓점을 넣고,Delete나Backspace는 고른 꼭짓점을 지웁니다(이 두 키는 피처 삭제로 넘어가지 않습니다).Escape는 대상을 다시 불러옵니다.
쓰기. 쓰기 전에 대상 지오메트리를 모두 레이어의 좌표계로 바꾸고, 하나라도 바꾸지 못하면 아무것도 쓰지 않습니다. 그 다음 순서는 다음과 같습니다.
BeginFeatureGeometryEdit(layerId)를 부릅니다.false이면 아무것도 쓰지 않습니다. 이때 도구는 오류 메시지를 보내지 않으므로 이유는 호스트가 알립니다(VertexEdit는 대상을 다시 불러오며 안내 메시지VertexEditHint를 보냅니다. 다시 불러오지 못하면VertexEditHint대신 불러오지 못한 이유를 보냅니다).- 대상을 레이어의 편집이 열리기 전에 불러왔고 편집이 아직 닫혀 있으면 편집 컨트롤러의
BeginEditingLayer로 엽니다. 이것은StartEditing이 기록한 레이어에만 됩니다(10장). 호스트가 1에서 직접 열어도 됩니다. - 대상마다 편집 컨트롤러의
UpdateFeatureGeometry로 대기 중인 변경에 넣습니다. 한 번의 쓰기가 되돌리기 한 단계(UpdateGeometry)입니다. - 하나라도 바뀌었으면 지도 뷰의 스냅 캐시를 비우고 다시 그리기를 요청하고
RequestMapUpdate를 부릅니다. EndFeatureGeometryEdit(layerId, changedCount)를 부릅니다. 1이true였으면 실패해도 언제나 부릅니다.
실패하면 OperationFailed 메시지에 오류 상세를 담아 보냅니다. ObjectMove는 대상을 원래 자리로 돌리고 편집 중인 데이터에서 다시 읽습니다. 파일에는 아무것도 쓰지 않으며, 저장과 취소는 10장의 컨트롤러 호출로 합니다. 두 도구의 문맥 메뉴에 있는 SaveEdits, CancelEdits 항목도 호스트의 InvokeAppCommand가 실행합니다.
예제는 SelectPoint 모드로 Spice Market을 선택하고 ObjectMove로 바꿉니다. 대상 1개를 불러오고(메시지 MoveDragHint, 57) 선택이 비워집니다. 대상을 오른쪽으로 40픽셀 끌어 놓으면 호스트의 BeginFeatureGeometryEdit와 EndFeatureGeometryEdit가 한 번씩 불리고(바뀐 피처 1개), 메시지 FeaturesMoved(64)가 오며, Spice Market이 동쪽으로 옮겨집니다.
// ObjectMove loads the selected features of the selection layer as its
// targets when it starts (asking CanEditFeatureGeometry) and clears the map
// selection through the ClearSelection command. Dragging a target moves it;
// on release the tool asks BeginFeatureGeometryEdit, stages the new geometry
// through the edit controller as one undo step, and calls
// EndFeatureGeometryEdit.
static bool moveSelected(Tools& t)
{
GDK::glsScreenPoint spice;
const size_t mark = t.host.messages.size();
const int begun = t.host.editsBegun;
const int ended = t.host.editsEnded;
if (!screenOf(t.view, kSpiceMarket, spice) || !click(t, spice) ||
!sent(t, t.tools.SetMode(GDK::glsMapToolMode::ObjectMove))) {
return false;
}
const bool loadMessages = messagesSince(t.host, mark, {GDK::glsMapToolMessageKind::MoveDragHint});
const size_t dragMark = t.host.messages.size();
GDK::glsMapToolOverlay overlay;
int selected = -1;
if (!succeeded(t.tools.GetOverlay(&overlay)) || !succeeded(t.selection.GetSelectedCount(kPlaces, &selected))) {
return false;
}
std::printf("[sample] object move: %d target loaded, places has %d selected\n", overlay.GetPathCount(),
selected);
const GDK::glsScreenPoint to{spice.X + 40.0f, spice.Y};
bool down = false;
bool moved = false;
bool up = false;
if (!sent(t, t.tools.PointerDown(pointer(t.view, spice, kLeft, kLeft), &down)) ||
!sent(t, t.tools.PointerMove(pointer(t.view, to, 0, kLeft), &moved)) ||
!sent(t, t.tools.PointerUp(pointer(t.view, to, kLeft, 0), &up))) {
return false;
}
GDK::glsMapPoint now;
if (!placeAt(t, kSpiceMarketId, now)) {
return false;
}
const int begunNow = t.host.editsBegun - begun;
const int endedNow = t.host.editsEnded - ended;
const bool canUndo = t.editor.CanUndo();
std::printf("[sample] moved Spice Market to %.4f %.4f; geometry edits begun %d, ended %d (%d changed); "
"can undo %s\n",
now.X, now.Y, begunNow, endedNow, t.host.lastChangedCount, yesNo(canUndo));
return (overlay.GetPathCount() == 1 && selected == 0 && loadMessages && down && moved && up &&
now.X > kSpiceMarket.X + 0.001 && std::abs(now.Y - kSpiceMarket.Y) < 1e-9 && begunNow == 1 &&
endedNow == 1 && t.host.lastChangedCount == 1 && canUndo &&
messagesSince(t.host, dragMark, {GDK::glsMapToolMessageKind::FeaturesMoved})) ||
unexpected("expected Spice Market to move east");
}
되돌리기. 도구가 쓴 변경은 편집 컨트롤러의 되돌리기 이력에 쌓이므로 10장의 Undo, Redo로 되돌립니다. 도구에도 따로 되돌릴 단계가 있을 수 있습니다.
HasUndoableStep(): 스케치 도구(측정, 다각형 선택, 선과 다각형 만들기)에 찍은 점이 있고 아직 끝내지 않았으면true입니다.UndoStep()은 마지막 점을 지웁니다. 스케치 도구는Undo키도 이렇게 처리합니다.BlocksEditHistory(): 편집 도구가 끌기 중이면true입니다. 이때는 편집 이력을 되돌리지 마세요.- 편집 이력을 되돌린 뒤에는
NotifyEditStateChanged()로 도구에 알립니다.ObjectMove는 대상을 피처 id로 다시 읽고(MoveTargetsLabel메시지),VertexEdit는 선택에서 다시 불러옵니다.
예제는 도구의 단계가 없고 끌기 중도 아니므로 편집 컨트롤러로 되돌린 뒤 도구에 알립니다. Spice Market이 제자리로 돌아오고, 도구의 대상도 다시 읽혀 같은 자리에 있습니다(메시지 60).
// An Undo command goes to the tool first when it has a step of its own (a
// sketch point); otherwise, unless the tool is in a drag, to the edit
// controller. After an edit undo the tool is told with NotifyEditStateChanged,
// and ObjectMove reads its targets again.
static bool toolUndo(Tools& t)
{
const size_t mark = t.host.messages.size();
const bool toolStep = t.tools.HasUndoableStep();
const bool blocked = t.tools.BlocksEditHistory();
bool undone = false;
if (toolStep) {
if (!sent(t, t.tools.UndoStep(&undone))) {
return false;
}
} else if (!blocked) {
if (!succeeded(t.editor.Undo(&t.view, nullptr)) || !sent(t, t.tools.NotifyEditStateChanged())) {
return false;
}
}
GDK::glsMapPoint now;
GDK::glsMapToolOverlay overlay;
if (!placeAt(t, kSpiceMarketId, now) || !succeeded(t.tools.GetOverlay(&overlay))) {
return false;
}
if (overlay.GetPathCount() < 1) {
return unexpected("expected one tool target");
}
GDK::glsMapPoint target{};
int required = 0;
bool closed = false;
if (!succeeded(overlay.GetPath(0, &target, 1, &required, &closed))) {
return false;
}
if (required < 1) {
return unexpected("expected one tool target");
}
std::printf("[sample] undo: tool step %s, blocks history %s; Spice Market at %.4f %.4f, tool target at %.4f\n",
yesNo(toolStep), yesNo(blocked), now.X, now.Y, target.X);
return (!toolStep && !blocked && std::abs(now.X - kSpiceMarket.X) < 1e-9 &&
std::abs(target.X - kSpiceMarket.X) < 1e-9 &&
messagesSince(t.host, mark, {GDK::glsMapToolMessageKind::MoveTargetsLabel})) ||
unexpected("expected Spice Market back in place");
}
문맥 메뉴
BuildContextMenu(e)는 지금 도구가 포인터 이벤트 e의 자리에서 내놓는 메뉴의 스냅숏을 만듭니다. 항목마다 다음이 있습니다.
| 필드 | 뜻 |
|---|---|
Command |
항목이 하는 일(glsMapToolMenuCommand). Separator는 구분선입니다 |
AppCommand |
Command가 AppCommand일 때 그 응용 프로그램 명령 |
Label |
문구의 종류와 인자(메시지) |
Enabled, DisabledTip |
실행할 수 있는지, 없으면 그 이유의 메시지 종류 |
Values (C# Value0, Value1) |
MeasureCopy의 측정값(길이, 또는 면적과 둘레. 단위는 측정의 규칙대로 미터나 지도 단위) |
Token |
ExecuteMenuItem에 넘길 값 |
사용자가 항목을 고르면 그 Token을 ExecuteMenuItem에 넘깁니다. 가장 최근에 만든 메뉴의 항목만, 한 번만 실행됩니다. 메뉴를 만든 뒤 도구가 바뀌었거나 도구의 내용(스케치의 점, 편집 대상 등)이 바뀌었으면 실행하지 않습니다. 사용할 수 없는 항목과 구분선도 실행하지 않습니다. 실행했는지는 반환값으로 알 수 있습니다. MeasureCopy는 SDK가 실행하지 않는 항목이므로, 응용 프로그램이 Values를 자기 클립보드에 복사합니다.
응용 프로그램 명령. glsMapAppCommand(ZoomToSelection, DeleteSelection, ClearSelection, ZoomToIdentified, OpenInfoPanel, SaveEdits, CancelEdits)는 도구가 응용 프로그램에 맡기는 일입니다. SDK는 상태를 묻고(GetAppCommandState) 실행을 요청할 뿐(InvokeAppCommand) 일 자체는 하지 않습니다. 메뉴와 기본 키에서는 Hidden인 명령을 메뉴에 넣지 않고 실행하지도 않으며, Disabled는 사용할 수 없는 항목으로 넣고, Enabled일 때만 실행합니다. 명령 항목은 실행할 때 상태를 다시 물어 Enabled일 때만 실행합니다. 예외로 ObjectMove는 대상을 불러온 뒤, 대상을 고른 뒤, Escape로 대상을 비울 때 ClearSelection이 Hidden만 아니면(Disabled여도) InvokeAppCommand(ClearSelection)를 부릅니다.
| 모드 | 메뉴 |
|---|---|
Pan |
IdentifyHere |
Info |
IdentifyHere, ZoomToIdentified, OpenInfoPanel 명령 |
측정, SelectPolygon, CreateLine, CreatePolygon |
스케치 중에는 끝내기(점이 모자라면 사용할 수 없음), 마지막 점 지우기, 취소. 측정은 끝낼 수 있으면 MeasureCopy, 끝낸 뒤에는 MeasureClear |
MeasureBearing |
점이 있으면 MeasureClear |
| 선택 도구 | ZoomToSelection, DeleteSelection, ClearSelection 명령. SelectPolygon은 스케치 항목 뒤에 둡니다 |
CreatePoint, CreateText |
CreatePointHere |
ObjectMove |
SaveEdits, CancelEdits 명령 |
VertexEdit |
불러온 대상이 없으면 비어 있음. 꼭짓점 위에서 VertexDelete, 변 위에서 VertexInsert, 그리고 SaveEdits, CancelEdits 명령(앞에 항목이 있으면 그 사이에 Separator) |
IdentifyHere와 CreatePointHere는 이벤트의 WorldValid가 true일 때만 들어갑니다. CreateRect, CreateEllipse의 메뉴는 비어 있습니다.
예제는 Pan 모드에서 메뉴를 만듭니다. 항목은 IdentifyHere 하나(이름표 종류 24)이고, 실행하면 호스트의 IdentifyAt이 한 번 불립니다. 같은 Token을 다시 실행하면 실행되지 않습니다.
glsMapToolMenu를 만들어 넘기면 채워집니다. GetCount()와 GetItem(index, &item)으로 읽습니다. ExecuteMenuItem(token, &executed)의 두 번째 인자가 nullptr이면 InvalidArgument입니다.
// BuildContextMenu returns what the active tool offers at a point. The UI
// shows the items and passes the token of the chosen one to ExecuteMenuItem.
// A menu runs at most one item, and only while the tool and its content are
// unchanged. In Pan mode the menu has IdentifyHere, which calls IdentifyAt.
static bool contextMenu(Tools& t)
{
GDK::glsScreenPoint spice;
const size_t mark = t.host.messages.size();
const int identifies = t.host.identifies;
if (!sent(t, t.tools.SetMode(GDK::glsMapToolMode::Pan)) || !screenOf(t.view, kSpiceMarket, spice)) {
return false;
}
GDK::glsMapToolMenu menu;
if (!sent(t, t.tools.BuildContextMenu(pointer(t.view, spice, kRight, kRight), &menu))) {
return false;
}
GDK::glsMapToolMenuItem item;
if (menu.GetCount() < 1 || !succeeded(menu.GetItem(0, &item))) {
return unexpected("expected a menu item");
}
std::printf("[sample] context menu in Pan: %d item, %s, label kind %d, enabled %s\n", menu.GetCount(),
menuCommandName(item.Command), static_cast<int>(item.Label.Kind), yesNo(item.Enabled));
bool first = false;
bool second = false;
if (!sent(t, t.tools.ExecuteMenuItem(item.Token, &first)) ||
!sent(t, t.tools.ExecuteMenuItem(item.Token, &second))) {
return false;
}
const int requests = t.host.identifies - identifies;
std::printf("[sample] run the item: executed %s, identify requests %d; run it again: executed %s\n",
yesNo(first), requests, yesNo(second));
return (menu.GetCount() == 1 && item.Command == GDK::glsMapToolMenuCommand::IdentifyHere &&
item.Label.Kind == GDK::glsMapToolMessageKind::IdentifyHere && item.Enabled && first && !second &&
requests == 1 && messagesSince(t.host, mark, {})) ||
unexpected("expected one IdentifyHere run");
}
오버레이 그리기
오버레이는 지금 도구가 지도 위에 그려 달라는 것입니다. GetOverlay는 그 순간의 오버레이를 복사해 주며, 복사본은 그 뒤에 바뀌지 않습니다. 도구가 오버레이를 새로 낼 때마다 판(revision) 번호가 올라가고 호스트의 RequestOverlayUpdate가 불립니다. 내용이 같아도 새 판이 날 수 있습니다. 판 번호는 GetOverlayRevision()(C# OverlayRevision)으로 미리 볼 수 있습니다. 도구를 끄거나 바꾸면 오버레이가 비워집니다.
| 내용 | 읽기 | 좌표 |
|---|---|---|
| 모양의 종류 | GetGeometry() (C# Geometry): None, Polyline, Polygon, VertexEdit, DragRect |
|
스케치와 모양의 점 (Polyline, Polygon) |
GetPoints (C# Points). Polygon도 닫는 점은 없습니다 |
지도 좌표 |
| 포인터의 자리 | GetHoverPoint (C# HasHover, Hover). 스케치에 점이 있을 때 포인터가 있는 자리 |
지도 좌표 |
| 스냅한 점과 그 종류 | GetSnapPoint (C# HasSnap, Snap, SnapKind) |
지도 좌표 |
정보 도구의 끌기 사각형 (DragRect) |
GetDragRect (C# HasDragRect, DragA, DragB) |
기기 픽셀 |
편집 대상의 경로와 꼭짓점 손잡이 (VertexEdit) |
GetPath, GetHandle (C# Paths, Handles). 손잡이에는 포인터가 올라 있는지, 골랐는지가 있습니다. ObjectMove는 대상마다 손잡이 하나만 줍니다 |
지도 좌표 |
| 꼭짓점을 넣을 자리 | GetInsertPoint (C# HasInsert, InsertPoint). VertexEdit에서 Control을 누르고 변 위에 있을 때 |
지도 좌표 |
| 이름표 | GetLabel() (C# Label): 메시지 종류와 인자 |
지도 좌표의 내용은 그릴 때마다 지금 뷰의 WorldToScreen으로 화면 좌표로 바꿉니다. 뷰가 바뀌면 판 번호가 그대로여도 오버레이를 다시 그리세요. 이동 도구는 뷰를 옮길 때 판 번호를 올리지 않고 RequestOverlayUpdate를 부릅니다.
예제는 MeasureArea 모드에서 두 점을 찍고 포인터를 세 번째 장소로 옮긴 뒤 오버레이를 읽습니다. 모양은 Polygon, 점 2개, 포인터의 자리 있음, 이름표 SelectAtLeastThreePoints(13)이고, 판 번호가 올라갔으며 RequestOverlayUpdate가 불렸습니다.
glsMapToolOverlay를 만들어 GetOverlay에 넘기면 채워집니다. GetPoints와 GetPath는 필요한 개수를 언제나 알려 주고 준 버퍼 크기까지만 복사합니다(두 번 호출 방식과 같은 모양).
// The overlay is what the UI draws over the map for the active tool: points
// in map coordinates, a hover point, a label. GetOverlay copies it; the copy
// does not change afterwards. RequestOverlayUpdate tells the host that a new
// revision is ready. Here an area measurement has two points and the pointer
// rests on a third spot.
static bool overlaySnapshot(Tools& t)
{
GDK::glsScreenPoint a;
GDK::glsScreenPoint b;
GDK::glsScreenPoint hover;
const size_t mark = t.host.messages.size();
const uint64_t before = t.tools.GetOverlayRevision();
const int updatesBefore = t.host.overlayUpdates;
if (!sent(t, t.tools.SetMode(GDK::glsMapToolMode::MeasureArea)) || !screenOf(t.view, kLighthousePier, a) ||
!screenOf(t.view, kCentralMarket, b) || !screenOf(t.view, kFishDock, hover) || !click(t, a) ||
!click(t, b)) {
return false;
}
bool handled = false;
GDK::glsMapToolOverlay overlay;
if (!sent(t, t.tools.PointerMove(pointer(t.view, hover, 0, 0), &handled)) ||
!succeeded(t.tools.GetOverlay(&overlay))) {
return false;
}
std::vector<GDK::glsMapPoint> points(static_cast<size_t>(overlay.GetPointCount()));
int required = 0;
if (!points.empty() &&
!succeeded(overlay.GetPoints(points.data(), static_cast<int>(points.size()), &required))) {
return false;
}
GDK::glsMapPoint hoverPoint{};
const bool hasHover = overlay.GetHoverPoint(&hoverPoint);
const GDK::glsMapToolMessage label = overlay.GetLabel();
const bool revisionChanged = overlay.GetRevision() > before;
const bool updatesRequested = t.host.overlayUpdates > updatesBefore;
std::printf("[sample] overlay: %s, %d points, hover %s, label kind %d; revision changed %s, updates requested %s\n",
geometryName(overlay.GetGeometry()), required, yesNo(hasHover), static_cast<int>(label.Kind),
yesNo(revisionChanged), yesNo(updatesRequested));
return (overlay.GetGeometry() == GDK::glsMapToolOverlayGeometry::Polygon && required == 2 && hasHover &&
label.Kind == GDK::glsMapToolMessageKind::SelectAtLeastThreePoints && revisionChanged &&
updatesRequested && messagesSince(t.host, mark, {})) ||
unexpected("expected a two-point area sketch");
}
취소와 끄기. 예제는 측정 중에 Cancel(Escape)를 불러 스케치를 지우고(도구는 켜진 채, 점 0개), Deactivate(Switch)로 도구를 끕니다. 끈 뒤 IsActive는 false이고 오버레이는 None입니다.
// Cancel drops the gesture in progress and keeps the tool; Deactivate ends the
// tool, for example when the application's own tool takes over the input.
// The reason tells the tool why.
static bool cancelAndDeactivate(Tools& t)
{
const size_t mark = t.host.messages.size();
GDK::glsMapToolOverlay overlay;
if (!sent(t, t.tools.Cancel(GDK::glsMapToolCancelReason::Escape)) || !succeeded(t.tools.GetOverlay(&overlay))) {
return false;
}
const bool activeAfterCancel = t.tools.IsActive();
const GDK::glsMapToolMode mode = t.tools.GetMode();
const bool toolStep = t.tools.HasUndoableStep();
const int points = overlay.GetPointCount();
std::printf("[sample] after Cancel: active %s, mode %s, %d points, tool step %s\n", yesNo(activeAfterCancel),
modeName(mode), points, yesNo(toolStep));
if (!sent(t, t.tools.Deactivate(GDK::glsMapToolCancelReason::Switch)) ||
!succeeded(t.tools.GetOverlay(&overlay))) {
return false;
}
std::printf("[sample] after Deactivate: active %s, overlay %s\n", yesNo(t.tools.IsActive()),
geometryName(overlay.GetGeometry()));
return (activeAfterCancel && mode == GDK::glsMapToolMode::MeasureArea && points == 0 && !toolStep &&
!t.tools.IsActive() && overlay.GetGeometry() == GDK::glsMapToolOverlayGeometry::None &&
messagesSince(t.host, mark, {})) ||
unexpected("expected the sketch dropped and the tool off");
}
메시지
도구가 보내는 문구는 모두 glsMapToolMessage입니다. 상태 문구(ShowMessage), 오버레이의 이름표, 메뉴 항목의 이름표가 같은 형식을 씁니다.
| 필드 | 뜻 |
|---|---|
Kind |
문구의 종류(glsMapToolMessageKind) |
IntArgs[0..2], RealArgs[0..1] (C# Int0~Int2, Real0, Real1) |
종류에 따른 인자. 예: MeasureDistanceLabel의 길이(단위는 측정의 규칙), MoveTargetsLabel의 대상 수 |
ErrorDomain, ErrorKind, ErrorArg |
OperationFailed일 때 실패한 호출의 오류 상세 |
ErrorDiagnostic |
OperationFailed일 때 영어 진단 문장. 없으면 비어 있습니다 |
각 종류가 어디에 쓰이고 어떤 인자를 갖는지는 헤더 gdk_dll/maptools/glsMapToolMessage.h의 값마다 적혀 있습니다. glsMapToolMessageKind의 값은 고정되어 있으므로(값이 고정된 열거형) 응용 프로그램은 종류 번호로 자기 문구 표를 만드세요. SDK는 문구를 주지 않습니다.
실패. 도구 안에서 편집 컨트롤러나 선택 서비스의 호출이 실패하면 도구는 대개 OperationFailed를 ShowMessage로 보냅니다. 예외도 있습니다. 선택을 가진 레이어가 없으면 VertexEditNeedsSelection, 편집 연결이 없으면 VertexEditNotConnected나 MoveNotConnected를 보내고, ObjectMove가 켜질 때 불러오기에 실패하면 MoveSelectOrClick만 보내며, BeginFeatureGeometryEdit가 거절한 쓰기는 메시지를 보내지 않습니다. ErrorDomain이 Edit이면 ErrorKind는 glsEditErrorKind(10장), Selection이면 glsSelectionErrorKind(9장) 값이므로 그 표로 문구를 만듭니다. 컨트롤러 호출 자체는 이때도 성공을 돌려줍니다.
예제의 호스트는 메시지를 종류 번호로만 출력합니다. 예제에서 오는 메시지는 MoveDragHint(57), FeaturesMoved(64), MoveTargetsLabel(60)입니다.
재진입
호스트 함수는 컨트롤러 호출 안에서 불리므로, 호스트가 그 안에서 컨트롤러를 다시 부를 수 있습니다. 규칙은 다음과 같습니다.
- 모드와 상태를 바꾸는 호출은 미룹니다.
SetMode,Deactivate,Cancel,ViewChanged,NotifyEditStateChanged는 성공을 돌려주지만, 바깥 호출이 돌아가기 직전에 부른 순서대로 실행됩니다. 그래서 호스트 함수 안에서GetMode는 아직 앞의 모드입니다.SetMapView와SetEditBinding은 뷰와 연결을 바로 바꾸고 그에 따른 취소만 미룹니다. - 입력은 거절합니다. 호스트 함수 안에서 넘긴 포인터 입력, 키,
UndoStep은 아무것도 하지 않고 성공과 "처리하지 않음"을 돌려줍니다. 호스트 함수 안에서 대화 상자를 띄우는 동안 들어온 입력이 이렇게 버려집니다. - 메뉴. 호스트 함수 안에서
BuildContextMenu는 빈 메뉴를,ExecuteMenuItem은 실행하지 않음을 돌려줍니다. - 컨트롤러를 없애지 마세요. 호스트 함수 안에서 컨트롤러를 없애면 안 됩니다.
예제의 호스트는 CreateFeature 안에서 SelectPoint를 요청합니다. 호출 안에서 모드는 CreatePoint이고, 바깥의 PointerDown이 돌아온 뒤 SelectPoint가 됩니다(만들기 도구의 예제 코드).
C#에서는 호스트 함수 안에서 MapView를 바꾸거나 SetEditBinding을 부르거나 컨트롤러를 Dispose하면 InvalidOperationException을 던집니다.
수명과 해제
스레드. 컨트롤러는 만든 스레드(보통 UI 스레드)에서만 부릅니다. 호스트 함수도 그 스레드에서 불립니다.
해제 순서. 컨트롤러가 쓰는 객체(호스트, 지도 뷰, 편집 컨트롤러와 세션 상태)는 컨트롤러보다 오래 살아야 합니다. 그렇지 않은 객체는 먼저 연결을 풉니다. 편집을 끝낼 때는 10장처럼 편집 컨트롤러로 저장하거나 취소합니다. 예제는 끝에 편집 연결을 풀고(SetEditBinding(null, null)), CancelEditing으로 편집을 버린 뒤(실패한 실행에서는 Reset), 컨트롤러, 호스트, 선택 서비스, 편집 컨트롤러, 세션 상태, 지도 뷰의 순서로 없앱니다.
컨트롤러는 호스트, 지도 뷰, 편집 객체를 모두 빌립니다. 호스트는 컨트롤러보다 오래 살아야 하고, 지도 뷰와 편집 객체는 컨트롤러보다 오래 살거나 먼저 SetMapView(nullptr), SetEditBinding(nullptr, nullptr)로 풀어야 합니다. 컨트롤러의 소멸자는 호스트를 부르지 않고 도구를 정리합니다. 디버그 구성의 SDK는 만든 스레드가 아닌 곳에서 부른 호출을 대부분 InvalidArgument로 거절합니다. GetMode, IsActive, GetOverlayRevision, HasUndoableStep, BlocksEditHistory는 검사하지 않습니다. 릴리스 구성은 이 검사를 하지 않으므로 스레드 규칙을 지키는 것은 호출하는 쪽의 몫입니다.
다음 장
이 장으로 가이드의 지도 상호작용 부분이 끝납니다. 각 형식과 함수의 자세한 설명은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다.
다음은 12장 래스터, 타일, 고도입니다. 래스터와 타일 데이터를 읽고 지도에 그리는 방법과 래스터의 값을 고도로 읽는 방법을 설명합니다.