-
Notifications
You must be signed in to change notification settings - Fork 4
/
FBEview.cpp
4214 lines (3645 loc) · 102 KB
/
FBEview.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
// FBEView.cpp : implementation of the CFBEView class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "res1.h"
#include "utils.h"
#include "apputils.h"
#include "FBEView.h"
#include "SearchReplace.h"
#include "Scintilla.h"
#include "ElementDescMnr.h"
extern CElementDescMnr _EDMnr;
// normalization helpers
static void PackText(MSHTML::IHTMLElement2Ptr elem,MSHTML::IHTMLDocument2 *doc);
static void KillDivs(MSHTML::IHTMLElement2Ptr elem);
static void FixupParagraphs(MSHTML::IHTMLElement2Ptr elem);
static void RelocateParagraphs(MSHTML::IHTMLDOMNode *node);
static void KillStyles(MSHTML::IHTMLElement2Ptr elem);
_ATL_FUNC_INFO CFBEView::DocumentCompleteInfo=
{ CC_STDCALL, VT_EMPTY, 2, { VT_DISPATCH, (VT_BYREF | VT_VARIANT) } };
_ATL_FUNC_INFO CFBEView::BeforeNavigateInfo=
{ CC_STDCALL, VT_EMPTY, 7, {
VT_DISPATCH,
(VT_BYREF | VT_VARIANT),
(VT_BYREF | VT_VARIANT),
(VT_BYREF | VT_VARIANT),
(VT_BYREF | VT_VARIANT),
(VT_BYREF | VT_VARIANT),
(VT_BYREF | VT_BOOL),
}
};
_ATL_FUNC_INFO CFBEView::VoidInfo=
{ CC_STDCALL, VT_EMPTY, 0 };
_ATL_FUNC_INFO CFBEView::EventInfo=
{ CC_STDCALL, VT_BOOL, 1, { VT_DISPATCH } };
_ATL_FUNC_INFO CFBEView::VoidEventInfo=
{ CC_STDCALL, VT_EMPTY, 1, { VT_DISPATCH } };
LRESULT CFBEView::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (DefWindowProc(uMsg,wParam,lParam))
return 1;
if (!SUCCEEDED(QueryControl(&m_browser)))
return 1;
// register browser events handler
BrowserEvents::DispEventAdvise(m_browser,&DIID_DWebBrowserEvents2);
return 0;
}
CFBEView::~CFBEView()
{
if(HasDoc())
{
DocumentEvents::DispEventUnadvise(Document(), &DIID_HTMLDocumentEvents2);
TextEvents::DispEventUnadvise(Document()->body, &DIID_HTMLTextContainerEvents2);
m_mkc->UnRegisterForDirtyRange(m_dirtyRangeCookie);
}
if(m_browser)
BrowserEvents::DispEventUnadvise(m_browser, &DIID_DWebBrowserEvents2);
if(m_find_dlg)
{
CloseFindDialog(m_find_dlg);
delete m_find_dlg;
}
}
BOOL CFBEView::PreTranslateMessage(MSG* pMsg)
{
return SendMessage(WM_FORWARDMSG,0,(LPARAM)pMsg)!=0;
}
// editing commands
LRESULT CFBEView::ExecCommand(int cmd) {
IOleCommandTargetPtr ct(m_browser);
if (ct)
ct->Exec(&CGID_MSHTML,cmd,0,NULL,NULL);
return 0;
}
void CFBEView::QueryStatus(OLECMD *cmd,int ncmd) {
IOleCommandTargetPtr ct(m_browser);
if (ct)
ct->QueryStatus(&CGID_MSHTML,ncmd,cmd,NULL);
}
CString CFBEView::QueryCmdText(int cmd) {
IOleCommandTargetPtr ct(m_browser);
if (ct) {
OLECMD oc={cmd};
struct {
OLECMDTEXT oct;
wchar_t buffer[512];
} oct={ { OLECMDTEXTF_NAME, 0, 512 } };
if (SUCCEEDED(ct->QueryStatus(&CGID_MSHTML,1,&oc,&oct.oct)))
return oct.oct.rgwz;
}
return CString();
}
LRESULT CFBEView::OnStyleLink(WORD, WORD, HWND, BOOL&) {
try {
if (Document()->execCommand(L"CreateLink",VARIANT_FALSE,_variant_t(L""))==VARIANT_TRUE)
{
::SendMessage(m_frame,WM_COMMAND,MAKELONG(0,IDN_SEL_CHANGE),(LPARAM)m_hWnd);
::SendMessage(m_frame,WM_COMMAND,MAKELONG(IDC_HREF,IDN_WANTFOCUS),(LPARAM)m_hWnd);
}
}
catch (_com_error&) { }
return 0;
}
LRESULT CFBEView::OnStyleFootnote(WORD, WORD, HWND, BOOL&) {
try {
m_mk_srv->BeginUndoUnit(L"Create Footnote");
if (Document()->execCommand(L"CreateLink",VARIANT_FALSE,_variant_t(L""))==VARIANT_TRUE) {
MSHTML::IHTMLTxtRangePtr r(Document()->selection->createRange());
MSHTML::IHTMLElementPtr pe(r->parentElement());
if (U::scmp(pe->tagName,L"A")==0)
pe->className=L"note";
}
m_mk_srv->EndUndoUnit();
::SendMessage(m_frame,WM_COMMAND,MAKELONG(0,IDN_SEL_CHANGE),(LPARAM)m_hWnd);
::SendMessage(m_frame,WM_COMMAND,MAKELONG(IDC_HREF,IDN_WANTFOCUS),(LPARAM)m_hWnd);
}
catch (_com_error&) { }
return 0;
}
bool CFBEView::CheckCommand(WORD wID)
{
if (!m_normalize)
return false;
switch (wID) {
case ID_EDIT_ADD_BODY:
return true;
case ID_EDIT_ADD_TITLE:
return bCall(L"AddTitle",SelectionStructCon());
case ID_EDIT_CLONE:
return bCall(L"CloneContainer",SelectionStructCon());
case ID_STYLE_NORMAL:
return bCall(L"StyleNormal",SelectionStructCon());
case ID_STYLE_SUBTITLE:
return bCall(L"StyleSubtitle",SelectionStructCon());
case ID_STYLE_TEXTAUTHOR:
return bCall(L"StyleTextAuthor",SelectionStructCon());
case ID_EDIT_INS_IMAGE:
return bCall(L"InsImage") && !SelectionStructCode() && !SelectionHasTags(L"SPAN");
case ID_EDIT_INS_INLINEIMAGE:
return bCall(L"InsInlineImage");
case ID_EDIT_ADD_IMAGE:
return bCall(L"AddImage", SelectionStructCon()) && !SelectionStructCode() && !SelectionHasTags(L"SPAN");
case ID_EDIT_ADD_EPIGRAPH:
return bCall(L"AddEpigraph",SelectionStructCon());
case ID_EDIT_ADD_ANN:
return bCall(L"AddAnnotation",SelectionStructCon());
case ID_EDIT_SPLIT:
return SplitContainer(true);
case ID_EDIT_INS_POEM:
return InsertPoem(true);
case ID_EDIT_INS_CITE:
return InsertCite(true);
case ID_EDIT_CODE:
{
_variant_t params[3] =
{
Document()->selection->createRange().GetInterfacePtr(),
SelectionStructCon().GetInterfacePtr(),
true
};
return bCall(L"StyleCode", 3, params);
}
case ID_INSERT_TABLE:
return InsertTable(true);
case ID_GOTO_FOOTNOTE:
return (GoToFootnote(true) | GoToReference(true));
case ID_GOTO_REFERENCE:
return GoToReference(true);
case ID_EDIT_ADD_TA:
return bCall(L"AddTA",SelectionStructCon());
case ID_EDIT_MERGE:
return bCall(L"MergeContainers",SelectionStructCon());
case ID_EDIT_REMOVE_OUTER_SECTION:
return bCall(L"RemoveOuterContainer",SelectionStructCon());
case ID_STYLE_LINK:
case ID_STYLE_NOTE:
try {
return Document()->queryCommandEnabled(L"CreateLink")==VARIANT_TRUE;
}
catch (_com_error) { }
break;
}
return false;
}
bool CFBEView::CheckSetCommand(WORD wID) {
if (!m_normalize)
return false;
switch (wID)
{
case ID_EDIT_CODE:
return bCall(L"IsCode", SelectionStructCode());
}
return false;
}
// changes tracking
MSHTML::IHTMLDOMNodePtr CFBEView::GetChangedNode() {
MSHTML::IMarkupPointerPtr p1,p2;
m_mk_srv->CreateMarkupPointer(&p1);
m_mk_srv->CreateMarkupPointer(&p2);
m_mkc->GetAndClearDirtyRange(m_dirtyRangeCookie,p1,p2);
MSHTML::IHTMLElementPtr e1,e2;
p1->CurrentScope(&e1);
p2->CurrentScope(&e2);
p1.Release();
p2.Release();
while ((bool)e1 && e1!=e2 && e1->contains(e2)!=VARIANT_TRUE)
e1=e1->parentElement;
return e1;
}
static bool IsEmptyNode(MSHTML::IHTMLDOMNode *node) {
if (node->nodeType!=1)
return false;
_bstr_t name(node->nodeName);
if (U::scmp(name,L"BR")==0)
return false;
if (U::scmp(name,L"P")==0) // the editor uses empty Ps to represent empty lines
return false;
/* if (U::scmp(name,L"EM")==0) // конвертеры иногда обрамляют пробелы тегами <emphasis> и <strong>
return false;
if (U::scmp(name,L"STRONG")==0) // конвертеры иногда обрамляют пробелы тегами <emphasis> и <strong>
return false;*/
// images are always empty
if (U::scmp(name,L"DIV")==0 && U::scmp(MSHTML::IHTMLElementPtr(node)->className,L"image")==0)
return false;
if (U::scmp(name,L"IMG")==0)
return false;
if (node->hasChildNodes()==VARIANT_FALSE)
return true;
if (U::scmp(name,L"A")==0) // links can be meaningful even if the contain only ws
return false;
if ((bool)node->firstChild->nextSibling)
return false;
if (node->firstChild->nodeType!=3)
return false;
if (U::is_whitespace(node->firstChild->nodeValue.bstrVal))
return true;
return false;
}
// Remove empty leaf nodes
static void RemoveEmptyNodes(MSHTML::IHTMLDOMNode *node) {
if (node->nodeType!=1)
return;
MSHTML::IHTMLDOMNodePtr cur(node->firstChild);
while (cur)
{
MSHTML::IHTMLDOMNodePtr next;
try { next = cur->nextSibling; } catch(...) { return; }
RemoveEmptyNodes(cur);
if(IsEmptyNode(cur))
cur->removeNode(VARIANT_TRUE);
cur=next;
}
}
// Find parent DIV
static MSHTML::IHTMLElementPtr GetHP(MSHTML::IHTMLElementPtr hp)
{
while((bool)hp && U::scmp(hp->tagName,L"DIV"))
hp = hp->parentElement;
return hp;
}
// Splitting
bool CFBEView::SplitContainer(bool fCheck)
{
try
{
MSHTML::IHTMLTxtRangePtr rng(Document()->selection->createRange());
if(!(bool)rng)
return false;
MSHTML::IHTMLElementPtr pe(rng->parentElement());
while((bool)pe && U::scmp(pe->tagName, L"DIV"))
pe = pe->parentElement;
if(!(bool)pe || (U::scmp(pe->className, L"section") && U::scmp(pe->className, L"stanza")))
return false;
MSHTML::IHTMLTxtRangePtr r2(rng->duplicate());
r2->moveToElementText(pe);
if(rng->compareEndPoints(L"StartToStart", r2) == 0)
return false;
MSHTML::IHTMLTxtRangePtr r3(rng->duplicate());
r3->collapse(true);
MSHTML::IHTMLTxtRangePtr r4(rng->duplicate());
r4->collapse(false);
if(!(bool)pe || GetHP(r3->parentElement()) != pe || GetHP(r4->parentElement()) != pe)
return false;
if(fCheck)
return true;
// At this point we are ready to split
// Create an undo unit
CString name(L"split ");
name += (const wchar_t*)pe->className;
m_mk_srv->BeginUndoUnit((TCHAR*)(const TCHAR*)name);
//// Create a new element
MSHTML::IHTMLElementPtr ne(Document()->createElement(L"DIV"));
ne->className = pe->className;
_bstr_t className = pe->className;
// SeNS: issue #153
_bstr_t id = pe->id;
pe->id = L"";
MSHTML::IHTMLElementPtr peTitle(Document()->createElement(L"DIV"));
MSHTML::IHTMLElementCollectionPtr peColl = pe->children;
{
MSHTML::IHTMLElementPtr peChild = peColl->item(0);
if(!U::scmp(peChild->tagName, L"DIV") && !U::scmp(peChild->className, L"title"))
peTitle->innerHTML = peChild->outerHTML;
else
peTitle = NULL;
}
// Create and position markup pointers
MSHTML::IMarkupPointerPtr selstart, selend, elembeg, elemend;
m_mk_srv->CreateMarkupPointer(&selstart);
m_mk_srv->CreateMarkupPointer(&selend);
m_mk_srv->CreateMarkupPointer(&elembeg);
m_mk_srv->CreateMarkupPointer(&elemend);
MSHTML::IHTMLTxtRangePtr titleRng(rng->duplicate());
m_mk_srv->MovePointersToRange(titleRng, selstart, selend);
U::ElTextHTML title(titleRng->htmlText, titleRng->text);
MSHTML::IHTMLTxtRangePtr preRng(rng->duplicate());
elembeg->MoveAdjacentToElement(pe, MSHTML::ELEM_ADJ_AfterBegin);
m_mk_srv->MoveRangeToPointers(elembeg, selstart, preRng);
U::ElTextHTML pre(preRng->htmlText, preRng->text);
MSHTML::IHTMLElementCollectionPtr peChilds = pe->children;
MSHTML::IHTMLElementPtr elLast = peChilds->item(peChilds->length - 1);
if(U::scmp(elLast->innerText, L"") == 0)
elLast->innerText = L"123";
MSHTML::IHTMLTxtRangePtr postRng(rng->duplicate());
elemend->MoveAdjacentToElement(pe, MSHTML::ELEM_ADJ_BeforeEnd);
m_mk_srv->MoveRangeToPointers(selend, elemend, postRng);
U::ElTextHTML post(postRng->htmlText, postRng->text);
// Check if title needs to be created and further text to be copied
bool fTitle = !title.text.IsEmpty();
bool fContent = !post.html.IsEmpty();
if(fTitle && title.html.Find(L"<P") == -1)
title.html = CString(L"<P>") + title.html + CString(L"</P>");
if(fContent && post.html.Find(L"<P") == -1)
post.html = CString(L"<P>") + post.html + CString(L"</P>");
title.html.Remove(L'\r');
title.html.Remove(L'\n');
post.html.Remove(L'\r');
post.html.Remove(L'\n');
if(post.html.Find(L"<P> </P>") == 0
&& post.html.GetLength() > 13
&& fTitle
&& title.html.Find(L"<P> </P>") != title.html.GetLength() -14)
post.html.Delete(0, 13);
if(post.html.Find(L"<P>123</P>") != -1)
post.html.Replace(L"<P>123</P>", L"<P> </P>");
// Insert it after pe
MSHTML::IHTMLElement2Ptr(pe)->insertAdjacentElement(L"afterEnd", ne);
// Move content or create new
if(fContent)
{
// Create and position destination markup pointer
if(post.html == L"<P> </P>")
post.html += L"<P> </P>";
ne->innerHTML = post.html.AllocSysString();
// SeNS: issue #153
ne->id = id;
}
else
{
MSHTML::IHTMLElementPtr para(Document()->createElement(L"P"));
MSHTML::IHTMLElement3Ptr(para)->inflateBlock = VARIANT_TRUE;
MSHTML::IHTMLElement2Ptr(ne)->insertAdjacentElement(L"beforeEnd", para);
}
// Create and move title if needed
if(fTitle)
{
MSHTML::IHTMLElementPtr elTitle(Document()->createElement(L"DIV"));
elTitle->className = L"title";
MSHTML::IHTMLElement2Ptr(ne)->insertAdjacentElement(L"afterBegin", elTitle);
// Create and position destination markup pointer
elTitle->innerHTML = title.html.AllocSysString();
// Delete all containers from title
KillDivs(elTitle);
KillStyles(elTitle);
}
if(pre.html.Find(L"<P") == -1)
{
if(pre.html == L"")
pre.html = L"<P> </P>";
else
pre.html = CString(L"<P>") + pre.html + CString(L"</P>");
}
pe->innerHTML = pre.html.AllocSysString();
// Ensure we have good html
FixupParagraphs(ne);
PackText(ne, Document());
peColl = pe->children;
if(peColl->length == 1)
{
MSHTML::IHTMLElementPtr peChild = peColl->item(0);
if(!U::scmp(peChild->tagName, L"DIV") && !U::scmp(peChild->className, className.GetBSTR()))
m_mk_srv->RemoveElement(peChild);
}
MSHTML::IHTMLElementCollectionPtr neColl = ne->children;
if(neColl->length == 1)
{
MSHTML::IHTMLElementPtr neChild = neColl->item(0);
if(!U::scmp(neChild->tagName, L"DIV") && !U::scmp(neChild->className, className.GetBSTR()))
m_mk_srv->RemoveElement(neChild);
}
CString peTitSect;
if(peTitle)
{
peTitSect = peTitle->innerHTML.GetBSTR();
peTitSect += L"<P> </P>";
}
CString b = pe->innerText;
b.Remove(L'\r');
b.Remove(L'\n');
CString c = peTitle ? peTitle->innerText : L"";
c.Remove(L'\r');
c.Remove(L'\n');
if(peTitle && !U::scmp(b, c))
pe->innerHTML = peTitSect.AllocSysString();
// Close undo unit
m_mk_srv->EndUndoUnit();
// Move cursor to newly created item
GoTo(ne, false);
}
catch (_com_error& e)
{
U::ReportError(e);
}
return false;
}
// cleaning up html
static void KillDivs(MSHTML::IHTMLElement2Ptr elem) {
MSHTML::IHTMLElementCollectionPtr divs(elem->getElementsByTagName(L"DIV"));
while (divs->length>0)
MSHTML::IHTMLDOMNodePtr(divs->item(0L))->removeNode(VARIANT_FALSE);
}
static void KillStyles(MSHTML::IHTMLElement2Ptr elem) {
MSHTML::IHTMLElementCollectionPtr ps(elem->getElementsByTagName(L"P"));
for (long l=0;l<ps->length;++l)
CheckError(MSHTML::IHTMLElementPtr(ps->item(l))->put_className(NULL));
}
//////////////////////////////////////////////////////////////////////////////
/// @fn static bool MergeEqualHTMLElements(MSHTML::IHTMLDOMNode *node)
///
/// функция объединяет стоящие рядом одинаковые HTML элементы
///
/// @params MSHTML::IHTMLDOMNode *node [in, out] - нода, внутри которой будет производиться преобразование
///
/// @note сливаются следующие элементы: EM, STRONG
/// при этом пробельные символы, располагающиеся между закрывающем и открывающим тегами остаются, т.е.
/// '<EM>хороший</EM> <EM>пример</EM>' преобразуется в '<EM>хороший пример</EM>'
///
/// @author Ильин Иван @date 31.03.08
//////////////////////////////////////////////////////////////////////////////
static bool MergeEqualHTMLElements(MSHTML::IHTMLDOMNode *node, MSHTML::IHTMLDocument2 *doc)
{
if (node->nodeType != 1) // Element node
return false;
bool fRet=false;
MSHTML::IHTMLDOMNodePtr cur(node->firstChild);
while ((bool)cur)
{
MSHTML::IHTMLDOMNodePtr next;
try { next = cur->nextSibling; } catch(...) { return false; }
if (MergeEqualHTMLElements(cur,doc))
{
cur = node->firstChild;
continue;
}
// если нет следующего элемента, то сливать будет несчем
if(!(bool)next)
return false;
_bstr_t name(cur->nodeName);
MSHTML::IHTMLElementPtr curelem(cur);
MSHTML::IHTMLElementPtr nextElem(next);
if (U::scmp(name,L"EM")==0 || U::scmp(name,L"STRONG")==0)
{
// отлавливаем ситуацию с пробелом, обрамленным тегами EM т.д.
bstr_t curText = curelem->innerText;
if(curText.length() == 0 || U::is_whitespace(curelem->innerText))
{
// удаляем обрамляющие теги
MSHTML::IHTMLDOMNodePtr prev = cur->previousSibling;
if((bool)prev)
{
if(prev->nodeType == 3)//text
{
prev->nodeValue = (bstr_t)prev->nodeValue.bstrVal + curelem->innerText;
}
else
{
MSHTML::IHTMLElementPtr prevElem(prev);
prevElem->innerHTML = prevElem->innerHTML + curelem->innerText;
}
cur->removeNode(VARIANT_TRUE);
cur = prev;
continue;
}
if((bool)next)
{
MSHTML::IHTMLDOMNodePtr parent = cur->parentNode;
if(next->nodeType == 3)//text
{
next->nodeValue = (bstr_t)curelem->innerText + next->nodeValue.bstrVal;
}
else
{
MSHTML::IHTMLElementPtr nextElem(next);
nextElem->innerHTML = curelem->innerText + nextElem->innerHTML;
}
cur->removeNode(VARIANT_TRUE);
cur = parent->firstChild;
continue;
}
}
if(next->nodeType == 3) // TextNode
{
MSHTML::IHTMLDOMNodePtr afterNext(next->nextSibling);
if(!(bool)afterNext)
{
cur = next;
continue;
}
MSHTML::IHTMLElementPtr afterNextElem(afterNext);
bstr_t afterNextName = afterNext->nodeName;
if(U::scmp(name, afterNextName))// если следующий элемент другого типа
{
cur = next;
continue;
}
// проверяем между одинаковыми элементами стоят одни пробелы
if(!U::is_whitespace(next->nodeValue.bstrVal))
{
cur = next;
continue; // <EM>123</EM>45<EM>678</EM> абсолютно нормальная ситуация
}
// объединяем элементы
MSHTML::IHTMLElementPtr newelem(doc->createElement(name));
MSHTML::IHTMLDOMNodePtr newnode(newelem);
newelem->innerHTML = curelem->innerHTML + next->nodeValue.bstrVal + afterNextElem->innerHTML;
cur->replaceNode(newnode);
afterNext->removeNode(VARIANT_TRUE);
next->removeNode(VARIANT_TRUE);
cur = newnode;
fRet=true;
}
else
{
bstr_t nextName(next->nodeName);
if(U::scmp(name, nextName))// если следующий элемент другого типа
{
cur = next;
continue;
}
// объединяем элементы
MSHTML::IHTMLElementPtr newelem(doc->createElement(name));
MSHTML::IHTMLDOMNodePtr newnode(newelem);
newelem->innerHTML = curelem->innerHTML + nextElem->innerHTML;
cur->replaceNode(newnode);
next->removeNode(VARIANT_TRUE);
cur = newnode;
fRet=true;
continue;
}
}
cur=next;
}
return fRet;
}
static bool RemoveUnk(MSHTML::IHTMLDOMNode *node, MSHTML::IHTMLDocument2 *doc) {
if (node->nodeType!=1) // Element node
return false;
bool fRet=false;
restart:
MSHTML::IHTMLDOMNodePtr cur(node->firstChild);
while ((bool)cur)
{
MSHTML::IHTMLDOMNodePtr next;
try { next = cur->nextSibling; } catch(...) { return false; }
if (RemoveUnk(cur,doc))
goto restart;
_bstr_t name(cur->nodeName);
MSHTML::IHTMLElementPtr curelem(cur);
if (U::scmp(name,L"B")==0 || U::scmp(name,L"I")==0) {
const wchar_t *newname=U::scmp(name,L"B")==0 ? L"STRONG" : L"EM";
MSHTML::IHTMLElementPtr newelem(doc->createElement(newname));
MSHTML::IHTMLDOMNodePtr newnode(newelem);
newelem->innerHTML=curelem->innerHTML;
cur->replaceNode(newnode);
cur=newnode;
fRet=true;
goto restart;
}
CString text;
if (curelem != NULL)
text.SetString(curelem->outerHTML);
if (U::scmp(name,L"P") && U::scmp(name,L"STRONG") &&
U::scmp(name,L"STRIKE") && U::scmp(name,L"SUP") && U::scmp(name,L"SUB") &&
U::scmp(name,L"EM") && U::scmp(name,L"A") &&
(U::scmp(name,L"SPAN") || U::scmp(curelem->className, L"code")) &&
U::scmp(name,L"#text") && U::scmp(name,L"BR") &&
(U::scmp(name,L"IMG") || U::scmp(curelem->parentElement->className, L"image") &&
// Added by SeNS: inline images support
(U::scmp(name,L"SPAN") || U::scmp(curelem->className, L"image"))))
{
if (U::scmp(name,L"DIV")==0) {
_bstr_t cls(curelem->className);
_bstr_t id(curelem->id);
if (!(U::scmp(cls,L"body") && U::scmp(cls,L"section") &&
U::scmp(cls,L"table") && U::scmp(cls,L"tr") && U::scmp(cls,L"th") && U::scmp(cls,L"td") &&
U::scmp(cls,L"output") && U::scmp(cls,L"part") && U::scmp(cls,L"output-document-class") &&
U::scmp(cls,L"annotation") && U::scmp(cls,L"title") && U::scmp(cls,L"epigraph") &&
U::scmp(cls,L"poem") && U::scmp(cls,L"stanza") && U::scmp(cls,L"cite") &&
U::scmp(cls,L"date") &&
U::scmp(cls,L"history") && U::scmp(cls,L"image")&&
U::scmp(cls,L"code") &&
U::scmp(id,L"fbw_desc") && U::scmp(id,L"fbw_body") && U::scmp(id,L"fbw_updater")))
goto ok;
}
CElementDescriptor* ED;
if(_EDMnr.GetElementDescriptor(cur, &ED))
goto ok;
MSHTML::IHTMLDOMNodePtr ce(cur->previousSibling);
cur->removeNode(VARIANT_FALSE);
if (ce)
next=ce->nextSibling;
else
next=node->firstChild;
}
ok:
cur=next;
}
return fRet;
}
// move the paragraph up one level
void MoveUp(bool fCopyFmt,MSHTML::IHTMLDOMNodePtr& node) {
MSHTML::IHTMLDOMNodePtr parent(node->parentNode);
MSHTML::IHTMLElement2Ptr elem(parent);
// clone parent (it can be A/EM/STRONG/SPAN)
if (fCopyFmt) {
MSHTML::IHTMLDOMNodePtr clone(parent->cloneNode(VARIANT_FALSE));
while ((bool)node->firstChild)
clone->appendChild(node->firstChild);
node->appendChild(clone);
}
// clone parent once more and move siblings after node to it
if ((bool)node->nextSibling) {
MSHTML::IHTMLDOMNodePtr clone(parent->cloneNode(VARIANT_FALSE));
while ((bool)node->nextSibling)
clone->appendChild(node->nextSibling);
elem->insertAdjacentElement(L"afterEnd",MSHTML::IHTMLElementPtr(clone));
if (U::scmp(parent->nodeName,L"P")==0)
MSHTML::IHTMLElement3Ptr(clone)->inflateBlock=VARIANT_TRUE;
}
// now move node to parent level, the tree may be in some weird state
node->removeNode(VARIANT_TRUE); // delete from tree
node=elem->insertAdjacentElement(L"afterEnd",MSHTML::IHTMLElementPtr(node));
}
void BubbleUp(MSHTML::IHTMLDOMNode *node,const wchar_t *name) {
MSHTML::IHTMLElement2Ptr elem(node);
MSHTML::IHTMLElementCollectionPtr elements(elem->getElementsByTagName(name));
long len=elements->length;
for (long i=0;i<len;++i) {
MSHTML::IHTMLDOMNodePtr ce(elements->item(i));
if (!(bool)ce)
break;
for (int ll=0;ce->parentNode!=node && ll<30;++ll)
MoveUp(true,ce);
MoveUp(false,ce);
}
}
#if (1)
// split paragraphs containing BR elements
static void SplitBRs(MSHTML::IHTMLElement2Ptr elem)
{
CString text = MSHTML::IHTMLElementPtr(elem)->outerHTML;
if (text.Replace(L"<BR>", L"</P><P>") > 0)
MSHTML::IHTMLElementPtr(elem)->outerHTML = text.AllocSysString();
}
#else
static void SplitBRs(MSHTML::IHTMLElement2Ptr elem) {
MSHTML::IHTMLElementCollectionPtr BRs(elem->getElementsByTagName(L"BR"));
while (BRs->length>0) {
MSHTML::IHTMLDOMNodePtr ce(BRs->item(0L));
if (!(bool)ce)
break;
for (;;) {
MSHTML::IHTMLDOMNodePtr parent(ce->parentNode);
if (!(bool)parent) // no parent? huh?
goto blowit;
_bstr_t name(parent->nodeName);
if (U::scmp(name,L"P")==0 || U::scmp(name,L"DIV")==0)
break;
if (U::scmp(name,L"BODY")==0)
goto blowit;
MoveUp(false,ce);
}
MoveUp(false,ce);
blowit:
ce->removeNode(VARIANT_TRUE);
}
}
#endif
// this sub should locate any nested paragraphs and bubble them up
static void RelocateParagraphs(MSHTML::IHTMLDOMNode *node) {
if (node->nodeType!=1)
return;
MSHTML::IHTMLDOMNodePtr cur(node->firstChild);
while (cur) {
if (cur->nodeType==1) {
if (!U::scmp(cur->nodeName,L"P")) {
BubbleUp(cur,L"P");
BubbleUp(cur,L"DIV");
} else
RelocateParagraphs(cur);
}
cur=cur->nextSibling;
}
}
static bool IsStanza(MSHTML::IHTMLDOMNode *node) {
MSHTML::IHTMLElementPtr elem(node);
return U::scmp(elem->className,L"stanza")==0;
}
// Move text content in DIV items to P elements, so DIVs can
// contain P and DIV only
static void PackText(MSHTML::IHTMLElement2Ptr elem, MSHTML::IHTMLDocument2* doc)
{
MSHTML::IHTMLElementCollectionPtr elements(elem->getElementsByTagName(L"DIV"));
for(long i = 0; i < elements->length; ++i)
{
MSHTML::IHTMLDOMNodePtr div(elements->item(i));
if(U::scmp(MSHTML::IHTMLElementPtr(div)->className, L"image") == 0)
continue;
MSHTML::IHTMLDOMNodePtr cur(div->firstChild);
while((bool)cur)
{
_bstr_t cur_name(cur->nodeName);
if (U::scmp(cur_name, L"P") && U::scmp(cur_name, L"DIV"))
{
// create a paragraph from a run of !P && !DIV
MSHTML::IHTMLElementPtr newp(doc->createElement(L"P"));
MSHTML::IHTMLDOMNodePtr newn(newp);
cur->replaceNode(newn);
newn->appendChild(cur);
while ((bool)newn->nextSibling)
{
cur_name = newn->nextSibling->nodeName;
if (U::scmp(cur_name, L"P") == 0 || U::scmp(cur_name, L"DIV") == 0)
break;
newn->appendChild(newn->nextSibling);
}
cur = newn->nextSibling;
}
else
cur = cur->nextSibling;
}
}
}
static void FixupLinks(MSHTML::IHTMLDOMNode *dom) {
MSHTML::IHTMLElement2Ptr elem(dom);
if (!(bool)elem)
return;
MSHTML::IHTMLElementCollectionPtr coll(elem->getElementsByTagName(L"a"));
if (!(bool)coll)
return;
if (coll->length == 0) coll = elem->getElementsByTagName(L"A");
for (long l=0;l<coll->length;++l) {
MSHTML::IHTMLElementPtr a(coll->item(l));
if (!(bool)a)
continue;
_variant_t href(a->getAttribute(L"href",2));
if (V_VT(&href)==VT_BSTR && V_BSTR(&href) &&
::SysStringLen(V_BSTR(&href))>11 &&
memcmp(V_BSTR(&href),L"file://",6*sizeof(wchar_t))==0)
{
wchar_t* pos = wcschr((wchar_t*)V_BSTR(&href), L'#');
if(!pos)
continue;
a->setAttribute(L"href",pos,0);
}
}
}
bool CFBEView::InsertPoem(bool fCheck)
{
try
{
MSHTML::IHTMLTxtRangePtr rng(Document()->selection->createRange());
if(!(bool)rng)
return false;
MSHTML::IHTMLElementPtr pe(GetHP(rng->parentElement()));
if(!(bool)pe)
return false;
// Get parents for start and end ranges and ensure they are the same as pe
MSHTML::IHTMLTxtRangePtr tr(rng->duplicate());
tr->collapse(VARIANT_TRUE);
if (GetHP(tr->parentElement()) != pe)
return false;
// Check if it possible to insert a poem there
_bstr_t cls(pe->className);
if(U::scmp(cls, L"section")
&& U::scmp(cls, L"epigraph")
&& U::scmp(cls, L"annotation")
&& U::scmp(cls, L"history")
&& U::scmp(cls, L"cite"))
return false;
// Preventing double expanding whether checked or actual executed
MSHTML::IHTMLElementPtr elBegin, elEnd;
MSHTML::IHTMLDOMNodePtr begin, end;
if(!ExpandTxtRangeToParagraphs(rng, elBegin, elEnd))
return false;
else
{
begin = elBegin;
end = elEnd;
}
// All checks passed
if(fCheck)
return true;
m_mk_srv->BeginUndoUnit(L"insert poem");
CString rngHTML;
MSHTML::IHTMLDOMNodePtr sibling = begin;
do
{
rngHTML += MSHTML::IHTMLElementPtr(sibling)->outerHTML.GetBSTR();
if(sibling == end)
break;
}
while((sibling = sibling->nextSibling));
MSHTML::IHTMLElementPtr ne(Document()->createElement(L"<DIV class=poem>"));
if(!U::scmp(rng->text.GetBSTR(), L""))
{
MSHTML::IHTMLElementPtr se(Document()->createElement(L"<DIV class=stanza>"));
se->innerHTML = L"<P> </P>";
ne->innerHTML = se->outerHTML;
}
else
{
MSHTML::IHTMLElementPtr acc(Document()->createElement(L"DIV"));
acc->innerHTML = rngHTML.AllocSysString();
MSHTML::IHTMLElementCollectionPtr coll = acc->children;
bool trim = true;
CString stanzaHTML;
for(int i = 0; i < coll->length; ++i)
{
MSHTML::IHTMLElementPtr curr = coll->item(i);
CString line = curr->innerText;
// changed by SeNS: issue #61
if (line.Trim().IsEmpty())
{
if(trim)
continue;
else
{
MSHTML::IHTMLElementPtr se(Document()->createElement(L"<DIV class=stanza>"));
se->innerHTML = stanzaHTML.AllocSysString();
MSHTML::IHTMLElement2Ptr(ne)->insertAdjacentElement(L"beforeEnd", se);
stanzaHTML = L"";
trim = true;
}
}
else
{
if(!U::scmp(curr->tagName, L"DIV"))
{
if(curr->innerText.GetBSTR())
{
stanzaHTML += CString(L"<P>") + curr->innerText.GetBSTR() + CString(L"</P>");
}
else
continue;