-
Notifications
You must be signed in to change notification settings - Fork 4
/
FBDoc.cpp
1915 lines (1626 loc) · 97.7 KB
/
FBDoc.cpp
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Doc.cpp: implementation of the Doc class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include "res1.h"
#include "utils.h"
#include "apputils.h"
#include "FBDoc.h"
#include "Scintilla.h"
#include "Settings.h"
#include "ElementDescMnr.h"
extern CElementDescMnr _EDMnr;
extern CSettings _Settings;
namespace FB {
// namespaces
const _bstr_t FBNS(L"http://www.gribuser.ru/xml/fictionbook/2.0");
const _bstr_t XLINKNS(L"http://www.w3.org/1999/xlink");
const _bstr_t NEWLINE(L"\n");
// document list
CSimpleMap<Doc*,Doc*> Doc::m_active_docs;
Doc* FB::Doc::m_active_doc;
bool FB::Doc::m_fast_mode;
Doc *Doc::LocateDocument(const wchar_t *id) {
unsigned long *lv;
if (swscanf(id,L"%lu",&lv)!=1)
return NULL;
return m_active_docs.Lookup((Doc*)lv);
}
// initialize a new Doc
Doc::Doc(HWND hWndFrame) :
m_filename(_T("Untitled.fb2")), m_namevalid(false),
// m_desc(hWndFrame,false),
m_body(hWndFrame, true),
m_frame(hWndFrame),
// m_desc_ver(-1),
m_body_ver(-1),
// m_desc_cp(-1),
m_body_cp(-1),
m_encoding(_T("utf-8"))
{
m_active_docs.Add(this,this);
}
// destroy a Doc
Doc::~Doc() {
// destroy windows explicitly
// if (m_desc.IsWindow())
// m_desc.DestroyWindow();
if (m_body.IsWindow())
m_body.DestroyWindow();
m_active_docs.Remove(this);
}
bool Doc::GetBinary(const wchar_t *id,_variant_t& vt) {
if (id && *id==L'#') {
CComDispatchDriver body(m_body.Script());
_variant_t vid(id+1);
body.Invoke1(L"apiGetBinary",&vid,&vt);
return true;
}
return false;
}
struct ThreadArgs {
MSXML2::IXSLProcessor *proc;
HANDLE hWr;
};
static DWORD __stdcall XMLTransformThread(LPVOID varg) {
ThreadArgs *arg=(ThreadArgs*)varg;
arg->proc->put_output(_variant_t(U::NewStream(arg->hWr)));
VARIANT_BOOL val;
arg->proc->raw_transform(&val);
arg->proc->Release();
delete arg;
return 0;
}
void Doc::TransformXML(MSXML2::IXSLTemplatePtr tp,MSXML2::IXMLDOMDocument2Ptr doc,
CFBEView& dest)
{
// create processor
MSXML2::IXSLProcessorPtr proc(tp->createProcessor());
proc->input=_variant_t(doc.GetInterfacePtr());
// add parameters
CString fss(_Settings.GetFont());
if (!fss.IsEmpty())
proc->addParameter(L"font",(const wchar_t *)fss,_bstr_t());
DWORD fs = _Settings.GetFontSize();
if (fs>1) {
fss.Format(_T("%d"),fs);
proc->addParameter(L"fontSize",(const wchar_t *)fss,_bstr_t());
}
fs = _Settings.GetColorFG();
if (fs!=CLR_DEFAULT) {
fss.Format(_T("rgb(%d,%d,%d)"),GetRValue(fs),GetGValue(fs),GetBValue(fs));
proc->addParameter(L"colorFG",(const wchar_t *)fss,_bstr_t());
}
fs = _Settings.GetColorBG();
if (fs!=CLR_DEFAULT) {
fss.Format(_T("rgb(%d,%d,%d)"),GetRValue(fs),GetGValue(fs),GetBValue(fs));
proc->addParameter(L"colorBG",(const wchar_t *)fss,_bstr_t());
}
fs=::GetSysColor(COLOR_BTNFACE);
fss.Format(_T("rgb(%d,%d,%d)"),GetRValue(fs),GetGValue(fs),GetBValue(fs));
proc->addParameter(L"dlgBG",(const wchar_t *)fss,_bstr_t());
fs=::GetSysColor(COLOR_BTNTEXT);
fss.Format(_T("rgb(%d,%d,%d)"),GetRValue(fs),GetGValue(fs),GetBValue(fs));
proc->addParameter(L"dlgFG",(const wchar_t *)fss,_bstr_t());
proc->addParameter(L"dID",(const wchar_t *)MyID(),_bstr_t());
// add jscript paths
proc->addParameter(L"bodyscript",(const wchar_t *)U::UrlFromPath(U::GetProgDirFile(_T("body.js"))),_bstr_t());
proc->addParameter(L"descscript",(const wchar_t *)U::UrlFromPath(U::GetProgDirFile(_T("desc.js"))),_bstr_t());
ThreadArgs *arg=new ThreadArgs;
// pass the processor to worker thread, this is a dirty hack, but we know that
// MSXML survives it, otherwise we'd have to jump through the hoops with
// COM MTAs, because if we just marshal the pointer to worker thread, then
// we'll deadlock in load. To do everything cleanly, we'd need to create the
// XSL processor and XML documents in an MTA, and run the transforms there,
// all this is rather awkward. Another alternative is to transform all XML
// to memory and the load from it
arg->proc=proc.Detach();
// setup the streams
HANDLE hRd;
::CreatePipe(&hRd,&arg->hWr,NULL,0);
// start the processor
::CloseHandle(::CreateThread(NULL,0,XMLTransformThread,arg,0,NULL));
// now stuff the data into mshtml
IPersistStreamInitPtr ips(dest.Browser()->Document);
ips->InitNew();
ips->Load(U::NewStream(hRd));
}
static MSXML2::IXSLTemplatePtr LoadXSL(const CString& path) {
MSXML2::IXMLDOMDocument2Ptr xsl(U::CreateDocument(true));
if (!U::LoadXml(xsl,U::GetProgDirFile(path)))
throw _com_error(E_FAIL);
MSXML2::IXSLTemplatePtr tp(U::CreateTemplate());
tp->stylesheet=xsl;
return tp;
}
// loading
/*bool Doc::LoadFromDOM(HWND hWndParent,MSXML2::IXMLDOMDocument2 *dom) {
try {
dom->setProperty(L"SelectionLanguage",L"XPath");
CString nsprop(L"xmlns:fb='");
nsprop+=(const wchar_t *)FBNS;
nsprop+=L"' xmlns:xlink='";
nsprop+=(const wchar_t *)XLINKNS;
nsprop+=L"'";
dom->setProperty(L"SelectionNamespaces",(const TCHAR *)nsprop);
// try to find out current encoding
MSXML2::IXMLDOMProcessingInstructionPtr pi(dom->firstChild);
if (pi) {
MSXML2::IXMLDOMNamedNodeMapPtr attr(pi->attributes);
if (attr) {
MSXML2::IXMLDOMNodePtr enc(attr->getNamedItem(L"encoding"));
if (enc)
m_encoding=(const wchar_t *)enc->text;
}
}
// create desc view
m_desc.Create(hWndParent, CRect(0,0,500,500), _T("{8856F961-340A-11D0-A96B-00C04FD705A2}"));
// navigate to blank page
m_desc.Browser()->Navigate(L"about:blank");
// run a message loop until it loads
MSG msg;
while (!m_desc.Loaded() && ::GetMessage(&msg,NULL,0,0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
// transform to html
TransformXML(LoadXSL(_T("description.xsl")),dom,m_desc);
// wait until it loads
while (!m_desc.Loaded() && ::GetMessage(&msg,NULL,0,0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
// initialize view
m_desc.Init();
// store binaries
CComDispatchDriver desc(m_desc.Script());
_variant_t arg(dom);
desc.Invoke1(L"PutBinaries",&arg);
// create body view
m_body.Create(hWndParent, CRect(0,0,500,500), _T("{8856F961-340A-11D0-A96B-00C04FD705A2}"));
// navigate body browser
m_body.Browser()->Navigate(L"about:blank");
// wait until it loads
while (!m_body.Loaded() && ::GetMessage(&msg,NULL,0,0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
// transform to html
TransformXML(LoadXSL(_T("body.xsl")),dom,m_body);
// wait until it loads
while (!m_body.Loaded() && ::GetMessage(&msg,NULL,0,0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
// initialize view
m_body.Init();
// mark unchanged
MarkSavePoint();
// ok, now setup filename and return
m_filename=_T("Untitled");
m_namevalid=false;
}
catch (_com_error& e) {
U::ReportError(e);
return false;
}
return true;
}*/
HRESULT Doc::InvokeFunc(BSTR FuncName, CComVariant *params, int count, CComVariant &vtResult)
{
LPDISPATCH pScript;
IHTMLDocument2Ptr doc = m_body.Browser()->Document;
doc->get_Script(&pScript);
pScript->AddRef();
BSTR szMember = FuncName;
DISPID dispid;
HRESULT hr = pScript->GetIDsOfNames(IID_NULL, &szMember, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
if (SUCCEEDED(hr))
{
CComDispatchDriver dispDriver(pScript);
hr = dispDriver.InvokeN(dispid, params , count, &vtResult);
}
return hr;
}
void Doc::ShowDescription(bool Show)
{
CComVariant vtResult;
CComVariant params;
V_VT(¶ms) = VT_BOOL;
V_BOOL(¶ms) = Show;
InvokeFunc(L"apiShowDesc", ¶ms, 1, vtResult);
return;
}
void Doc::RunScript(BSTR filePath)
{
CComVariant vtResult;
CComVariant params(filePath);
InvokeFunc(L"apiRunCmd", ¶ms, 1, vtResult);
}
VARIANT_BOOL Doc::CheckScript(BSTR filePath)
{
CComVariant vtResult;
CComVariant params(filePath);
InvokeFunc(L"apiCheckScript", ¶ms, 1, vtResult);
return vtResult.boolVal;
}
bool Doc::LoadFromHTML(HWND hWndParent,const CString& filename)
{
HRESULT hr;
wchar_t path[MAX_PATH + 1];
GetModuleFileName(0, path, MAX_PATH);
PathRemoveFileSpec(path);
wcscat(path, L"\\main.html");
m_body.Create(hWndParent, CRect(0,0,500,500), _T("{8856F961-340A-11D0-A96B-00C04FD705A2}"));
hr = m_body.Browser()->Navigate(path);
MSG msg;
while (!m_body.Loaded() && ::GetMessage(&msg,NULL,0,0))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
m_body.SetExternalDispatch(m_body.CreateHelper());
m_body.Init();
//FastMode();
CComVariant params[2];
params[1] = filename;
params[0] = _Settings.GetInterfaceLanguageName();
CComVariant res;
ApplyConfChanges();
hr = InvokeFunc(L"apiLoadFB2", params, 2, res);
//m_body.Normalize(m_body.Document()->body);
// mark unchanged
MarkSavePoint();
if(res.vt == VT_BOOL)
{
m_encoding = _Settings.GetDefaultEncoding();
return res.boolVal != VARIANT_FALSE;
}
if(res.vt == VT_BSTR)
{
m_encoding = res.bstrVal;
return true;
}
if(res.vt == VT_EMPTY)
{
m_encoding = _Settings.GetDefaultEncoding();
return true;
}
return false;
}
bool Doc::Load(HWND hWndParent,const CString& filename) {
try {
// AU::CPersistentWaitCursor wc;
// load document into DOM
/*MSXML2::IXMLDOMDocument2Ptr dom(U::CreateDocument(true));
if (!U::LoadXml(dom,filename))
return false;
if (!LoadFromDOM(hWndParent,dom))
return false;*/
CWaitCursor *hourglass = new CWaitCursor();
if(!LoadFromHTML(hWndParent, filename))
{
return false;
}
m_filename = filename;
m_namevalid = true;
}
catch (_com_error& e) {
U::ReportError(e);
return false;
}
return true;
}
void Doc::CreateBlank(HWND hWndParent) {
try {
// load document into DOM
LoadFromHTML(hWndParent, L"blank.fb2");
//LoadFromDOM(hWndParent,U::CreateDocument(true));
}
catch (_com_error& e) {
U::ReportError(e);
}
}
// indent something
static void Indent(MSXML2::IXMLDOMNode *node, MSXML2::IXMLDOMDocument2 *xml, int len)
{
// inefficient
BSTR s = SysAllocStringLen(NULL,len+2);
if(s)
{
s[0] = L'\r';
s[1] = L'\n';
for(BSTR p = s + 2, q = s + 2 + len; p < q; ++p)
*p = L' ';
MSXML2::IXMLDOMTextPtr text;
if(SUCCEEDED(xml->raw_createTextNode(s, &text)))
node->raw_appendChild(text, NULL);
SysFreeString(s);
}
}
// set an attribute on the element
static void SetAttr(MSXML2::IXMLDOMElement *xe,const wchar_t *name,
const wchar_t *ns,const _bstr_t& val,
MSXML2::IXMLDOMDocument2 *doc)
{
MSXML2::IXMLDOMAttributePtr attr(doc->createNode(2L,name,ns));
attr->appendChild(doc->createTextNode(val));
xe->setAttributeNode(attr);
}
// setup an ID for the element
static void SetID(MSHTML::IHTMLElement *he,MSXML2::IXMLDOMElement *xe,
MSXML2::IXMLDOMDocument2 *doc) {
_bstr_t id(he->id);
if (id.length()>0)
SetAttr(xe,L"id",FBNS,id,doc);
}
// copy text
static MSXML2::IXMLDOMTextPtr MkText(MSHTML::IHTMLDOMNode *hn,MSXML2::IXMLDOMDocument2 *xml)
{
VARIANT vt;
VariantInit(&vt);
CheckError(hn->get_nodeValue(&vt));
if (V_VT(&vt)!=VT_BSTR) {
VariantClear(&vt);
return xml->createTextNode(_bstr_t());
}
MSXML2::IXMLDOMText *txt;
HRESULT hr=xml->raw_createTextNode(V_BSTR(&vt),&txt);
VariantClear(&vt);
CheckError(hr);
return MSXML2::IXMLDOMTextPtr(txt,FALSE);
}
// set an href attribute
static void SetHref(MSXML2::IXMLDOMElementPtr xe,MSXML2::IXMLDOMDocument2 *xml,
const _bstr_t& href)
{
SetAttr(xe,L"l:href",XLINKNS,href,xml);
}
static void SetTitle(MSXML2::IXMLDOMElementPtr xe,MSXML2::IXMLDOMDocument2 *xml,
const _bstr_t& title)
{
if(!title)
{
return;
}
SetAttr(xe,L"title",FB::FBNS,title,xml);
}
// handle inline formatting
static MSXML2::IXMLDOMNodePtr ProcessInline(MSHTML::IHTMLDOMNode *inl,
MSXML2::IXMLDOMDocument2 *doc)
{
// Source
_bstr_t name(inl->nodeName);
MSHTML::IHTMLElementPtr einl(inl);
_bstr_t cls(einl->className);
const wchar_t *xname=NULL;
bool fA=false;
bool fStyle=false;
bool fUnk = false;
bool fImg = false;
// Modification by Pilgrim
if (U::scmp(name,L"STRONG")==0)
xname=L"strong";
else if (U::scmp(name,L"EM")==0)
xname=L"emphasis";
else if (U::scmp(name,L"STRIKE")==0)
xname=L"strikethrough";
else if (U::scmp(name,L"SUB")==0)
xname=L"sub";
else if (U::scmp(name,L"SUP")==0)
xname=L"sup";
else if (U::scmp(name,L"A")==0) {
xname=L"a"; fA=true;
} else if (U::scmp(name,L"SPAN")==0)
{
if(U::scmp(cls,L"unknown_element")==0)
{
_bstr_t realClassName = einl->getAttribute(L"source_class", 2);
xname = realClassName;
fUnk = true;
}
else if (U::scmp(cls,L"image")==0)
{
fImg=true;
xname=L"image";
}
else if (U::scmp(cls,L"code")==0)
xname=L"code";
else
{
xname=L"style"; fStyle=true;
}
}
MSXML2::IXMLDOMElementPtr xinl(doc->createNode(1L,xname,FBNS));
if (fImg)
SetHref(xinl,doc,AU::GetAttrB(einl,L"href"));
if (fA) {
SetHref(xinl,doc,AU::GetAttrB(einl,L"href"));
if (U::scmp(cls,L"note")==0)
SetAttr(xinl,L"type",FBNS,cls,doc);
}
if (fStyle)
SetAttr(xinl,L"name",FBNS,cls,doc);
if (fUnk)
{
MSHTML::IHTMLAttributeCollectionPtr col = inl->attributes;
for(int i = 0; i < col->length; ++i)
{
VARIANT index;
V_VT(&index) = VT_INT;
index.intVal = i;
_bstr_t attr_name = MSHTML::IHTMLDOMAttributePtr(col->item(&index))->nodeName;
_bstr_t attr_value;
wchar_t* real_attr_name = 0;
const wchar_t* prefix = L"unknown_attribute_";
if(wcsncmp(attr_name, prefix, wcslen(prefix)))
{
continue;
}
else
{
real_attr_name = (wchar_t*)attr_name + wcslen(prefix);
attr_value = MSHTML::IHTMLDOMAttributePtr(col->item(&index))->nodeValue;
}
MSXML2::IXMLDOMAttributePtr attr(doc->createNode(2L,real_attr_name,FBNS));
attr->appendChild(doc->createTextNode(attr_value));
xinl->setAttributeNode(attr);
}
}
MSHTML::IHTMLDOMNodePtr cn(inl->firstChild);
// Modification by Pilgrim
while ((bool)cn) {
if (cn->nodeType==NODE_TEXT/*3*/)
xinl->appendChild(MkText(cn,doc));
else if ((cn->nodeType==NODE_ELEMENT/*1*/) && (!fImg)) // added by SeNS
xinl->appendChild(ProcessInline(cn,doc));
cn=cn->nextSibling;
}
return xinl;
}
// handle a paragraph element with subelements
static MSXML2::IXMLDOMNodePtr ProcessP(MSHTML::IHTMLElement *p,
MSXML2::IXMLDOMDocument2 *doc,
const wchar_t *baseName)
{
_bstr_t cls(p->className);
if (U::scmp(cls,L"text-author")==0)
baseName=L"text-author";
else if (U::scmp(cls,L"subtitle")==0)
baseName=L"subtitle";
// Modification by Pilgrim
else if (U::scmp(cls,L"th")==0)
baseName=L"th";
else if (U::scmp(cls,L"td")==0)
baseName=L"td";
MSHTML::IHTMLDOMNodePtr hp(p);
// check if it is an empty-line
if(U::scmp(cls, L"td") && U::scmp(cls, L"th"))
{
if (hp->hasChildNodes()==VARIANT_FALSE ||
(!(bool)hp->firstChild->nextSibling && hp->firstChild->nodeType==3 &&
U::is_whitespace(hp->firstChild->nodeValue.bstrVal)))
{
MSHTML::IHTMLElementPtr pParent = MSHTML::IHTMLElementPtr(p)->parentElement;
if (MSHTML::IHTMLElement3Ptr(p)->inflateBlock == VARIANT_TRUE)
{
if(pParent && U::scmp(pParent->className, L"stanza") == 0)
{
MSXML2::IXMLDOMNodePtr vNode = doc->createNode(NODE_ELEMENT, L"v", FBNS);
vNode->appendChild(doc->createTextNode(L" "));
return vNode;
}
else
return doc->createNode(1L, L"empty-line", FBNS);
}
return MSXML2::IXMLDOMNodePtr();
}
}
MSXML2::IXMLDOMElementPtr xp(doc->createNode(1L,baseName,FBNS));
SetID(p,xp,doc);
_bstr_t style(AU::GetAttrB(p,L"fbstyle"));
if (style.length()>0)
SetAttr(xp,L"style",FBNS,style,doc);
// Modification by Pilgrim
_bstr_t colspan(AU::GetAttrB(p,L"fbcolspan"));
if (colspan.length()>0)
SetAttr(xp,L"colspan",FBNS,colspan,doc);
_bstr_t rowspan(AU::GetAttrB(p,L"fbrowspan"));
if (rowspan.length()>0)
SetAttr(xp,L"rowspan",FBNS,rowspan,doc);
_bstr_t align(AU::GetAttrB(p,L"fbalign"));
if (align.length()>0)
SetAttr(xp,L"align",FBNS,align,doc);
_bstr_t valign(AU::GetAttrB(p,L"fbvalign"));
if (valign.length()>0)
SetAttr(xp,L"valign",FBNS,valign,doc);
hp=hp->firstChild;
// Modification by Pilgrim
while ((bool)hp) {
if (hp->nodeType==NODE_TEXT/*3*/) // text segment
xp->appendChild(MkText(hp,doc));
else if (hp->nodeType==NODE_ELEMENT/*1*/)
xp->appendChild(ProcessInline(hp,doc));
hp=hp->nextSibling;
}
_bstr_t selected (AU::GetAttrB(p,L"fbe_selected"));
if (selected.length()>0)
SetAttr(xp,L"selected",FBNS,selected,doc);
return xp;
}
// handle a div element with subelements
static MSXML2::IXMLDOMNodePtr ProcessDiv(MSHTML::IHTMLElement *div,
MSXML2::IXMLDOMDocument2 *doc,
int indent)
{
_bstr_t cls(div->className);
MSXML2::IXMLDOMElementPtr xdiv(doc->createNode(1L,cls,FBNS));
if (U::scmp(cls,L"image")==0) {
SetID(div,xdiv,doc);
SetHref(xdiv,doc,AU::GetAttrB(div,L"href"));
SetTitle(xdiv,doc,AU::GetAttrB(div,L"title"));
return xdiv;
}
SetID(div,xdiv,doc);
// Modification by Pilgrim
if (U::scmp(cls,L"table")==0) {
_bstr_t style(AU::GetAttrB(div,L"fbstyle"));
if (style.length()>0){
SetAttr(xdiv,L"style",FBNS,style,doc);
}
}
if (U::scmp(cls,L"tr")==0) {
_bstr_t align(AU::GetAttrB(div,L"fbalign"));
if (align.length()>0){
SetAttr(xdiv,L"align",FBNS,align,doc);
}
}
MSHTML::IHTMLDOMNodePtr ndiv(div);
MSHTML::IHTMLDOMNodePtr fc(ndiv->firstChild);
const wchar_t *bn=U::scmp(cls,L"stanza")==0 ? L"v" : L"p";
while ((bool)fc) {
_bstr_t name(fc->nodeName);
MSHTML::IHTMLElementPtr efc(fc);
// process empty lines
MSHTML::IHTMLElement3Ptr(efc)->inflateBlock = VARIANT_TRUE;
if (U::scmp(name,L"DIV")==0) {
Indent(xdiv,doc,indent+1);
MSXML2::IXMLDOMNodePtr nnp = ProcessDiv(efc,doc,indent+1);
xdiv->appendChild(nnp);
} else if (U::scmp(name,L"P")==0) {
MSXML2::IXMLDOMNodePtr np;
try { np = ProcessP(efc,doc,bn); } catch (...) { np = 0; }
if (np) {
Indent(xdiv,doc,indent+1);
xdiv->appendChild(np);
}
}
fc=fc->nextSibling;
}
Indent(xdiv,doc,indent);
return xdiv;
}
// find a first named DIV
static MSXML2::IXMLDOMNodePtr GetDiv(MSHTML::IHTMLElementPtr body,
MSXML2::IXMLDOMDocument2 *xml,
const wchar_t *name,
int indent)
{
MSHTML::IHTMLElementCollectionPtr children(body->children);
long c_len=children->length;
for (long i=0;i<c_len;++i) {
MSHTML::IHTMLElementPtr div(children->item(i));
if (!(bool)div)
continue;
if (U::scmp(div->tagName,L"DIV")==0 && U::scmp(div->className,name)==0)
return ProcessDiv(div,xml,indent);
}
return MSXML2::IXMLDOMNodePtr();
}
// fetch bodies
static void GetBodies(MSHTML::IHTMLElementPtr body,
MSXML2::IXMLDOMDocument2 *doc)
{
MSHTML::IHTMLElementCollectionPtr children(body->children);
long c_len=children->length;
for (long i=0;i<c_len;++i) {
MSHTML::IHTMLElementPtr div(children->item(i));
if (!(bool)div)
continue;
if (U::scmp(div->tagName,L"DIV")==0 && U::scmp(div->className,L"body")==0)
{
MSXML2::IXMLDOMElementPtr xb(ProcessDiv(div,doc,1));
_bstr_t bn(AU::GetAttrB(div,L"fbname"));
if (bn.length()>0)
SetAttr(xb,L"name",FBNS,bn,doc);
Indent(doc->documentElement,doc,1);
doc->documentElement->appendChild(xb);
}
}
}
// validator object
class SAXErrorHandler: public CComObjectRoot, public MSXML2::ISAXErrorHandler {
public:
CString m_msg;
int m_line,m_col;
SAXErrorHandler() : m_line(0),m_col(0) { }
void SetMsg(MSXML2::ISAXLocator *loc, const wchar_t *msg, HRESULT hr) {
if (!m_msg.IsEmpty())
return;
m_msg=msg;
CString ns;
ns.Format(_T("{%s}"),(const TCHAR *)FBNS);
m_msg.Replace(ns,_T(""));
ns.Format(_T("{%s}"),(const TCHAR *)XLINKNS);
m_msg.Replace(ns,_T("xlink"));
m_line=loc->getLineNumber();
m_col=loc->getColumnNumber();
}
BEGIN_COM_MAP(SAXErrorHandler)
COM_INTERFACE_ENTRY(MSXML2::ISAXErrorHandler)
END_COM_MAP()
STDMETHOD(raw_error)(MSXML2::ISAXLocator *loc, wchar_t *msg, HRESULT hr) {
SetMsg(loc,msg,hr);
return E_FAIL;
}
STDMETHOD(raw_fatalError)(MSXML2::ISAXLocator *loc, wchar_t *msg, HRESULT hr) {
SetMsg(loc,msg,hr);
return E_FAIL;
}
STDMETHOD(raw_ignorableWarning)(MSXML2::ISAXLocator *loc, wchar_t *msg, HRESULT hr) {
SetMsg(loc,msg,hr);
return E_FAIL;
}
};
MSXML2::IXMLDOMDocument2Ptr Doc::CreateDOMImp(const CString& encoding) {
// normalize body first
_EDMnr.CleanUpAll();
m_body.Normalize(m_body.Document()->body);
// create document
MSXML2::IXMLDOMDocument2Ptr ndoc(U::CreateDocument(false));
ndoc->async=VARIANT_FALSE;
// set encoding
if (!encoding.IsEmpty())
ndoc->appendChild(ndoc->createProcessingInstruction(L"xml",(const wchar_t *)(L"version=\"1.0\" encoding=\""+encoding+L"\"")));
// create document element
MSXML2::IXMLDOMElementPtr root=ndoc->createNode(_variant_t(1L),L"FictionBook",FBNS);
root->setAttribute(L"xmlns:l",XLINKNS);
ndoc->documentElement=MSXML2::IXMLDOMElementPtr(root);
// enable xpath queries
ndoc->setProperty(L"SelectionLanguage",L"XPath");
CString nsprop(L"xmlns:fb='");
nsprop+=(const wchar_t *)FBNS;
nsprop+=L"' xmlns:xlink='";
nsprop+=(const wchar_t *)XLINKNS;
nsprop+=L"'";
ndoc->setProperty(L"SelectionNamespaces",(const TCHAR *)nsprop);
// fetch annotation
MSHTML::IHTMLElementCollectionPtr children(m_body.Document()->body->children);
long c_len = children->length;
MSHTML::IHTMLElementPtr fbw_body;
for (long i=0;i<c_len;++i) {
MSHTML::IHTMLElementPtr div(children->item(i));
if (!(bool)div)
continue;
if (U::scmp(div->tagName,L"DIV")==0 && U::scmp(div->id,L"fbw_body")==0)
{
fbw_body = div;
break;
}
}
MSXML2::IXMLDOMNodePtr ann(GetDiv(fbw_body,ndoc,L"annotation",3));
// fetch history
MSXML2::IXMLDOMNodePtr hist(GetDiv(fbw_body,ndoc,L"history",3));
// fetch description
CComDispatchDriver body(m_body.Script());
CComVariant args[3];
if (hist)
args[0]=hist.GetInterfacePtr();
if (ann)
args[1]=ann.GetInterfacePtr();
args[2]=ndoc.GetInterfacePtr();
CComVariant res;
CheckError(body.InvokeN(L"GetDesc",&args[0],3));
// fetch body elements
GetBodies(fbw_body,ndoc);
// fetch binaries
CheckError(body.Invoke1(L"GetBinaries",&args[2]));
Indent(root,ndoc,0);
return ndoc;
}
MSXML2::IXMLDOMDocument2Ptr Doc::CreateDOM(const CString& encoding)
{
try
{
return CreateDOMImp(encoding);
}
catch (_com_error& e)
{
U::ReportError(e);
}
return NULL;
}
bool Doc::SaveToFile(const CString& filename,bool fValidateOnly,
int *errline,int *errcol)
{
try {
// create a schema collection
MSXML2::IXMLDOMSchemaCollection2Ptr scol;
CheckError(scol.CreateInstance(L"Msxml2.XMLSchemaCache.4.0"));
// load fictionbook schema
scol->add(FBNS,(const wchar_t *)U::GetProgDirFile(L"FictionBook.xsd"));
// create a SAX reader
MSXML2::ISAXXMLReaderPtr rdr;
CheckError(rdr.CreateInstance(L"Msxml2.SAXXMLReader.4.0"));
// attach a schema
rdr->putFeature(L"schema-validation",VARIANT_TRUE);
rdr->putProperty(L"schemas",scol.GetInterfacePtr());
rdr->putFeature(L"exhaustive-errors",VARIANT_TRUE);
// create an error handler
CComObject<SAXErrorHandler> *ehp;
CheckError(CComObject<SAXErrorHandler>::CreateInstance(&ehp));
CComPtr<CComObject<SAXErrorHandler> > eh(ehp);
rdr->putErrorHandler(eh);
// construct the document
MSXML2::IXMLDOMDocument2Ptr ndoc(CreateDOMImp(_Settings.KeepEncoding() ? m_encoding : _Settings.GetDefaultEncoding()));
// reparse the document
IStreamPtr isp(ndoc);
HRESULT hr=rdr->raw_parse(_variant_t((IUnknown *)isp));
bool bErrSave = false;
if (FAILED(hr)) {
if (!eh->m_msg.IsEmpty()) {
// record error position
if (errline)
*errline=eh->m_line;
if (errcol)
*errcol=eh->m_col;
if (fValidateOnly)
::MessageBeep(MB_ICONERROR);
else
{
if(IDYES == U::MessageBox(MB_YESNO|MB_DEFBUTTON2|MB_ICONERROR, IDS_VALIDATION_FAIL_CPT, IDS_VALIDATION_FAIL_MSG, eh->m_msg))
{
bErrSave = true;
goto forcesave;
}
}
::SendMessage(m_frame,AU::WM_SETSTATUSTEXT,0,
(LPARAM)(const TCHAR *)eh->m_msg);
} else
U::ReportError(hr);
return false;
}
if (fValidateOnly)
{
wchar_t buf[MAX_LOAD_STRING + 1];
::LoadString(_Module.GetResourceInstance(), IDS_SB_NO_ERR, buf, MAX_LOAD_STRING);
::SendMessage(m_frame,AU::WM_SETSTATUSTEXT, 0, (LPARAM)buf);
::MessageBeep(MB_OK);
return true;
}
forcesave:
// now save it
// create tmp filename
CString path(filename);
int cp=path.ReverseFind(_T('\\'));
if (cp<0)
path=_T(".\\");
else
path.Delete(cp,path.GetLength()-cp);
CString buf;
TCHAR *bp=buf.GetBuffer(MAX_PATH);
UINT uv=::GetTempFileName(path,_T("fbe"),0,bp);
if (uv==0)
throw _com_error(HRESULT_FROM_WIN32(::GetLastError()));
buf.ReleaseBuffer();
// added by SeNS: replace all nbsp - non-breaking spaces
if (_Settings.GetNBSPChar().Compare(L"\u00A0") != 0)
{
MSXML2::IXMLDOMNodePtr node = ndoc->firstChild;
CString nbsp = _Settings.GetNBSPChar();
while (node && node!=ndoc)
{
if (node->nodeType==3)
{
CString s = node->nodeValue;
int n = s.Replace( _Settings.GetNBSPChar(), L"\u00A0");
int k = s.Replace(L"<p>\u00A0</p>", L"<empty-line/>");
if (n || k)
{
node->nodeValue = s.AllocSysString();
}
}
if (node->firstChild)
node=node->firstChild;
else
{
while (node && node!=ndoc && node->nextSibling==NULL) node=node->parentNode;
if (node && node!=ndoc) node=node->nextSibling;
}