clipboard-rs 0.3.5

Cross-platform clipboard API (text | image | rich text | html | files | monitoring changes) | 跨平台剪贴板 API(文本|图片|富文本|html|文件|监听变化) Windows,MacOS,Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
use std::collections::HashMap;
use std::io::Cursor;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{mem, ptr};

use crate::common::{ContentData, Result};
#[cfg(feature = "image")]
use crate::common::{RustImage, RustImageData};
use crate::{Clipboard, ClipboardContent, ClipboardHandler, ClipboardWatcher, ContentFormat};
use clipboard_win::raw::{set_file_list_with, set_string_with, set_without_clear};
use clipboard_win::types::c_uint;
use clipboard_win::{
	formats, get, get_clipboard, options, raw, set_clipboard, Clipboard as ClipboardWin, Monitor,
	SysResult,
};
#[cfg(feature = "image")]
use image::codecs::bmp::BmpDecoder;
#[cfg(feature = "image")]
use image::DynamicImage;
use windows::Win32::Foundation::{HANDLE, HWND};
use windows::Win32::Graphics::Gdi::{
	CreateDIBitmap, DeleteObject, GetDC, ReleaseDC, BITMAPFILEHEADER, BITMAPINFO, BITMAPINFOHEADER,
	BITMAPV5HEADER, CBM_INIT, DIB_RGB_COLORS, HDC, HGDIOBJ,
};
use windows::Win32::System::DataExchange::SetClipboardData;

pub struct WatcherShutdown {
	state: Arc<Mutex<ShutdownState>>,
}

static UNKNOWN_FORMAT: &str = "unknown format";
static CF_RTF: &str = "Rich Text Format";
static CF_HTML: &str = "HTML Format";
static CF_PNG: &str = "PNG";

pub struct ClipboardContext {
	format_map: HashMap<&'static str, c_uint>,
	html_format: formats::Html,
}

/// Shared shutdown state between a [`WatcherShutdown`] handle and the running
/// watch loop.
///
/// The `clipboard_win` [`Monitor`] (and thus its `Shutdown`) must be created on
/// the thread that runs `start_watch`, but `get_shutdown_channel` is typically
/// called earlier on another thread. This state bridges that gap and is guarded
/// by a mutex so the handoff is race-free: storing the live `Shutdown` and
/// observing a pre-start stop request both happen under the same lock.
enum ShutdownState {
	/// Watch loop has not published its `Shutdown` yet.
	NotStarted,
	/// Watch loop is running; dropping this `Shutdown` interrupts `recv`.
	Running(clipboard_win::monitor::Shutdown),
	/// Stop was requested before the watch loop published its `Shutdown`.
	StopRequested,
}

pub struct ClipboardWatcherContext<T: ClipboardHandler> {
	handlers: Vec<T>,
	state: Arc<Mutex<ShutdownState>>,
	running: bool,
}

unsafe impl Send for ClipboardContext {}
unsafe impl Sync for ClipboardContext {}
unsafe impl<T: ClipboardHandler> Send for ClipboardWatcherContext<T> {}
unsafe impl<T: ClipboardHandler> Sync for ClipboardWatcherContext<T> {}

impl ClipboardContext {
	pub fn new() -> Result<ClipboardContext> {
		let (format_map, html_format) = {
			let cf_html_format = formats::Html::new();
			let cf_rtf_uint = clipboard_win::register_format(CF_RTF);
			let cf_png_uint = clipboard_win::register_format(CF_PNG);
			let mut m: HashMap<&str, c_uint> = HashMap::new();
			if let Some(cf_html) = cf_html_format {
				m.insert(CF_HTML, cf_html.code());
			}
			if let Some(cf_rtf) = cf_rtf_uint {
				m.insert(CF_RTF, cf_rtf.get());
			}
			if let Some(cf_png) = cf_png_uint {
				m.insert(CF_PNG, cf_png.get());
			}
			(m, cf_html_format)
		};
		Ok(ClipboardContext {
			format_map,
			html_format: html_format.ok_or("register html format error")?,
		})
	}

