1// The Win32 window's file dialogs and drops (PLAN.md, F6b): the2// shell's IFileOpenDialog and IFileSaveDialog, shown modal to the window,3// and an IDropTarget registered with OLE, whose calls queue events the4// window gives the program after them.56import std::string;7import std::vector;8import std::option;9import std::fs;10import std::ffi;1112import window;13import unicode;14import pkg::alloy::com;1516extern RegisterDragDrop(hwnd: c_pointer, target: c_pointer) -> i32;17extern RevokeDragDrop(hwnd: c_pointer) -> i32;18extern ReleaseStgMedium(medium: c_pointer);19extern DragQueryFileW(drop: c_pointer, index: u32, out: c_pointer, length: u32) -> u32;20extern ScreenToClient(hwnd: c_pointer, point: c_pointer) -> i32;21extern PostMessageW(hwnd: c_pointer, message: u32, wparam: u64, lparam: i64) -> i32;22extern GlobalLock(memory: c_pointer) -> c_pointer;23extern GlobalUnlock(memory: c_pointer) -> i32;2425const CLSID_FILE_OPEN_DIALOG: [u8 : 16] = guid(&"dc1c5a9c-e88a-4dde-a5a1-60f82a20aef7");26const CLSID_FILE_SAVE_DIALOG: [u8 : 16] = guid(&"c0b4e2f3-ba21-4773-8dba-335ec946eb8b");27const IID_FILE_OPEN_DIALOG: [u8 : 16] = guid(&"d57c7288-d4ad-4768-be02-9d969532d960");28const IID_FILE_SAVE_DIALOG: [u8 : 16] = guid(&"84bccd23-5fde-4cdb-aea4-af64b83d78ab");29const IID_DROP_TARGET: [u8 : 16] = guid(&"00000122-0000-0000-c000-000000000046");3031// IFileDialog's slots (IFileOpenDialog and IFileSaveDialog share them)32const SHOW: u64 = 3;33const SET_FILE_TYPES: u64 = 4;34const SET_OPTIONS: u64 = 9;35const GET_OPTIONS: u64 = 10;36const SET_FILE_NAME: u64 = 15;37const SET_TITLE: u64 = 17;38const GET_RESULT: u64 = 20;39const SET_DEFAULT_EXTENSION: u64 = 22;40const GET_RESULTS: u64 = 27; // IFileOpenDialog's41const ITEMS_GET_COUNT: u64 = 7; // IShellItemArray's42const ITEMS_GET_ITEM: u64 = 8;43const ITEM_DISPLAY_NAME: u64 = 5; // IShellItem's44const DATA_GET: u64 = 3; // IDataObject's45const DATA_QUERY: u64 = 5;4647type ShowFunction = extern (c_pointer, c_pointer) -> i32;48type ValueFunction = extern (c_pointer, u32) -> i32;49type OutFunction = extern (c_pointer, c_pointer) -> i32;50type TypesFunction = extern (c_pointer, u32, c_pointer) -> i32;51type IndexOutFunction = extern (c_pointer, u32, c_pointer) -> i32;52type NameFunction = extern (c_pointer, u32, c_pointer) -> i32;5354// Shows the dialog modal to the window and gives the files chosen, none55// when cancelled.56pub fn show_dialog(hwnd: c_pointer, asked: &DialogRequest) -> Vector<ChosenFile> {57 var files = Vector<ChosenFile>::empty();58 const made = if (asked.save) create(59 &CLSID_FILE_SAVE_DIALOG,60 &IID_FILE_SAVE_DIALOG61 ) else create(62 &CLSID_FILE_OPEN_DIALOG,63 &IID_FILE_OPEN_DIALOG64 );65 const dialog = if (made is ::Some |d|) d else {66 return move files;67 };68 const d = &asked.dialog;69 var options: u32 = 0;70 method<OutFunction>(dialog, GET_OPTIONS)(dialog, c_pointer::from(&options));71 // FOS_FORCEFILESYSTEM, and FOS_ALLOWMULTISELECT72 options |= 0x40;73 if (d.multiple && !asked.save) {74 options |= 0x200;75 }76 method<ValueFunction>(dialog, SET_OPTIONS)(dialog, options);77 if (d.title.length() > 0) {78 const title = wide(&d.title.view());79 method<OutFunction>(dialog, SET_TITLE)(dialog, c_pointer::of(&title.view()));80 }81 // COMDLG_FILTERSPEC: a name and its patterns joined by ';'82 var texts = Vector<Vector<u16>>::empty();83 for (d.filters.view()) |&filter| {84 texts.push(wide(&filter.name.view()));85 var spec = String::empty();86 for ([..filter.patterns.length()]) |k| {87 if (k != 0) {88 spec.push(';');89 }90 spec.append(&filter.patterns.get(k).view());91 }92 texts.push(wide(&spec.view()));93 }94 if (texts.length() > 0) {95 var specs = Vector<c_pointer>::empty();96 for (texts.view()) |&text| {97 specs.push(c_pointer::of(&text.view()));98 }99 method<TypesFunction>(dialog, SET_FILE_TYPES)(100 dialog,101 (specs.length() / 2) to u32,102 c_pointer::of(&specs.view())103 );104 }105 if (asked.save) {106 if (d.name.length() > 0) {107 const name = wide(&d.name.view());108 method<OutFunction>(dialog, SET_FILE_NAME)(dialog, c_pointer::of(&name.view()));109 }110 // the first filter's first extension added to a name typed without one111 if (d.filters.length() > 0 && d.filters.get(0).patterns.length() > 0) {112 const pattern = &d.filters.get(0).patterns.get(0).view();113 if (pattern.length() > 2 && pattern[..2] == "*.") {114 const extension = wide(&pattern[2..]);115 method<OutFunction>(dialog, SET_DEFAULT_EXTENSION)(116 dialog,117 c_pointer::of(&extension.view())118 );119 }120 }121 }122 if (method<ShowFunction>(dialog, SHOW)(dialog, hwnd) == S_OK) {123 if (asked.save) {124 var item: c_pointer = 0;125 if (method<OutFunction>(dialog, GET_RESULT)(dialog, c_pointer::from(&item)) == S_OK) {126 files.push(chosen(item));127 release(item);128 }129 } else {130 var items: c_pointer = 0;131 if (method<OutFunction>(dialog, GET_RESULTS)(dialog, c_pointer::from(&items)) == S_OK) {132 var count: u32 = 0;133 method<OutFunction>(items, ITEMS_GET_COUNT)(items, c_pointer::from(&count));134 const get_item = method<IndexOutFunction>(items, ITEMS_GET_ITEM);135 for ([..count to u64]) |k| {136 var item: c_pointer = 0;137 if (get_item(items, k to u32, c_pointer::from(&item)) == S_OK) {138 files.push(chosen(item));139 release(item);140 }141 }142 release(items);143 }144 }145 }146 release(dialog);147 return move files;148}149150// A shell item as a file: its path (SIGDN_FILESYSPATH) and name.151fn chosen(item: c_pointer) -> ChosenFile {152 var text: c_pointer = 0;153 method<NameFunction>(item, ITEM_DISPLAY_NAME)(item, 0x80058000, c_pointer::from(&text));154 const path = narrow_c(text, false);155 free_task_memory(text);156 return ChosenFile::at(PathStyle::Windows, &path.view());157}158159/* --- Drops --- */160161// The window's IDropTarget: what the calls give, for the window to162// deliver once each returns (posted as `message`).163pub type DropTarget = struct {164 table: c_pointer,165 count: u32,166 pub hwnd: c_pointer,167 pub message: u32,168 pub events: Vector<Event>,169};170171type DragFunction = extern (c_pointer, c_pointer, u32, Pointl, c_pointer) -> i32;172type OverFunction = extern (c_pointer, u32, Pointl, c_pointer) -> i32;173type LeaveFunction = extern (c_pointer) -> i32;174type QueryFunction = extern (c_pointer, c_pointer, c_pointer) -> i32;175type CountFunction = extern (c_pointer) -> u32;176177type Slots = struct {178 table: [c_pointer : 7],179};180181// POINTL, by value182pub type Pointl = struct {183 pub x: i32,184 pub y: i32,185};186187// Registers a drop target for the window, which `revoke_drops` frees.188pub fn register_drops(hwnd: c_pointer, message: u32) -> c_pointer {189 var slots: *var Slots = new Slots { .table = [0 : 7] };190 const table = &var slots.table;191 const query: QueryFunction = drop_query;192 const add: CountFunction = drop_add;193 const release: CountFunction = drop_release;194 const enter: DragFunction = drag_enter;195 const over: OverFunction = drag_over;196 const leave: LeaveFunction = drag_leave;197 const drop: DragFunction = dropped_on;198 table[0] = query as c_pointer;199 table[1] = add as c_pointer;200 table[2] = release as c_pointer;201 table[3] = enter as c_pointer;202 table[4] = over as c_pointer;203 table[5] = leave as c_pointer;204 table[6] = drop as c_pointer;205 var made: *var DropTarget = new DropTarget {206 .table = c_pointer::keep(move slots),207 .count = 1,208 .hwnd = hwnd,209 .message = message,210 .events = Vector<Event>::empty()211 };212 // the target and its table live until revoke_drops213 const target = c_pointer::keep(move made);214 RegisterDragDrop(hwnd, target);215 return target;216}217218// Takes the window's drop target back from OLE, which releases it, and219// frees it with its table.220pub fn revoke_drops(hwnd: c_pointer, target: c_pointer) {221 RevokeDragDrop(hwnd);222 if (target == 0) {223 return;224 }225 var made = move target.take<DropTarget>();226 var slots = move made.table.take<Slots>();227}228229fn drop_query(this: c_pointer, id: c_pointer, out: c_pointer) -> i32 {230 if (is_guid(id, &IID_UNKNOWN) || is_guid(id, &IID_DROP_TARGET)) {231 this.as_var<DropTarget>().count += 1;232 put(out, this);233 return S_OK;234 }235 put(out, 0);236 return E_NOINTERFACE;237}238239fn drop_add(this: c_pointer) -> u32 {240 const t = &var this.as_var<DropTarget>();241 t.count += 1;242 return t.count;243}244245// The window keeps its reference until `revoke_drops` frees the target.246fn drop_release(this: c_pointer) -> u32 {247 const t = &var this.as_var<DropTarget>();248 t.count -= 1;249 return t.count;250}251252fn queue(self t: &var DropTarget, event: Event) {253 t.events.push(move event);254 PostMessageW(t.hwnd, t.message, 0, 0);255}256257// The point on the screen in the window's client area.258fn client_point(hwnd: c_pointer, at: Pointl) -> Point {259 var point: [i32 : 2] = [at.x, at.y];260 ScreenToClient(hwnd, c_pointer::of(&point[..]));261 return Point { .x = point[0] to f32, .y = point[1] to f32 };262}263264// CF_HDROP and CF_UNICODETEXT in global memory (FORMATETC)265const HDROP: u16 = 15;266const UNICODE_TEXT: u16 = 13;267268type FormatEtc = struct {269 format: u16,270 device: c_pointer,271 aspect: u32,272 index: i32,273 medium: u32,274};275276fn format(kind: u16) -> FormatEtc {277 // DVASPECT_CONTENT, every index, TYMED_HGLOBAL278 return FormatEtc { .format = kind, .device = 0, .aspect = 1, .index = -1, .medium = 1 };279}280281fn has(data: c_pointer, kind: u16) -> bool {282 var f = format(kind);283 return method<OutFunction>(data, DATA_QUERY)(data, c_pointer::from(&f)) == S_OK;284}285286fn drag_enter(this: c_pointer, data: c_pointer, keys: u32, at: Pointl, effect: c_pointer) -> i32 {287 const t = &var this.as_var<DropTarget>();288 const files = has(data, HDROP);289 const text = has(data, UNICODE_TEXT);290 // DROPEFFECT_COPY when it holds what the window takes291 effect.view_var<u32>(1)[0] = if (files || text) 1 else 0;292 t.queue(Event::DragEntered(Dragged {293 .position = client_point(t.hwnd, at),294 .files = files,295 .text = text296 }));297 return S_OK;298}299300fn drag_over(this: c_pointer, keys: u32, at: Pointl, effect: c_pointer) -> i32 {301 const t = &var this.as_var<DropTarget>();302 effect.view_var<u32>(1)[0] = effect.view<u32>(1)[0] & 1;303 t.queue(Event::DragMoved(client_point(t.hwnd, at)));304 return S_OK;305}306307fn drag_leave(this: c_pointer) -> i32 {308 const t = &var this.as_var<DropTarget>();309 t.queue(Event::DragLeft);310 return S_OK;311}312313fn dropped_on(this: c_pointer, data: c_pointer, keys: u32, at: Pointl, effect: c_pointer) -> i32 {314 const t = &var this.as_var<DropTarget>();315 var dropped = Drop {316 .position = client_point(t.hwnd, at),317 .files = Vector<ChosenFile>::empty(),318 .text = ::None319 };320 const get = method<QueryFunction>(data, DATA_GET);321 // STGMEDIUM: its kind, then the global memory322 var medium: [c_pointer : 3] = [0 : 3];323 var f = format(HDROP);324 if (get(data, c_pointer::from(&f), c_pointer::of(&medium[..])) == S_OK) {325 const handle = medium[1];326 const count = DragQueryFileW(handle, 0xFFFFFFFF, 0, 0);327 for ([..count to u64]) |k| {328 const length = DragQueryFileW(handle, k to u32, 0, 0);329 var units: *var [u16] = new [0 to u16 : length to u64 + 1];330 DragQueryFileW(handle, k to u32, c_pointer::of(&units[..]), length + 1);331 const path = narrow(&units[..length to u64], false);332 dropped.files.push(ChosenFile::at(PathStyle::Windows, &path.view()));333 }334 ReleaseStgMedium(c_pointer::of(&medium[..]));335 } else {336 var g = format(UNICODE_TEXT);337 if (get(data, c_pointer::from(&g), c_pointer::of(&medium[..])) == S_OK) {338 const at_text = GlobalLock(medium[1]);339 if (at_text != 0) {340 dropped.text = ::Some(narrow_c(at_text, true));341 GlobalUnlock(medium[1]);342 }343 ReleaseStgMedium(c_pointer::of(&medium[..]));344 }345 }346 effect.view_var<u32>(1)[0] = if (dropped.files.length() > 0 || dropped.text is ::Some) 1 else 0;347 t.queue(Event::Dropped(move dropped));348 return S_OK;349}