OSDN Git Service

[Fix] Windows版のマルチバイト/ワイド文字列変換のメモリリーク修正
[hengbandforosx/hengbandosx.git] / src / main-win / main-win-utils.h
1 #pragma once
2 /*!
3  * @file main-win-utils.h
4  * @brief Windows版固有実装(ユーティリティー)ヘッダ
5  */
6
7 #include "term/z-virt.h"
8
9 #include <windows.h>
10
11 /*!
12  * @brief マルチバイト文字列(CP932)をワイド文字列へ変換するクラス
13  */
14 class to_wchar {
15 public:
16     to_wchar(const char *src)
17         : buf(NULL)
18         , buf_size(0)
19     {
20         if (!src)
21             return;
22
23         int size = ::MultiByteToWideChar(932, 0, src, -1, buf, 0);
24         if (size > 0) {
25             buf_size = size + 1;
26             C_MAKE(buf, buf_size, WCHAR);
27             if (::MultiByteToWideChar(932, 0, src, -1, buf, buf_size) == 0) {
28                 // fail
29                 kill();
30             }
31         }
32     }
33
34     virtual ~to_wchar()
35     {
36         kill();
37     }
38
39     to_wchar(const to_wchar &) = delete;
40     to_wchar &operator=(const to_wchar &) = delete;
41
42     WCHAR *wc_str()
43     {
44         return buf;
45     }
46
47 protected:
48     WCHAR *buf;
49     uint buf_size;
50
51     void kill()
52     {
53         if (buf) {
54             C_KILL(buf, buf_size, WCHAR);
55             buf = NULL;
56         }
57     }
58 };
59
60
61 /*!
62  * @brief ワイド文字列をマルチバイト文字列(CP932)へ変換するクラス
63  */
64 class to_multibyte {
65 public:
66     to_multibyte(const WCHAR *src)
67         : buf(NULL)
68         , buf_size(0)
69     {
70         if (!src)
71             return;
72
73         int size = ::WideCharToMultiByte(932, 0, src, -1, buf, 0, NULL, NULL);
74         if (size > 0) {
75             buf_size = size + 1;
76             C_MAKE(buf, buf_size, char);
77             if (::WideCharToMultiByte(932, 0, src, -1, buf, buf_size, NULL, NULL) == 0) {
78                 // fail
79                 kill();
80             }
81         }
82     }
83
84     virtual ~to_multibyte()
85     {
86         kill();
87     }
88
89     to_multibyte(const to_multibyte &) = delete;
90     char* &operator=(const char* &) = delete;
91
92     char *c_str()
93     {
94         return buf;
95     }
96
97 protected:
98     char *buf;
99     uint buf_size;
100
101     void kill()
102     {
103         if (buf) {
104             C_KILL(buf, buf_size, char);
105             buf = NULL;
106         }
107     }
108 };
109
110 bool is_already_running(void);
111 void save_screen_as_html(HWND hWnd);
112 void open_dir_in_explorer(char* filename);
113 bool get_open_filename(OPENFILENAMEW *ofn, concptr dirname, char *filename, DWORD max_name_size);