	fn get_format(&self, format: &ContentFormat) -> c_uint {
		match format {
			ContentFormat::Text => formats::CF_UNICODETEXT,
			ContentFormat::Rtf => *self.format_map.get(CF_RTF).unwrap(),
			ContentFormat::Html => *self.format_map.get(CF_HTML).unwrap(),
			#[cfg(feature = "image")]
			ContentFormat::Image => formats::CF_DIB,
			ContentFormat::Files => formats::CF_HDROP,
			ContentFormat::Other(format) => clipboard_win::register_format(format).unwrap().get(),
		}
	}
}

impl<T: ClipboardHandler> ClipboardWatcherContext<T> {
	pub fn new() -> Result<Self> {
		Ok(Self {
			handlers: Vec::new(),
			state: Arc::new(Mutex::new(ShutdownState::NotStarted)),
			running: false,
		})
	}

	/// Creates a watcher. Provided for cross-platform API symmetry with the
	/// macOS backend; `_interval` is ignored on Windows because changes are
	/// delivered by the OS via `WM_CLIPBOARDUPDATE` rather than polled.
	pub fn new_with_interval(_interval: Duration) -> Result<Self> {
		Self::new()
	}
}

impl Clipboard for ClipboardContext {
	fn available_formats(&self) -> Result<Vec<String>> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let format_count = clipboard_win::count_formats();
		if format_count.is_none() {
			return Ok(Vec::new());
		}
		let mut res = Vec::new();
		let enum_formats = clipboard_win::raw::EnumFormats::new();
		enum_formats.into_iter().for_each(|format| {
			let f_name = raw::format_name_big(format);
			match f_name {
				Some(name) => res.push(name),
				None => {
					res.push(UNKNOWN_FORMAT.to_string());
				}
			}
		});
		Ok(res)
	}

	fn has(&self, format: ContentFormat) -> bool {
		match format {
			ContentFormat::Text => clipboard_win::is_format_avail(formats::CF_UNICODETEXT),
			ContentFormat::Rtf => {
				let cf_rtf_uint = self.format_map.get(CF_RTF).unwrap();
				clipboard_win::is_format_avail(*cf_rtf_uint)
			}
			ContentFormat::Html => {
				let cf_html_uint = self.format_map.get(CF_HTML).unwrap();
				clipboard_win::is_format_avail(*cf_html_uint)
			}
			#[cfg(feature = "image")]
			ContentFormat::Image => {
				// Currently only judge whether there is a png format
				let cf_png_uint = self.format_map.get(CF_PNG).unwrap();
				clipboard_win::is_format_avail(*cf_png_uint)
					|| clipboard_win::is_format_avail(formats::CF_DIB)
			}
			ContentFormat::Files => clipboard_win::is_format_avail(formats::CF_HDROP),
			ContentFormat::Other(format) => {
				let format_uint = clipboard_win::register_format(format.as_str());
				if let Some(format_uint) = format_uint {
					return clipboard_win::is_format_avail(format_uint.get());
				}
				false
			}
		}
	}

	fn clear(&self) -> Result<()> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let res = clipboard_win::empty();
		if let Err(e) = res {
			return Err(format!("Empty clipboard error, code = {e}").into());
		}
		Ok(())
	}

	fn get_buffer(&self, format: &str) -> Result<Vec<u8>> {
		let format_uint = clipboard_win::register_format(format);
		if format_uint.is_none() {
			return Err("register format error".into());
		}
		let format_uint = format_uint.unwrap().get();
		let buffer = get_clipboard(formats::RawData(format_uint));
		match buffer {
			Ok(data) => Ok(data),
			Err(e) => Err(format!("Get buffer error, code = {e}").into()),
		}
	}

	fn get_text(&self) -> Result<String> {
		let string: SysResult<String> = get_clipboard(formats::Unicode);
		match string {
			Ok(s) => Ok(s),
			Err(e) => Err(format!("Get text error, code = {e}").into()),
		}
	}

	fn get_rich_text(&self) -> Result<String> {
		let rtf_raw_data = self.get_buffer(CF_RTF)?;
		Ok(String::from_utf8_lossy(&rtf_raw_data).to_string())
	}

	fn get_html(&self) -> Result<String> {
		let buffer = get_clipboard(formats::RawData(self.html_format.code()));
		match buffer {
			Ok(data) => {
				let html_res = String::from_utf8(data);
				if let Ok(html_full_str) = html_res {
					let html = extract_html_from_clipboard_data(html_full_str.as_str());
					if let Ok(html) = html {
						return Ok(html);
					}
				}
				Err("Get html error".into())
			}
			Err(e) => Err(format!("Get buffer error, code = {e}").into()),
		}
	}

	#[cfg(feature = "image")]
	fn get_image(&self) -> Result<RustImageData> {
		let cf_png_format = self.format_map.get(CF_PNG);
		if cf_png_format.is_some() && clipboard_win::is_format_avail(*cf_png_format.unwrap()) {
			let image_raw_data = self.get_buffer(CF_PNG)?;
			RustImageData::from_bytes(&image_raw_data)
		} else if clipboard_win::is_format_avail(formats::CF_DIBV5) {
			let res = get_clipboard(formats::RawData(formats::CF_DIBV5));
			match res {
				Ok(data) => {
					let decoder = {
						// if data.as_slice().starts_with(b"BM") {
						// 	BmpDecoder::new(Cursor::new(data.as_slice()))
						// } else {
						BmpDecoder::new_without_file_header(Cursor::new(data.as_slice()))
						// }
					};
					let decoder = decoder.map_err(|e| format!("{e}"))?;
					let dynamic_image =
						DynamicImage::from_decoder(decoder).map_err(|e| format!("{e}"))?;
					Ok(RustImageData::from_dynamic_image(dynamic_image))
				}
				Err(e) => Err(format!("Get image error, code = {e}").into()),
			}
		} else if clipboard_win::is_format_avail(formats::CF_DIB) {
			let res = get_clipboard(formats::Bitmap);
			match res {
				Ok(data) => RustImageData::from_bytes(&data),
				Err(e) => Err(format!("Get image error, code = {e}").into()),
			}
		} else {
			Err("No image data in clipboard".into())
		}
	}

	fn get_files(&self) -> Result<Vec<String>> {
		let files: SysResult<Vec<String>> = get_clipboard(formats::FileList);
		match files {
			Ok(f) => Ok(f),
			Err(e) => Err(format!("Get files error, code = {e}").into()),
		}
	}

	fn get(&self, formats: &[ContentFormat]) -> Result<Vec<ClipboardContent>> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let mut res = Vec::new();
		for format in formats {
			match format {
				ContentFormat::Text => {
					let r = get(formats::Unicode);
					match r {
						Ok(txt) => {
							res.push(ClipboardContent::Text(txt));
						}
						Err(_) => continue,
					}
				}
				ContentFormat::Rtf => {
					let format_uint = self.get_format(format);
					let buffer = get(formats::RawData(format_uint));
					match buffer {
						Ok(buffer) => {
							let rtf = String::from_utf8_lossy(&buffer);
							res.push(ClipboardContent::Rtf(rtf.to_string()));
						}
						Err(_) => continue,
					}
				}
				ContentFormat::Html => {
					let html_buffer = get(formats::RawData(self.html_format.code()));
					match html_buffer {
						Ok(html) => {
							let html_res = String::from_utf8(html);
							if let Ok(html_full_str) = html_res {
								let html = extract_html_from_clipboard_data(html_full_str.as_str());
								if let Ok(html) = html {
									res.push(ClipboardContent::Html(html));
								}
							}
						}
						Err(_) => continue,
					}
				}
				#[cfg(feature = "image")]
				ContentFormat::Image => {
					let img = self.get_image();
					match img {
						Ok(img) => {
							res.push(ClipboardContent::Image(img));
						}
						Err(_) => continue,
					}
				}
				ContentFormat::Other(fmt) => {
					let format_uint = self.get_format(format);
					let buffer = get(formats::RawData(format_uint));
					match buffer {
						Ok(buffer) => {
							res.push(ClipboardContent::Other(fmt.clone(), buffer));
						}
						Err(_) => continue,
					}
				}
				ContentFormat::Files => {
					let files = self.get_files();
					match files {
						Ok(files) => {
							res.push(ClipboardContent::Files(files));
						}
						Err(_) => continue,
					}
				}
			}
		}
		Ok(res)
	}

	fn set_buffer(&self, format: &str, buffer: Vec<u8>) -> Result<()> {
		let format_uint = clipboard_win::register_format(format);
		if format_uint.is_none() {
			return Err("register format error".into());
		}
		let format_uint = format_uint.unwrap().get();
		let res = set_clipboard(formats::RawData(format_uint), buffer);
		if res.is_err() {
			return Err("set buffer error".into());
		}
		Ok(())
	}

	fn set_text(&self, text: String) -> Result<()> {
		let res = set_clipboard(formats::Unicode, text);
		res.map_err(|e| format!("set text error, code = {e}").into())
	}

	fn set_rich_text(&self, text: String) -> Result<()> {
		let res = self.set_buffer(CF_RTF, text.as_bytes().to_vec());
		res.map_err(|e| format!("set rich text error, code = {e}").into())
	}

	fn set_html(&self, html: String) -> Result<()> {
		let cf_html = plain_html_to_cf_html(&html);
		let res = set_clipboard(
			formats::RawData(self.html_format.code()),
			cf_html.as_bytes(),
		);
		res.map_err(|e| format!("set html error, code = {e}").into())
	}

	#[cfg(feature = "image")]
	fn set_image(&self, image: RustImageData) -> Result<()> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let res = clipboard_win::empty();
		if let Err(e) = res {
			return Err(format!("Empty clipboard error, code = {e}").into());
		}
		// chromium source code
		// @link {https://source.chromium.org/chromium/chromium/src/+/main:ui/base/clipboard/clipboard_win.cc;l=771;drc=2a5aaed0ff3a0895c8551495c2656ed49baf742c;bpv=0;bpt=1}
		let cf_png_format = self.format_map.get(CF_PNG);
		if let Some(cf_png) = cf_png_format {
			let png = image.to_png()?;
			if let Err(e) = set_without_clear(*cf_png, png.get_bytes()) {
				eprintln!("set png image error, code = {e}");
				// continue set bmp image
			}
		}
		// 转换为 BMP 并设置到剪贴板
		let bmp = image
			.to_bitmap()
			.map_err(|e| format!("transform to bitmap error, code = {e}"))?;

		set_bitmap_inner(bmp.get_bytes()).map_err(|e| format!("set image error, code = {e}").into())
	}

	fn set_files(&self, files: Vec<String>) -> Result<()> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let res = set_file_list_with(&files, options::DoClear);
		res.map_err(|e| format!("set files error, code = {e}").into())
	}

	fn set(&self, contents: Vec<ClipboardContent>) -> Result<()> {
		let _clip = ClipboardWin::new_attempts(10)
			.map_err(|code| format!("Open clipboard error, code = {code}"));
		let res = clipboard_win::empty();
		if let Err(e) = res {
			return Err(format!("Empty clipboard error, code = {e}").into());
		}
		for content in contents {
			match content {
				ClipboardContent::Text(txt) => {
					let res = set_string_with(txt.as_str(), options::NoClear);
					if res.is_err() {
						continue;
					}
				}
				ClipboardContent::Html(html) => {
					let format_uint_html = self.html_format.code();
					let cf_html = plain_html_to_cf_html(&html);
					let res = set_without_clear(format_uint_html, cf_html.as_bytes());
					if res.is_err() {
						continue;
					}
				}
				#[cfg(feature = "image")]
				ClipboardContent::Image(img) => {
					// set image will clear clipboard
					let res = self.set_image(img);
					if res.is_err() {
						continue;
					}
				}
				ClipboardContent::Rtf(_) | ClipboardContent::Other(_, _) => {
					let format_uint = self.get_format(&content.get_format());
					let res = set_without_clear(format_uint, content.as_bytes());
					if res.is_err() {
						continue;
					}
				}
				ClipboardContent::Files(file_list) => {
					let res = set_file_list_with(&file_list, options::NoClear);
					if res.is_err() {
						continue;
					}
				}
			}
		}
		Ok(())
	}
}

