/
EncodingView.mm
326 lines (276 loc) · 10.7 KB
/
EncodingView.mm
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
#import "EncodingView.h"
#import <OakFoundation/NSString Additions.h>
#import <OakAppKit/OakEncodingPopUpButton.h>
#import <OakAppKit/OakUIConstructionFunctions.h>
#import <text/hexdump.h>
#import <text/utf8.h>
#import <text/transcode.h>
#import <oak/oak.h>
#import <oak/debug.h>
#import <ns/ns.h>
template <typename _InputIter>
size_t newline_size (_InputIter first, _InputIter const& last)
{
for(auto str : { "\r\n", "\n", "\r" })
{
if(oak::has_prefix(first, last, str, str + strlen(str)))
return strlen(str);
}
return 0;
}
static void append (NSMutableAttributedString* dst, char const* first, char const* last, NSDictionary* styles)
{
NSString* str = [NSString stringWithUTF8String:first length:last - first] ?: @"\uFFFD";
[dst appendAttributedString:[[NSAttributedString alloc] initWithString:str attributes:styles]];
}
static NSAttributedString* convert_and_highlight (char const* first, char const* last, std::string const& encodeFrom = "UTF-8", std::string const& encodeTo = "UTF-8", bool* success = nullptr)
{
std::set<ptrdiff_t> offsets;
auto lastPos = first;
for(auto it = first; it != last; ++it)
{
if(*it > 0x7F)
{
if(++lastPos != it)
offsets.insert(std::distance(first, it));
lastPos = it;
}
}
text::transcode_t transcode(encodeFrom, encodeTo);
if(!transcode)
return nil;
std::string dst;
std::set<size_t> decodedOffsets;
size_t from = 0;
for(size_t to : offsets)
{
transcode(first + from, first + to, back_inserter(dst));
decodedOffsets.insert(dst.size());
from = to;
}
transcode(transcode(first + from, last, back_inserter(dst)));
if(success)
*success = transcode.invalid_count() == 0;
NSMutableAttributedString* output = [[NSMutableAttributedString alloc] init];
NSDictionary* regularStyle = @{
NSFontAttributeName : [NSFont userFixedPitchFontOfSize:0],
NSForegroundColorAttributeName : [NSColor grayColor],
};
NSDictionary* lineHighlightStyle = @{
NSFontAttributeName : [NSFont userFixedPitchFontOfSize:0],
NSForegroundColorAttributeName : [NSColor grayColor],
NSBackgroundColorAttributeName : [NSColor colorWithCalibratedWhite:0.9 alpha:1],
};
NSDictionary* characterHighlightStyle = @{
NSFontAttributeName : [NSFont userFixedPitchFontOfSize:0],
NSBackgroundColorAttributeName : [NSColor colorWithCalibratedWhite:0.9 alpha:1],
};
size_t bol = 0;
auto offset = decodedOffsets.begin();
for(size_t eol = 0; eol < dst.size(); ++eol)
{
static std::string const newlines[] = { "\r\n", "\n", "\r" };
auto it = std::find_if(std::begin(newlines), std::end(newlines), [&](std::string const& str){ return oak::has_prefix(dst.begin() + eol, dst.end(), str.begin(), str.end()); });
if(it == std::end(newlines))
continue;
size_t crlf = it->size();
if(offset != decodedOffsets.end() && *offset < eol)
{
while(offset != decodedOffsets.end() && *offset < eol)
{
if(*offset < bol)
{
++offset;
continue;
}
append(output, dst.data() + bol, dst.data() + *offset, lineHighlightStyle);
bol = *offset;
while(bol != dst.size() && dst[bol] > 0x7F)
++bol;
append(output, dst.data() + *offset, dst.data() + bol, characterHighlightStyle);
++offset;
}
append(output, dst.data() + bol, dst.data() + eol + crlf, lineHighlightStyle);
}
else
{
append(output, dst.data() + bol, dst.data() + eol + crlf, regularStyle);
}
bol = eol + crlf;
eol += crlf - 1;
}
if(bol < dst.size())
append(output, dst.data() + bol, dst.data() + dst.size(), regularStyle);
return output;
}
static NSTextView* MyCreateTextView ()
{
NSTextView* res = [[NSTextView alloc] initWithFrame:NSZeroRect];
[res setVerticallyResizable:YES];
[res setHorizontallyResizable:YES];
[res setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
[[res textContainer] setWidthTracksTextView:NO];
[[res textContainer] setContainerSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX)];
return res;
}
@interface EncodingContentView : NSView
{
OBJC_WATCH_LEAKS(EncodingContentView);
}
@property (nonatomic) id delegate;
@end
@implementation EncodingContentView
- (NSSize)intrinsicContentSize
{
return NSMakeSize(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric);
}
- (void)updateConstraints
{
[super updateConstraints];
[self.delegate updateConstraints];
}
@end
@interface EncodingWindowController () <NSWindowDelegate, NSTextViewDelegate>
{
OBJC_WATCH_LEAKS(EncodingWindowController);
char const* first;
char const* last;
}
@property (nonatomic) NSObjectController* objectController;
@property (nonatomic) NSTextField* title;
@property (nonatomic) NSTextField* explanation;
@property (nonatomic) NSTextField* label;
@property (nonatomic) OakEncodingPopUpButton* popUpButton;
@property (nonatomic) NSScrollView* scrollView;
@property (nonatomic) NSTextView* textView;
@property (nonatomic) NSButton* learnCheckBox;
@property (nonatomic) NSButton* openButton;
@property (nonatomic) NSButton* cancelButton;
@property (nonatomic) EncodingContentView* contentView;
@property (nonatomic) NSMutableArray* myConstraints;
@end
@implementation EncodingWindowController
- (id)initWithFirst:(char const*)firstPointer last:(char const*)lastPointer
{
if(self = [super initWithWindow:[[NSWindow alloc] initWithContentRect:NSZeroRect styleMask:(NSTitledWindowMask|NSClosableWindowMask|NSResizableWindowMask|NSMiniaturizableWindowMask) backing:NSBackingStoreBuffered defer:NO]])
{
first = firstPointer;
last = std::min(firstPointer + 256*1024, lastPointer);
_encoding = @"ISO-8859-1";
_displayName = @"untitled";
_trainClassifier = YES;
self.objectController = [[NSObjectController alloc] initWithContent:self];
self.title = OakCreateLabel(@"Unknown Encoding", [NSFont boldSystemFontOfSize:0]);
self.explanation = OakCreateLabel();
self.label = OakCreateLabel(@"Encoding:");
self.popUpButton = [[OakEncodingPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];
self.scrollView = [[NSScrollView alloc] initWithFrame:NSZeroRect];
self.textView = MyCreateTextView();
self.learnCheckBox = OakCreateCheckBox(@"Use document for training encoding classifier");
self.openButton = OakCreateButton(@"Open");
self.cancelButton = OakCreateButton(@"Cancel");
[self.label setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
[self.popUpButton setContentHuggingPriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
self.scrollView.hasVerticalScroller = YES;
self.scrollView.hasHorizontalScroller = YES;
self.scrollView.borderType = NSBezelBorder;
self.scrollView.documentView = self.textView;
self.textView.editable = NO;
self.textView.delegate = self;
self.openButton.action = @selector(performOpenDocument:);
self.cancelButton.action = @selector(performCancelOperation:);
self.cancelButton.keyEquivalent = @"\e";
EncodingContentView* contentView = [[EncodingContentView alloc] initWithFrame:NSZeroRect];
[contentView setDelegate:self];
[contentView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
self.contentView = contentView;
OakAddAutoLayoutViewsToSuperview([[self allViews] allValues], contentView);
[self.window.contentView addSubview:contentView];
self.window.defaultButtonCell = self.openButton.cell;
self.window.delegate = self;
[self.popUpButton bind:@"encoding" toObject:_objectController withKeyPath:@"content.encoding" options:nil];
[self.learnCheckBox bind:NSValueBinding toObject:_objectController withKeyPath:@"content.trainClassifier" options:nil];
[self.openButton bind:NSEnabledBinding toObject:_objectController withKeyPath:@"content.acceptableEncoding" options:nil];
[self updateTextView];
}
return self;
}
- (void)beginSheetModalForWindow:(NSWindow*)aWindow completionHandler:(void(^)(NSModalResponse))callback
{
[self.window layoutIfNeeded];
[aWindow beginSheet:self.window completionHandler:callback];
}
- (BOOL)textView:(NSTextView*)aTextView doCommandBySelector:(SEL)aSelector
{
BOOL res = aSelector == @selector(insertNewline:) && !aTextView.editable && self.window.defaultButtonCell;
if(res)
[self.window.defaultButtonCell performClick:self];
return res;
}
- (NSDictionary*)allViews
{
return @{
@"title" : self.title,
@"explanation" : self.explanation,
@"label" : self.label,
@"popUp" : self.popUpButton,
@"textView" : self.scrollView,
@"learn" : self.learnCheckBox,
@"open" : self.openButton,
@"cancel" : self.cancelButton
};
}
#ifndef CONSTRAINT
#define CONSTRAINT(str, align) [_myConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:str options:align metrics:nil views:views]]
#endif
- (void)updateConstraints
{
if(_myConstraints)
[self.contentView removeConstraints:_myConstraints];
_myConstraints = [NSMutableArray array];
NSDictionary* views = [self allViews];
CONSTRAINT(@"H:|-[title]-|", NSLayoutFormatAlignAllBaseline);
CONSTRAINT(@"H:|-[explanation]-|", NSLayoutFormatAlignAllBaseline);
CONSTRAINT(@"H:|-[label]-[popUp]-|", NSLayoutFormatAlignAllBaseline);
CONSTRAINT(@"H:|-[textView(>=100)]-|", 0);
CONSTRAINT(@"H:|-[learn]-|", 0);
CONSTRAINT(@"H:[cancel]-[open]-|", NSLayoutFormatAlignAllBaseline);
CONSTRAINT(@"V:|-[title]-[explanation]-[popUp]-[textView(>=100)]-[learn]-[open]-|", NSLayoutFormatAlignAllRight);
[self.contentView addConstraints:_myConstraints];
}
- (void)setDisplayName:(NSString*)aString
{
_displayName = aString;
self.explanation.stringValue = [NSString stringWithFormat:@"The file “%@” contains characters with unknown encoding.\nPlease select the encoding which should be used to open the file.\nThe contents of the file is shown below with the relevant lines highlighted.\nBefore proceeding, check that the chosen encoding makes the preview look correct.", _displayName];
}
- (void)updateTextView
{
bool couldConvert = true;
[[self.textView textStorage] setAttributedString:convert_and_highlight(first, last, to_s(self.encoding), "UTF-8", &couldConvert)];
self.acceptableEncoding = couldConvert;
}
- (void)setEncoding:(NSString*)anEncoding
{
if([_encoding isEqualToString:anEncoding])
return;
_encoding = anEncoding;
[self updateTextView];
}
- (void)cleanup
{
self.contentView.delegate = nil;
self.objectController.content = nil;
}
- (IBAction)performOpenDocument:(id)sender
{
[self.window orderOut:self];
[self.window.sheetParent endSheet:self.window returnCode:NSModalResponseOK];
[self cleanup];
}
- (IBAction)performCancelOperation:(id)sender
{
[self.window orderOut:self];
[self.window.sheetParent endSheet:self.window returnCode:NSModalResponseCancel];
[self cleanup];
}
@end