impl<T: ClipboardHandler> ClipboardWatcher<T> for ClipboardWatcherContext<T> {
	fn add_handler(&mut self, f: T) -> &mut Self {
		self.handlers.push(f);
		self
	}

	fn start_watch(&mut self) {
		if self.running {
			println!("already start watch!");
			return;
		}
		if self.handlers.is_empty() {
			println!("no handler, no need to start watch!");
			return;
		}
		self.running = true;
		let mut monitor = Monitor::new().expect("create monitor error");

		// Publish the live Shutdown so a WatcherShutdown can interrupt `recv`.
		// If stop was already requested before we got here, bail out at once.
		{
			let mut state = self.state.lock().unwrap();
			if matches!(*state, ShutdownState::StopRequested) {
				self.running = false;
				return;
			}
			*state = ShutdownState::Running(monitor.shutdown_channel());
		}

		loop {
			match monitor.recv() {
				// New clipboard update.
				Ok(true) => {
					self.handlers.iter_mut().for_each(|f| {
						f.on_clipboard_change();
					});
				}
				// Shutdown requested (Shutdown handle dropped).
				Ok(false) => break,
				Err(e) => {
					eprintln!("watch error, code = {e}");
					break;
				}
			}
		}
		*self.state.lock().unwrap() = ShutdownState::NotStarted;
		self.running = false;
	}

	fn get_shutdown_channel(&self) -> WatcherShutdown {
		WatcherShutdown {
			state: self.state.clone(),
		}
	}
}

impl Drop for WatcherShutdown {
	fn drop(&mut self) {
		// Take the current state, marking a stop request, then act on what we
		// took after releasing the lock.
		let taken = {
			let mut state = self.state.lock().unwrap();
			std::mem::replace(&mut *state, ShutdownState::StopRequested)
		};
		match taken {
			// Loop is blocked in `recv`; dropping its Shutdown interrupts it.
			ShutdownState::Running(shutdown) => drop(shutdown),
			// Loop has not started (or already stopped): StopRequested, written
			// above, makes it bail out before entering `recv`.
			ShutdownState::NotStarted | ShutdownState::StopRequested => {}
		}
	}
}

// 将输入的 UTF-8 字符串转换为宽字符(UTF-16)字符串
// fn utf8_to_utf16(input: &str) -> Vec<u16> {
// 	let mut vec: Vec<u16> = input.encode_utf16().collect();
// 	vec.push(0);
// 	vec
// }

// https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format
// The description header includes the clipboard version number and offsets, indicating where the context and the fragment start and end. The description is a list of ASCII text keywords followed by a string and separated by a colon (:).
// Version: vv version number of the clipboard. Starting version is . As of Windows 10 20H2 this is now .Version:0.9Version:1.0
// StartHTML: Offset (in bytes) from the beginning of the clipboard to the start of the context, or if no context.-1
// EndHTML: Offset (in bytes) from the beginning of the clipboard to the end of the context, or if no context.-1
// StartFragment: Offset (in bytes) from the beginning of the clipboard to the start of the fragment.
// EndFragment: Offset (in bytes) from the beginning of the clipboard to the end of the fragment.
// StartSelection: Optional. Offset (in bytes) from the beginning of the clipboard to the start of the selection.
// EndSelection: Optional. Offset (in bytes) from the beginning of the clipboard to the end of the selection.
// The and keywords are optional and must both be omitted if you do not want the application to generate this information.StartSelectionEndSelection
// Future revisions of the clipboard format may extend the header, for example, since the HTML starts at the offset then multiple and pairs could be added later to support noncontiguous selection of fragments.CF_HTMLStartHTMLStartFragmentEndFragment
// example:
// html=Version:1.0
// StartHTML:000000096
// EndHTML:000000375
// StartFragment:000000096
// EndFragment:000000375
// <html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><div style="background-color:#2b2b2b;color:#a9b7c6;font-family:'JetBrains Mono',monospace;font-size:9.8pt;"><pre><span style="color:#9876aa;">sellChannel</span></pre></div></body></html>
// cp from https://github.com/Devolutions/IronRDP/blob/37aa6426dba3272f38a2bb46a513144a326854ee/crates/ironrdp-cliprdr-format/src/html.rs#L91
fn plain_html_to_cf_html(fragment: &str) -> String {
	const POS_PLACEHOLDER: &str = "0000000000";

	let mut buffer = String::new();

	let mut write_header = |key: &str, value: &str| {
		let size = key.len() + value.len() + ":\r\n".len();
		buffer.reserve(size);

		buffer.push_str(key);
		buffer.push(':');
		let value_pos = buffer.len();
		buffer.push_str(value);
		buffer.push_str("\r\n");

		value_pos
	};

	write_header("Version", "0.9");

	let start_html_header_value_pos = write_header("StartHTML", POS_PLACEHOLDER);
	let end_html_header_value_pos = write_header("EndHTML", POS_PLACEHOLDER);
	let start_fragment_header_value_pos = write_header("StartFragment", POS_PLACEHOLDER);
	let end_fragment_header_value_pos = write_header("EndFragment", POS_PLACEHOLDER);

	let start_html_pos = buffer.len();
	if !fragment.starts_with("<html>") {
		buffer.push_str("<html>\r\n<body>\r\n<!--StartFragment-->");
	}

	let start_fragment_pos = buffer.len();
	buffer.push_str(fragment);

	let end_fragment_pos = buffer.len();
	if !fragment.ends_with("</html>") {
		buffer.push_str("<!--EndFragment-->\r\n</body>\r\n</html>");
	}

	let end_html_pos = buffer.len();

	let start_html_pos_value = format!("{start_html_pos:0>10}");
	let end_html_pos_value = format!("{end_html_pos:0>10}");
	let start_fragment_pos_value = format!("{start_fragment_pos:0>10}");
	let end_fragment_pos_value = format!("{end_fragment_pos:0>10}");

	let mut replace_placeholder = |value_begin_idx: usize, header_value: &str| {
		let value_end_idx = value_begin_idx + POS_PLACEHOLDER.len();
		buffer.replace_range(value_begin_idx..value_end_idx, header_value);
	};

	replace_placeholder(start_html_header_value_pos, &start_html_pos_value);
	replace_placeholder(end_html_header_value_pos, &end_html_pos_value);
	replace_placeholder(start_fragment_header_value_pos, &start_fragment_pos_value);
	replace_placeholder(end_fragment_header_value_pos, &end_fragment_pos_value);

	buffer
}

const SEP: char = ':';
const START_HTML: &str = "StartHTML";
const END_HTML: &str = "EndHTML";

fn extract_html_from_clipboard_data(data: &str) -> Result<String> {
	let mut start_idx = 0usize;
	let mut end_idx = data.len();
	for line in data.lines() {
		let mut split = line.split(SEP);
		let key = match split.next() {
			Some(key) => key,
			None => break,
		};
		let value = match split.next() {
			Some(value) => value,
			//Reached HTML
			None => break,
		};
		match key {
			START_HTML => match value.trim_start_matches('0').parse() {
				Ok(value) => {
					start_idx = value;
					continue;
				}
				//Should not really happen
				Err(_) => break,
			},
			END_HTML => match value.trim_start_matches('0').parse() {
				Ok(value) => {
					end_idx = value;
					continue;
				}
				//Should not really happen
				Err(_) => break,
			},
			_ => continue,
		}
	}
	//Make sure HTML writer didn't screw up offsets of fragment
	// Check that start_idx is within bounds
	if start_idx > data.len() {
		return Err("Invalid HTML offsets: start index exceeds data length".into());
	}
	// Check that end_idx is within bounds
	if end_idx > data.len() {
		return Err("Invalid HTML offsets: end index exceeds data length".into());
	}
	// Check that end_idx >= start_idx
	if end_idx < start_idx {
		return Err("Invalid HTML offsets: end index before start index".into());
	}
	Ok(data[start_idx..end_idx].to_string())
}

fn set_bitmap_inner(data: &[u8]) -> Result<()> {
	const FILE_HEADER_LEN: usize = mem::size_of::<BITMAPFILEHEADER>();
	const INFO_HEADER_LEN: usize = mem::size_of::<BITMAPV5HEADER>();

	if data.len() <= (FILE_HEADER_LEN + INFO_HEADER_LEN) {
		return Err("Invalid bitmap data".into());
	}

	let mut file_header = mem::MaybeUninit::<BITMAPFILEHEADER>::uninit();
	let mut info_header = mem::MaybeUninit::<BITMAPV5HEADER>::uninit();

	let (file_header, info_header) = unsafe {
		ptr::copy_nonoverlapping(
			data.as_ptr(),
			file_header.as_mut_ptr() as _,
			FILE_HEADER_LEN,
		);
		ptr::copy_nonoverlapping(
			data.as_ptr().add(FILE_HEADER_LEN),
			info_header.as_mut_ptr() as _,
			INFO_HEADER_LEN,
		);
		(file_header.assume_init(), info_header.assume_init())
	};

	if data.len() <= file_header.bfOffBits as usize {
		return Err("Invalid bitmap data".into());
	}

	let bitmap = &data[file_header.bfOffBits as _..];

	if bitmap.len() < info_header.bV5SizeImage as usize {
		return Err("Invalid bitmap data".into());
	}

	let dc = DeviceContext::new()?;

	let handle = unsafe {
		CreateDIBitmap(
			dc.0,
			Some(&info_header as *const _ as *const BITMAPINFOHEADER),
			CBM_INIT as u32,
			Some(bitmap.as_ptr() as _),
			Some(&info_header as *const _ as *const BITMAPINFO),
			DIB_RGB_COLORS,
		)
	};

	if handle.is_invalid() {
		return Err("Failed to create DIB".into());
	}

	if let Err(err) = unsafe { SetClipboardData(formats::CF_BITMAP, Some(HANDLE(handle.0))) } {
		let _ = unsafe { DeleteObject(HGDIOBJ(handle.0)) };
		Err(err.into())
	} else {
		Ok(())
	}
}

struct DeviceContext(HDC);

impl DeviceContext {
	fn new() -> Result<Self> {
		let dc = unsafe { GetDC(Some(HWND::default())) };
		if dc.is_invalid() {
			return Err("Failed to get DC".into());
		}
		Ok(Self(dc))
	}
}

impl Drop for DeviceContext {
	fn drop(&mut self) {
		unsafe { ReleaseDC(Some(HWND::default()), self.0) };
	}
}